From e53c7654128496f5ff0a99810990106b506731a8 Mon Sep 17 00:00:00 2001 From: Oluwatobi Omisakin Date: Tue, 30 Apr 2024 01:19:32 +0300 Subject: [PATCH] feat: Fix head to return one element --- src/Traits/ArrayPrefix.php | 27 +++++++++++++++++++++++++-- tests/ArrayPrefixTraitTest.php | 13 +++++++++---- 2 files changed, 34 insertions(+), 6 deletions(-) diff --git a/src/Traits/ArrayPrefix.php b/src/Traits/ArrayPrefix.php index 88b6de0..a1f372d 100644 --- a/src/Traits/ArrayPrefix.php +++ b/src/Traits/ArrayPrefix.php @@ -6,6 +6,7 @@ use Transprime\Arrayed\Exceptions\ArrayedException; use Transprime\Arrayed\Interfaces\ArrayedInterface; +use Transprime\Arrayed\Types\Undefined; /** * Trait ArrayPrefix @@ -80,9 +81,18 @@ public function keysExists(array $needles, bool $all = true): bool : (!$intersect->empty()); } - public function head(bool $preserveKeys = false): ArrayedInterface + /** + * @throws ArrayedException + * @return ArrayedInterface|mixed + */ + public function head(bool $preserveKeys = false) { - return $this->slice(0, 1, $preserveKeys); + return self::makeArrayed( + $this->when($this->getWorkableItem()) + ->slice(0, 1, $preserveKeys) + ->values() + ->offsetGet(0) + ); } public function tail(): ArrayedInterface @@ -90,6 +100,19 @@ public function tail(): ArrayedInterface return $this->slice(1); } + private function when($truthyValue, $default = Undefined::class) + { + if ($truthyValue) { + return $this; + } + + if ($default === Undefined::class || $default instanceof Undefined) { + throw new \InvalidArgumentException('Value cannot be resolved'); + } + + return $this->setResult($default); + } + /** * Forward the calls to `array_*` that is not yet implemented *
diff --git a/tests/ArrayPrefixTraitTest.php b/tests/ArrayPrefixTraitTest.php index 39e2770..91cd397 100644 --- a/tests/ArrayPrefixTraitTest.php +++ b/tests/ArrayPrefixTraitTest.php @@ -182,16 +182,21 @@ public function testHead(): void $data = ['a', 'b', 'c', 'd']; $this->assertSame( - ['a'], - arrayed($data)->head()->result(), + 'a', + arrayed($data)->head(), ); $data = ['a' => 'b', 'c' => 'd']; $this->assertSame( - ['a' => 'b'], - arrayed($data)->head()->result(), + 'b', + arrayed($data)->head(), ); + + // Test empty. + $this->expectException(\InvalidArgumentException::class); + + arrayed([])->head(); } public function testTail(): void