From a7eb80f4f1cc7d7576711409d1c8bb99f43906f6 Mon Sep 17 00:00:00 2001 From: Oliver Vogel Date: Sat, 18 Jun 2022 16:02:11 +0200 Subject: [PATCH] Add Collection::get() method --- src/Collection.php | 5 +++++ src/Interfaces/CollectionInterface.php | 1 + tests/CollectionTest.php | 8 ++++++++ 3 files changed, 14 insertions(+) diff --git a/src/Collection.php b/src/Collection.php index 90fbefaf..e1e37a6c 100644 --- a/src/Collection.php +++ b/src/Collection.php @@ -109,6 +109,11 @@ class Collection implements CollectionInterface, IteratorAggregate, Countable return $this->items[$key]; } + public function has(int $key): bool + { + return array_key_exists($key, $this->items); + } + public function query(string $query, $default = null) { $items = $this->getItemsFlat(); diff --git a/src/Interfaces/CollectionInterface.php b/src/Interfaces/CollectionInterface.php index 5c63e5a7..d51cee76 100644 --- a/src/Interfaces/CollectionInterface.php +++ b/src/Interfaces/CollectionInterface.php @@ -6,6 +6,7 @@ interface CollectionInterface { public function push($item): CollectionInterface; public function get(int $key); + public function has(int $key); public function first(); public function last(); public function count(): int; diff --git a/tests/CollectionTest.php b/tests/CollectionTest.php index b4a6738b..9703486e 100644 --- a/tests/CollectionTest.php +++ b/tests/CollectionTest.php @@ -86,6 +86,14 @@ class CollectionTest extends TestCase $this->assertEquals('test', $collection->get(3, 'test')); } + public function testHas(): void + { + $collection = new Collection(['foo', 'bar']); + $this->assertTrue($collection->has(0)); + $this->assertTrue($collection->has(1)); + $this->assertFalse($collection->has(2)); + } + public function testToArray() { $collection = new Collection(['foo', 'bar', 'baz']);