Skip to content

Commit

Permalink
feat(support): add append and prepend to ArrayHelper (#833)
Browse files Browse the repository at this point in the history
  • Loading branch information
aidan-casey committed Dec 9, 2024
1 parent 0b63e54 commit 14b141a
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 0 deletions.
32 changes: 32 additions & 0 deletions src/ArrayHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,38 @@ public function pluck(string $value, ?string $key = null): self
return new self($results);
}

/**
* Prepends the specified values to the instance.
*
* @param TValue $values
*/
public function prepend(mixed ...$values): self
{
$array = $this->array;

foreach (array_reverse($values) as $value) {
$array = [$value, ...$array];
}

return new self($array);
}

/**
* Appends the specified values to the instance.
*
* @param TValue $values
*/
public function append(mixed ...$values): self
{
$array = $this->array;

foreach ($values as $value) {
$array = [...$array, $value];
}

return new self($array);
}

/**
* @alias of `add`.
*/
Expand Down
40 changes: 40 additions & 0 deletions tests/ArrayHelperTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1666,4 +1666,44 @@ public function test_every(): void
$this->assertTrue(arr([0, 1, true, false, ''])->every());
$this->assertFalse(arr([0, 1, true, false, '', null])->every());
}

public function test_append(): void
{
$collection = arr(['foo', 'bar']);

$this->assertSame(
actual: $collection->append('foo')->toArray(),
expected: ['foo', 'bar', 'foo'],
);

$this->assertSame(
actual: $collection->append(1, 'b')->toArray(),
expected: ['foo', 'bar', 1, 'b'],
);

$this->assertSame(
actual: $collection->append(['a' => 'b'])->toArray(),
expected: ['foo', 'bar', ['a' => 'b']],
);
}

public function test_prepend(): void
{
$collection = arr(['foo', 'bar']);

$this->assertSame(
actual: $collection->prepend('foo')->toArray(),
expected: ['foo', 'foo', 'bar'],
);

$this->assertSame(
actual: $collection->prepend(1, 'b')->toArray(),
expected: [1, 'b', 'foo', 'bar'],
);

$this->assertSame(
actual: $collection->prepend(['a' => 'b'])->toArray(),
expected: [['a' => 'b'], 'foo', 'bar'],
);
}
}

0 comments on commit 14b141a

Please sign in to comment.