mirror of
https://github.com/danog/endtoend-test-psl.git
synced 2024-12-02 09:38:32 +01:00
[Arr] flip: throw for non-arraykey values
This commit is contained in:
parent
78df0eba00
commit
4081ff0bd5
@ -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;
|
||||
|
@ -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;
|
||||
}
|
||||
|
||||
|
19
src/Psl/Arr/is_arraykey.php
Normal file
19
src/Psl/Arr/is_arraykey.php
Normal 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);
|
||||
}
|
@ -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]);
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user