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--')); + } +}