Skip to content

Commit bb95a41

Browse files
authored
Merge pull request #79 from KevinVanSonsbeek/feat/make-collections-support-iterables
Add support to the collection for iterables
2 parents 6244bf3 + a19e150 commit bb95a41

File tree

2 files changed

+13
-9
lines changed

2 files changed

+13
-9
lines changed

src/Collection.php

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
use Aeviiq\Collection\Exception\InvalidArgumentException;
66
use Aeviiq\Collection\Exception\LogicException;
7+
use Traversable;
78

89
/**
910
* @template TKey as array-key
@@ -33,17 +34,12 @@ class Collection implements CollectionInterface
3334
private $iteratorClass;
3435

3536
/**
36-
* @param array<TKey, TValue> $elements
37-
* @phpstan-param array<TKey, TValue> $elements
38-
*
37+
* @param iterable<TKey, TValue> $elements
3938
* @param class-string<\ArrayAccess>|string $iteratorClass
40-
* @phpstan-param class-string<\ArrayAccess>|string $iteratorClass
41-
*
42-
* @param array<string|int, mixed> $elements
43-
* @param string $iteratorClass
4439
*/
45-
final public function __construct(array $elements = [], string $iteratorClass = \ArrayIterator::class)
40+
final public function __construct(iterable $elements = [], string $iteratorClass = \ArrayIterator::class)
4641
{
42+
$elements = $elements instanceof Traversable ? iterator_to_array($elements) : $elements;
4743
$this->validateElements($elements);
4844
$this->elements = $elements;
4945
$this->setIteratorClass($iteratorClass);

tests/CollectionTest.php

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
use Aeviiq\Collection\Collection;
66
use Aeviiq\Collection\Exception\LogicException;
7+
use ArrayIterator;
78
use PHPUnit\Framework\TestCase;
89

910
class CollectionTest extends TestCase
@@ -25,6 +26,13 @@ public function testInstanceCreation(): void
2526
$this->assertSame($expected, $collection->toArray());
2627
}
2728

29+
public function testInstanceCreationWithIterator(): void
30+
{
31+
$expected = $this->getFirstThreeValidValues();
32+
$collection = $this->createCollectionWithElements(new ArrayIterator($expected));
33+
self::assertSame($expected, $collection->toArray());
34+
}
35+
2836
public function testAppend(): void
2937
{
3038
$collection = $this->createEmptyCollection();
@@ -343,7 +351,7 @@ protected function createEmptyCollection(): Collection
343351
/**
344352
* @param mixed[] $elements
345353
*/
346-
protected function createCollectionWithElements(array $elements): Collection
354+
protected function createCollectionWithElements(iterable $elements): Collection
347355
{
348356
$collectionClass = $this->getCollectionClass();
349357

0 commit comments

Comments
 (0)