Skip to content

Commit 7daf3fc

Browse files
authored
feat(support): add append and prepend to ArrayHelper (#833)
1 parent 8372827 commit 7daf3fc

File tree

2 files changed

+72
-0
lines changed

2 files changed

+72
-0
lines changed

src/Tempest/Support/src/ArrayHelper.php

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -258,6 +258,38 @@ public function pluck(string $value, ?string $key = null): self
258258
return new self($results);
259259
}
260260

261+
/**
262+
* Prepends the specified values to the instance.
263+
*
264+
* @param TValue $values
265+
*/
266+
public function prepend(mixed ...$values): self
267+
{
268+
$array = $this->array;
269+
270+
foreach (array_reverse($values) as $value) {
271+
$array = [$value, ...$array];
272+
}
273+
274+
return new self($array);
275+
}
276+
277+
/**
278+
* Appends the specified values to the instance.
279+
*
280+
* @param TValue $values
281+
*/
282+
public function append(mixed ...$values): self
283+
{
284+
$array = $this->array;
285+
286+
foreach ($values as $value) {
287+
$array = [...$array, $value];
288+
}
289+
290+
return new self($array);
291+
}
292+
261293
/**
262294
* @alias of `add`.
263295
*/

src/Tempest/Support/tests/ArrayHelperTest.php

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1666,4 +1666,44 @@ public function test_every(): void
16661666
$this->assertTrue(arr([0, 1, true, false, ''])->every());
16671667
$this->assertFalse(arr([0, 1, true, false, '', null])->every());
16681668
}
1669+
1670+
public function test_append(): void
1671+
{
1672+
$collection = arr(['foo', 'bar']);
1673+
1674+
$this->assertSame(
1675+
actual: $collection->append('foo')->toArray(),
1676+
expected: ['foo', 'bar', 'foo'],
1677+
);
1678+
1679+
$this->assertSame(
1680+
actual: $collection->append(1, 'b')->toArray(),
1681+
expected: ['foo', 'bar', 1, 'b'],
1682+
);
1683+
1684+
$this->assertSame(
1685+
actual: $collection->append(['a' => 'b'])->toArray(),
1686+
expected: ['foo', 'bar', ['a' => 'b']],
1687+
);
1688+
}
1689+
1690+
public function test_prepend(): void
1691+
{
1692+
$collection = arr(['foo', 'bar']);
1693+
1694+
$this->assertSame(
1695+
actual: $collection->prepend('foo')->toArray(),
1696+
expected: ['foo', 'foo', 'bar'],
1697+
);
1698+
1699+
$this->assertSame(
1700+
actual: $collection->prepend(1, 'b')->toArray(),
1701+
expected: [1, 'b', 'foo', 'bar'],
1702+
);
1703+
1704+
$this->assertSame(
1705+
actual: $collection->prepend(['a' => 'b'])->toArray(),
1706+
expected: [['a' => 'b'], 'foo', 'bar'],
1707+
);
1708+
}
16691709
}

0 commit comments

Comments
 (0)