[Arr] flip: throw for non-arraykey values

This commit is contained in:
azjezz 2020-07-06 19:19:36 +01:00
parent 78df0eba00
commit 4081ff0bd5
4 changed files with 21 additions and 8 deletions

View File

@ -27,6 +27,7 @@ function count_values(iterable $values): array
$result = [];
foreach ($values as $value) {
Psl\invariant(is_arraykey($value), 'Expected all values to be of type array-key, value of type (%s) provided.', gettype($value));
/** @psalm-var int $count */
$count = idx($result, $value, 0);
$result[$value] = $count + 1;

View File

@ -26,6 +26,7 @@ function flip(iterable $iterable): array
{
$result = [];
foreach ($iterable as $k => $v) {
Psl\invariant(is_arraykey($v), 'Expected all values to be of type array-key, value of type (%s) provided.', gettype($v));
$result[$v] = $k;
}

View File

@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace Psl\Arr;
use Psl\Str;
/**
* Finds whether a variable is an array key.
*
* @psalm-param mixed $key
*
* @psalm-assert-if-true array-key $key
*/
function is_arraykey($key): bool
{
return Str\is_string($key) || is_int($key);
}

View File

@ -32,12 +32,4 @@ class FlipTest extends TestCase
],
];
}
public function testFlipThrowsForNonArrayKeyValues(): void
{
$this->expectException(Exception\InvariantViolationException::class);
$this->expectExceptionMessage('Expected all values to be of type array-key, value of type (resource) provided.');
Arr\flip([STDOUT]);
}
}