diff --git a/src/AbstractLazyCollection.php b/src/AbstractLazyCollection.php index c926b6d8..753f7ea6 100644 --- a/src/AbstractLazyCollection.php +++ b/src/AbstractLazyCollection.php @@ -41,6 +41,13 @@ public function add(mixed $element): void $this->collection->add($element); } + public function prepend(mixed $element): void + { + $this->initialize(); + + $this->collection->prepend($element); + } + public function clear(): void { $this->initialize(); diff --git a/src/ArrayCollection.php b/src/ArrayCollection.php index 86b07039..830fa7ff 100644 --- a/src/ArrayCollection.php +++ b/src/ArrayCollection.php @@ -18,6 +18,7 @@ use function array_reverse; use function array_search; use function array_slice; +use function array_unshift; use function array_values; use function count; use function current; @@ -272,6 +273,16 @@ public function add(mixed $element): void $this->elements[] = $element; } + /** + * {@inheritDoc} + * + * @psalm-suppress InvalidPropertyAssignmentValue + */ + public function prepend(mixed $element): void + { + array_unshift($this->elements, $element); + } + public function isEmpty(): bool { return empty($this->elements); diff --git a/src/Collection.php b/src/Collection.php index 3dc56ac3..ba919b70 100644 --- a/src/Collection.php +++ b/src/Collection.php @@ -39,6 +39,14 @@ interface Collection extends ReadableCollection, ArrayAccess */ public function add(mixed $element): void; + /** + * Adds an element at the beginning of the collection. + * + * @param mixed $element The element to add. + * @psalm-param T $element + */ + public function prepend(mixed $element): void; + /** * Clears the collection, removing all elements. */ diff --git a/tests/CollectionTestCase.php b/tests/CollectionTestCase.php index 4dc136b0..053e3e07 100644 --- a/tests/CollectionTestCase.php +++ b/tests/CollectionTestCase.php @@ -184,6 +184,14 @@ public function testPartition(): void self::assertEquals($partition[1][0], false); } + public function testPrepend(): void + { + $this->collection->add('one'); + $this->collection->add('two'); + $this->collection->prepend('zero'); + self::assertEquals('zero', $this->collection->get(0)); + } + public function testClear(): void { $this->collection[] = 'one';