From dbb29cf8f0e4dcae706429c5aa4e3c6f54a06d5f Mon Sep 17 00:00:00 2001 From: Arif Hoque Date: Fri, 12 Jun 2026 15:03:38 +0600 Subject: [PATCH] fix collection first() and null-key existence handling --- src/Phaseolies/Support/Collection.php | 10 +++++++--- tests/CollectionTest.php | 14 ++++++++++++++ 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/src/Phaseolies/Support/Collection.php b/src/Phaseolies/Support/Collection.php index 6059e850..f84b75e3 100644 --- a/src/Phaseolies/Support/Collection.php +++ b/src/Phaseolies/Support/Collection.php @@ -99,7 +99,7 @@ public function __call($method, $parameters) */ public function __isset($name) { - return isset($this->data[$name]); + return array_key_exists($name, $this->data); } /** @@ -110,7 +110,7 @@ public function __isset($name) */ public function offsetExists($offset): bool { - return isset($this->data[$offset]); + return array_key_exists($offset, $this->data); } /** @@ -194,7 +194,11 @@ public function all(): array */ public function first(): mixed { - return $this->data[0] ?? null; + foreach ($this->data as $item) { + return $item; + } + + return null; } /** diff --git a/tests/CollectionTest.php b/tests/CollectionTest.php index ca46ad37..80151336 100644 --- a/tests/CollectionTest.php +++ b/tests/CollectionTest.php @@ -68,6 +68,17 @@ public function testMagicGetAndIsset() $this->assertFalse(isset($collection->baz)); } + public function testNullValuesAreStillConsideredPresent() + { + $collection = new Collection(Model::class, ["foo" => null]); + + $this->assertArrayHasKey("foo", $collection->all()); + $this->assertTrue(isset($collection["foo"])); + $this->assertTrue(isset($collection->foo)); + $this->assertNull($collection["foo"]); + $this->assertNull($collection->foo); + } + public function testGetIterator() { $items = [1, 2, 3]; @@ -97,6 +108,9 @@ public function testFirst() $collection = new Collection(Model::class, [1, 2, 3]); $this->assertEquals(1, $collection->first()); + $associativeCollection = new Collection(Model::class, ['a' => 10, 'b' => 20]); + $this->assertEquals(10, $associativeCollection->first()); + $emptyCollection = new Collection(Model::class, []); $this->assertNull($emptyCollection->first()); }