Skip to content

Commit

Permalink
Merge pull request #8 from boesing/feature/map-has-key
Browse files Browse the repository at this point in the history
  • Loading branch information
boesing committed Oct 21, 2020
2 parents cc3b0a0 + eaba62c commit 299fd6f
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 5 deletions.
14 changes: 11 additions & 3 deletions src/Map.php
Original file line number Diff line number Diff line change
Expand Up @@ -139,10 +139,10 @@ public function put($key, $value): MapInterface
/**
* @psalm-mutation-free
*/
public function get($key)
public function get(string $key)
{
if (! array_key_exists($key, $this->data)) {
throw new OutOfBoundsException(sprintf('There is no value stored for provided key: %s', (string) $key));
if (! $this->has($key)) {
throw new OutOfBoundsException(sprintf('There is no value stored for provided key: %s', $key));
}

return $this->data[$key];
Expand Down Expand Up @@ -267,4 +267,12 @@ public function map(callable $callback): MapInterface
{
return new GenericMap(array_map($callback, $this->data));
}

/**
* @psalm-mutation-free
*/
public function has(string $key): bool
{
return array_key_exists($key, $this->data);
}
}
8 changes: 6 additions & 2 deletions src/MapInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -92,12 +92,11 @@ public function keys(): OrderedListInterface;
public function put($key, $value): MapInterface;

/**
* @psalm-param string $key
* @psalm-return TValue
* @throws OutOfBoundsException if key does not exist.
* @psalm-mutation-free
*/
public function get($key);
public function get(string $key);

/**
* @psalm-param MapInterface<TValue> $other
Expand All @@ -124,4 +123,9 @@ public function intersectUserAssoc(
?callable $valueComparator = null,
?callable $keyComparator = null
): MapInterface;

/**
* @psalm-mutation-free
*/
public function has(string $key): bool;
}
19 changes: 19 additions & 0 deletions tests/GenericMapTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -467,4 +467,23 @@ public function testGetThrowsOutOfBoundsExceptionWhenKeyDoesNotExist(): void
$this->expectException(OutOfBoundsException::class);
$map->get('foo');
}

public function testHasDetectsExistingKey(): void
{
$map = new GenericMap(['foo' => 'bar']);

self::assertTrue($map->has('foo'));
}

public function testHasReturnsFalseOnEmptyMap(): void
{
$map = new GenericMap([]);
self::assertFalse($map->has('foo'));
}

public function testHasReturnsFalseForDueToCaseSensitivity(): void
{
$map = new GenericMap(['foo' => 'bar']);
self::assertFalse($map->has('Foo'));
}
}

0 comments on commit 299fd6f

Please sign in to comment.