Conditions | 9 |
Paths | 112 |
Total Lines | 30 |
Code Lines | 20 |
Lines | 0 |
Ratio | 0 % |
Tests | 19 |
CRAP Score | 9.0101 |
Changes | 0 |
1 | <?php |
||
17 | function iterable_sort(iterable $iterable, $compare, bool $preserveKeys = false): \Generator |
||
18 | { |
||
19 | 11 | expect_type( |
|
20 | 11 | $compare, |
|
21 | 11 | ['callable', 'int'], |
|
22 | 11 | \TypeError::class, |
|
23 | 11 | "Expected compare to be a callable or integer, %s given" |
|
24 | ); |
||
25 | |||
26 | 11 | $comparator = is_int($compare) ? null : $compare; |
|
27 | 11 | $flags = is_int($compare) ? $compare : 0; |
|
28 | |||
29 | 11 | ['keys' => $keys, 'values' => $values] = $preserveKeys |
|
30 | 3 | ? iterable_separate($iterable) |
|
31 | 8 | : ['keys' => null, 'values' => is_array($iterable) ? $iterable : iterator_to_array($iterable, false)]; |
|
32 | |||
33 | 11 | if (!is_array($values)) { |
|
34 | throw new \UnexpectedValueException("Values should be an array"); |
||
35 | } |
||
36 | |||
37 | 11 | isset($comparator) |
|
38 | 3 | ? uasort($values, $comparator) |
|
39 | 8 | : asort($values, $flags); |
|
40 | |||
41 | 11 | $counter = 0; |
|
42 | 11 | unset($iterable); |
|
43 | |||
44 | 11 | foreach ($values as $index => $value) { |
|
45 | 10 | $key = isset($keys) ? $keys[$index] : $counter++; |
|
46 | 10 | yield $key => $value; |
|
47 | } |
||
49 |