From 9021c6e08a4533a886cf2a4c915605d37b9be2e5 Mon Sep 17 00:00:00 2001 From: Enzo Innocenzi Date: Wed, 6 Nov 2024 10:41:31 -0800 Subject: [PATCH] fix(support): support calling `first` and `last` on empty `ArrayHelper` (#691) --- src/Tempest/Support/src/ArrayHelper.php | 8 ++++++++ src/Tempest/Support/tests/ArrayHelperTest.php | 2 ++ 2 files changed, 10 insertions(+) diff --git a/src/Tempest/Support/src/ArrayHelper.php b/src/Tempest/Support/src/ArrayHelper.php index 8e0c41a65..30ac16b0b 100644 --- a/src/Tempest/Support/src/ArrayHelper.php +++ b/src/Tempest/Support/src/ArrayHelper.php @@ -384,6 +384,10 @@ public function equals(array|self $other): bool */ public function first(?Closure $filter = null): mixed { + if ($this->array === []) { + return null; + } + if ($filter === null) { return $this->array[array_key_first($this->array)]; } @@ -405,6 +409,10 @@ public function first(?Closure $filter = null): mixed */ public function last(?Closure $filter = null): mixed { + if ($this->array === []) { + return null; + } + if ($filter === null) { return $this->array[array_key_last($this->array)]; } diff --git a/src/Tempest/Support/tests/ArrayHelperTest.php b/src/Tempest/Support/tests/ArrayHelperTest.php index ee06c9eab..bd71fec54 100644 --- a/src/Tempest/Support/tests/ArrayHelperTest.php +++ b/src/Tempest/Support/tests/ArrayHelperTest.php @@ -178,12 +178,14 @@ public function test_unshift(): void public function test_last(): void { + $this->assertSame(null, arr()->last()); $this->assertSame('c', arr(['a', 'b', 'c'])->last()); } public function test_first(): void { $this->assertSame('a', arr(['a', 'b', 'c'])->first()); + $this->assertSame(null, arr()->first()); } public function test_is_empty(): void