diff --git a/src/Domain/Collection.php b/src/Domain/Collection.php index a0f174f..0a941f6 100644 --- a/src/Domain/Collection.php +++ b/src/Domain/Collection.php @@ -11,6 +11,7 @@ use InvalidArgumentException; use IteratorAggregate; use Traversable; + use function array_filter; use function array_map; use function array_reduce; @@ -28,7 +29,7 @@ class Collection implements ArrayAccess, Countable, IteratorAggregate { /** - * @param T[] $items + * @param array $items * @param class-string|null $itemType * @throws Assert\AssertionFailedException */ @@ -63,6 +64,27 @@ public static function fromIterable(iterable $items, ?string $itemType = null): return new static(iterator_to_array($items), $itemType); } + /** + * Returns the collection as an array. + * The returned array is either a key-value array with values of type T or a list of T + * + * @return array|list + */ + public function toArray(): array + { + return $this->items; + } + + /** + * Returns the collection as a list of T + * + * @return list + */ + public function toList(): array + { + return array_values($this->items); + } + /** * Returns true if every value in the collection passes the callback truthy test. Opposite of self::none(). * Callback arguments will be element, index, collection. diff --git a/tests/Domain/CollectionTest.php b/tests/Domain/CollectionTest.php index 5e42dea..54aa3cf 100644 --- a/tests/Domain/CollectionTest.php +++ b/tests/Domain/CollectionTest.php @@ -156,7 +156,7 @@ public function testAddMultiple(): void public function testFilter(): void { // Given - $items = [1, 2, 3,4, 5, 6, 7, 8, 9, 10]; + $items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; $collection = new Collection($items); // When @@ -584,4 +584,32 @@ public function testHasItems(): void $this->assertFalse((new Collection([]))->hasItems()); $this->assertTrue((new Collection([1]))->hasItems()); } + + public function testToArray(): void + { + $this->assertSame([], (new Collection([]))->toArray()); + + $list = [1, 2, 3]; + $this->assertSame($list, (new Collection($list))->toArray()); + + $keyValue = ['foo' => 1, 'bar' => 2, 'baz' => 3]; + $this->assertSame($keyValue, (new Collection($keyValue))->toArray()); + + $numberIndexed = [1 => 1, 2 => 2, 3 => 3, 0 => 0]; + $this->assertSame($numberIndexed, (new Collection($numberIndexed))->toArray()); + } + + public function testToList(): void + { + $this->assertSame([], (new Collection([]))->toList()); + + $list = [1, 2, 3]; + $this->assertSame($list, (new Collection($list))->toList()); + + $keyValue = ['foo' => 1, 'bar' => 2, 'baz' => 3]; + $this->assertSame([1, 2, 3], (new Collection($keyValue))->toList()); + + $numberIndexed = [1 => 1, 2 => 2, 3 => 3, 0 => 0]; + $this->assertSame([1, 2, 3, 0], (new Collection($numberIndexed))->toList()); + } }