Skip to content

Commit 9d39e15

Browse files
authored
feat(support): add every to ArrayHelper (#813)
1 parent b7f99a8 commit 9d39e15

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

src/Tempest/Support/src/ArrayHelper.php

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -723,6 +723,26 @@ public function contains(mixed $search): bool
723723
return $this->first(fn (mixed $value) => $value === $search) !== null;
724724
}
725725

726+
/**
727+
* Asserts whether all items in the instance pass the given `$callback`.
728+
*
729+
* @param Closure(TValue, TKey): bool $callback
730+
*
731+
* @return bool If the collection is empty, returns `true`.
732+
*/
733+
public function every(?Closure $callback = null): bool
734+
{
735+
$callback ??= static fn (mixed $value) => ! is_null($value);
736+
737+
foreach ($this->array as $key => $value) {
738+
if (! $callback($value, $key)) {
739+
return false;
740+
}
741+
}
742+
743+
return true;
744+
}
745+
726746
/**
727747
* Associates the given `$value` to the given `$key` on the instance.
728748
*/

src/Tempest/Support/tests/ArrayHelperTest.php

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1651,4 +1651,13 @@ public function test_slice(): void
16511651
expected: [8, 9],
16521652
);
16531653
}
1654+
1655+
public function test_every(): void
1656+
{
1657+
$this->assertTrue(arr([])->every(fn (int $value) => ($value % 2) === 0));
1658+
$this->assertTrue(arr([2, 4, 6])->every(fn (int $value) => ($value % 2) === 0));
1659+
$this->assertFalse(arr([1, 2, 4, 6])->every(fn (int $value) => ($value % 2) === 0));
1660+
$this->assertTrue(arr([0, 1, true, false, ''])->every());
1661+
$this->assertFalse(arr([0, 1, true, false, '', null])->every());
1662+
}
16541663
}

0 commit comments

Comments
 (0)