Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions src/AbstractCollection.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand Down
26 changes: 26 additions & 0 deletions tests/Unit/AbstractCollection/DoGetOrDefaultTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

declare(strict_types=1);

namespace Steevanb\PhpCollection\Tests\Unit\AbstractCollection;

use PHPUnit\Framework\TestCase;

final class DoGetOrDefaultTest extends TestCase
{
public function testGetExistingKey(): void
{
$collection = new Collection([1, 'two' => '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--'));
}
}