Skip to content

Commit

Permalink
Looping through keys (#7)
Browse files Browse the repository at this point in the history
- Implement \Countable with KeySet
- Implement \IteratorAggregate with KeySet
  • Loading branch information
Strobotti authored Apr 1, 2020
1 parent b589a25 commit a78580b
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 2 deletions.
20 changes: 18 additions & 2 deletions src/KeySet.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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()));
}

Expand Down Expand Up @@ -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);
}
}
38 changes: 38 additions & 0 deletions tests/KeySetTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}

0 comments on commit a78580b

Please sign in to comment.