Skip to content

Commit 1f7d851

Browse files
author
Bl00D4NGEL
committed
feat: add fromIterable function for Collection
1 parent f5b449a commit 1f7d851

File tree

2 files changed

+45
-2
lines changed

2 files changed

+45
-2
lines changed

src/Domain/Collection.php

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
namespace GeekCell\Ddd\Domain;
66

77
use Assert;
8+
use InvalidArgumentException;
9+
use Traversable;
810

911
/**
1012
* @template T of object
@@ -26,11 +28,32 @@ final public function __construct(
2628
}
2729
}
2830

31+
/**
32+
* Creates a collection from a given iterable of items.
33+
* This function is useful when trying to create a collection from a generator or an iterator
34+
*
35+
* @param iterable<T> $items
36+
* @param class-string<T>|null $itemType
37+
* @return self<T>
38+
*/
39+
public static function fromIterable(iterable $items, ?string $itemType = null): static
40+
{
41+
if (is_array($items)) {
42+
return new static($items, $itemType);
43+
}
44+
45+
if (!$items instanceof Traversable) {
46+
$items = [...$items];
47+
}
48+
49+
return new static(iterator_to_array($items), $itemType);
50+
}
51+
2952
/**
3053
* Add one or more items to the collection. It **does not** modify the
3154
* current collection, but returns a new one.
3255
*
33-
* @param mixed $item One or more items to add to the collection.
56+
* @param T|iterable<T> $item One or more items to add to the collection.
3457
* @return static
3558
*/
3659
public function add(mixed $item): static
@@ -158,7 +181,7 @@ public function count(): int
158181
/**
159182
* @inheritDoc
160183
*/
161-
public function getIterator(): \Traversable
184+
public function getIterator(): Traversable
162185
{
163186
return new \ArrayIterator($this->items);
164187
}

tests/Domain/CollectionTest.php

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

55
namespace GeekCell\Ddd\Tests\Domain;
66

7+
use ArrayIterator;
78
use Assert;
89
use GeekCell\Ddd\Domain\Collection;
910
use PHPUnit\Framework\TestCase;
@@ -300,4 +301,23 @@ public function testChaining(): void
300301
// Then
301302
$this->assertEquals(60, $result);
302303
}
304+
305+
public function testFromIterable(): void
306+
{
307+
$items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
308+
$collectionFromArray = Collection::fromIterable($items);
309+
$this->assertSame($items, iterator_to_array($collectionFromArray));
310+
311+
$collectionFromIterator = Collection::fromIterable(new ArrayIterator($items));
312+
$this->assertSame($items, iterator_to_array($collectionFromIterator));
313+
314+
$generatorFn = static function () use ($items) {
315+
foreach ($items as $item) {
316+
yield $item;
317+
}
318+
};
319+
320+
$collectionFromGenerator = Collection::fromIterable($generatorFn());
321+
$this->assertSame($items, iterator_to_array($collectionFromGenerator));
322+
}
303323
}

0 commit comments

Comments
 (0)