From 6a65d30c1baca2a757aa26bbf8554e8f16542012 Mon Sep 17 00:00:00 2001 From: Billy VILLENA Date: Wed, 12 Feb 2025 14:53:15 +0100 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20[AbstractCollection]=20Get=20or=20d?= =?UTF-8?q?efault=20value?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * ✨ `AbstractCollection::getOrDefaultValue()`: get value for index or return default given value - ✅ **Tested!** upon `Tests\Unit\Collection` --- src/AbstractCollection.php | 11 ++++++++ .../AbstractCollection/DoGetOrDefaultTest.php | 26 +++++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 tests/Unit/AbstractCollection/DoGetOrDefaultTest.php diff --git a/src/AbstractCollection.php b/src/AbstractCollection.php index a4b20a1..7091a32 100644 --- a/src/AbstractCollection.php +++ b/src/AbstractCollection.php @@ -167,6 +167,17 @@ public function get(string|int $key): mixed return $this->values[$key]; } + /** + * @param TValueType $default + * @return TValueType + */ + public function getOrDefault(string|int $key, mixed $default): mixed + { + $this->assertValueType($default); + + return $this->hasKey($key) ? $this->get($key) : $default; + } + /** @param TValueType $value */ public function contains(mixed $value): bool { diff --git a/tests/Unit/AbstractCollection/DoGetOrDefaultTest.php b/tests/Unit/AbstractCollection/DoGetOrDefaultTest.php new file mode 100644 index 0000000..0ed95ff --- /dev/null +++ b/tests/Unit/AbstractCollection/DoGetOrDefaultTest.php @@ -0,0 +1,26 @@ + '2', null]); + + static::assertSame(expected: 1, actual: $collection->getOrDefault(key: 0, default: '--test_1--')); + static::assertSame(expected: '2', actual: $collection->getOrDefault(key: 'two', default: '--test_2--')); + static::assertNull(actual: $collection->getOrDefault(key: 1, default: '--test_3--')); + } + + public function testGetNotExistingKey(): void + { + $collection = new Collection([1, 'two' => '2', null]); + + static::assertSame(expected: '--test_1--', actual: $collection->getOrDefault(key: 2, default: '--test_1--')); + } +}