Skip to content

Commit 299fd6f

Browse files
authored
Merge pull request #8 from boesing/feature/map-has-key
2 parents cc3b0a0 + eaba62c commit 299fd6f

File tree

3 files changed

+36
-5
lines changed

3 files changed

+36
-5
lines changed

src/Map.php

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -139,10 +139,10 @@ public function put($key, $value): MapInterface
139139
/**
140140
* @psalm-mutation-free
141141
*/
142-
public function get($key)
142+
public function get(string $key)
143143
{
144-
if (! array_key_exists($key, $this->data)) {
145-
throw new OutOfBoundsException(sprintf('There is no value stored for provided key: %s', (string) $key));
144+
if (! $this->has($key)) {
145+
throw new OutOfBoundsException(sprintf('There is no value stored for provided key: %s', $key));
146146
}
147147

148148
return $this->data[$key];
@@ -267,4 +267,12 @@ public function map(callable $callback): MapInterface
267267
{
268268
return new GenericMap(array_map($callback, $this->data));
269269
}
270+
271+
/**
272+
* @psalm-mutation-free
273+
*/
274+
public function has(string $key): bool
275+
{
276+
return array_key_exists($key, $this->data);
277+
}
270278
}

src/MapInterface.php

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -92,12 +92,11 @@ public function keys(): OrderedListInterface;
9292
public function put($key, $value): MapInterface;
9393

9494
/**
95-
* @psalm-param string $key
9695
* @psalm-return TValue
9796
* @throws OutOfBoundsException if key does not exist.
9897
* @psalm-mutation-free
9998
*/
100-
public function get($key);
99+
public function get(string $key);
101100

102101
/**
103102
* @psalm-param MapInterface<TValue> $other
@@ -124,4 +123,9 @@ public function intersectUserAssoc(
124123
?callable $valueComparator = null,
125124
?callable $keyComparator = null
126125
): MapInterface;
126+
127+
/**
128+
* @psalm-mutation-free
129+
*/
130+
public function has(string $key): bool;
127131
}

tests/GenericMapTest.php

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -467,4 +467,23 @@ public function testGetThrowsOutOfBoundsExceptionWhenKeyDoesNotExist(): void
467467
$this->expectException(OutOfBoundsException::class);
468468
$map->get('foo');
469469
}
470+
471+
public function testHasDetectsExistingKey(): void
472+
{
473+
$map = new GenericMap(['foo' => 'bar']);
474+
475+
self::assertTrue($map->has('foo'));
476+
}
477+
478+
public function testHasReturnsFalseOnEmptyMap(): void
479+
{
480+
$map = new GenericMap([]);
481+
self::assertFalse($map->has('foo'));
482+
}
483+
484+
public function testHasReturnsFalseForDueToCaseSensitivity(): void
485+
{
486+
$map = new GenericMap(['foo' => 'bar']);
487+
self::assertFalse($map->has('Foo'));
488+
}
470489
}

0 commit comments

Comments
 (0)