diff --git a/src/KeySet.php b/src/KeySet.php index c739fb7..efaf0c5 100644 --- a/src/KeySet.php +++ b/src/KeySet.php @@ -13,7 +13,7 @@ * @see https://github.com/Strobotti/php-jwk * @since 1.0.0 */ -class KeySet implements \JsonSerializable +class KeySet implements \JsonSerializable, \Countable, \IteratorAggregate { /** * @var KeyFactory @@ -84,7 +84,7 @@ public function getKeyById(string $kid, string $use = KeyInterface::PUBLIC_KEY_U */ public function addKey(KeyInterface $key): self { - if ($this->containsKey($key->getKeyId(), $key->getPublicKeyUse())) { + if ($key->getKeyId() && $this->containsKey($key->getKeyId(), $key->getPublicKeyUse())) { throw new \InvalidArgumentException(\sprintf('Key with id `%s` and use `%s` already exists in the set', $key->getKeyId(), $key->getPublicKeyUse())); } @@ -116,4 +116,20 @@ public function jsonSerialize(): array 'keys' => \array_values($ret), ]; } + + /** + * @since 1.3.0 + */ + public function count(): int + { + return \count($this->keys); + } + + /** + * @since 1.3.0 + */ + public function getIterator(): \ArrayIterator + { + return new \ArrayIterator($this->keys); + } } diff --git a/tests/KeySetTest.php b/tests/KeySetTest.php index 2130c1c..2729ed5 100644 --- a/tests/KeySetTest.php +++ b/tests/KeySetTest.php @@ -97,4 +97,42 @@ public function testGetKeyById(): void static::assertNull($keySet->getKeyById('asdf')); } + + public function testCountable(): void + { + $keyset = new KeySet(); + static::assertCount(0, $keyset); + + $keyset->addKey(new Rsa()); + static::assertCount(1, $keyset); + + $keyset->addKey(new Rsa()); + static::assertCount(2, $keyset); + } + + public function testIteratorAggregate(): void + { + $keyset = new KeySet(); + + $count = 0; + + foreach ($keyset as $key) { + ++$count; + } + + static::assertSame(0, $count); + + $keyset->addKey(new Rsa()); + $keyset->addKey(new Rsa()); + $keyset->addKey(new Rsa()); + + foreach ($keyset as $index => $key) { + static::assertInstanceOf(Rsa::class, $key); + static::assertSame($index, $count); + + ++$count; + } + + static::assertSame(3, $count); + } }