Skip to content

Commit a78580b

Browse files
authored
Looping through keys (#7)
- Implement \Countable with KeySet - Implement \IteratorAggregate with KeySet
1 parent b589a25 commit a78580b

File tree

2 files changed

+56
-2
lines changed

2 files changed

+56
-2
lines changed

src/KeySet.php

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
* @see https://github.com/Strobotti/php-jwk
1414
* @since 1.0.0
1515
*/
16-
class KeySet implements \JsonSerializable
16+
class KeySet implements \JsonSerializable, \Countable, \IteratorAggregate
1717
{
1818
/**
1919
* @var KeyFactory
@@ -84,7 +84,7 @@ public function getKeyById(string $kid, string $use = KeyInterface::PUBLIC_KEY_U
8484
*/
8585
public function addKey(KeyInterface $key): self
8686
{
87-
if ($this->containsKey($key->getKeyId(), $key->getPublicKeyUse())) {
87+
if ($key->getKeyId() && $this->containsKey($key->getKeyId(), $key->getPublicKeyUse())) {
8888
throw new \InvalidArgumentException(\sprintf('Key with id `%s` and use `%s` already exists in the set', $key->getKeyId(), $key->getPublicKeyUse()));
8989
}
9090

@@ -116,4 +116,20 @@ public function jsonSerialize(): array
116116
'keys' => \array_values($ret),
117117
];
118118
}
119+
120+
/**
121+
* @since 1.3.0
122+
*/
123+
public function count(): int
124+
{
125+
return \count($this->keys);
126+
}
127+
128+
/**
129+
* @since 1.3.0
130+
*/
131+
public function getIterator(): \ArrayIterator
132+
{
133+
return new \ArrayIterator($this->keys);
134+
}
119135
}

tests/KeySetTest.php

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,4 +97,42 @@ public function testGetKeyById(): void
9797

9898
static::assertNull($keySet->getKeyById('asdf'));
9999
}
100+
101+
public function testCountable(): void
102+
{
103+
$keyset = new KeySet();
104+
static::assertCount(0, $keyset);
105+
106+
$keyset->addKey(new Rsa());
107+
static::assertCount(1, $keyset);
108+
109+
$keyset->addKey(new Rsa());
110+
static::assertCount(2, $keyset);
111+
}
112+
113+
public function testIteratorAggregate(): void
114+
{
115+
$keyset = new KeySet();
116+
117+
$count = 0;
118+
119+
foreach ($keyset as $key) {
120+
++$count;
121+
}
122+
123+
static::assertSame(0, $count);
124+
125+
$keyset->addKey(new Rsa());
126+
$keyset->addKey(new Rsa());
127+
$keyset->addKey(new Rsa());
128+
129+
foreach ($keyset as $index => $key) {
130+
static::assertInstanceOf(Rsa::class, $key);
131+
static::assertSame($index, $count);
132+
133+
++$count;
134+
}
135+
136+
static::assertSame(3, $count);
137+
}
100138
}

0 commit comments

Comments
 (0)