Skip to content

Commit

Permalink
Add prepend() to Collection interface
Browse files Browse the repository at this point in the history
  • Loading branch information
ker0x committed May 19, 2024
1 parent 885a8f8 commit 84f2b49
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/AbstractLazyCollection.php
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
11 changes: 11 additions & 0 deletions src/ArrayCollection.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
Expand Down
8 changes: 8 additions & 0 deletions src/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*/
Expand Down
8 changes: 8 additions & 0 deletions tests/CollectionTestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down

0 comments on commit 84f2b49

Please sign in to comment.