iterable_sort()   B
last analyzed

Complexity

Conditions 8
Paths 56

Size

Total Lines 25
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 8

Importance

Changes 0
Metric Value
cc 8
eloc 16
nc 56
nop 3
dl 0
loc 25
ccs 16
cts 16
cp 1
crap 8
rs 8.4444
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Improved;
6
7
/**
8
 * Sort all elements of an iterator.
9
 *
10
 * @param iterable     $iterable
11
 * @param callable|int $compare       SORT_* flag or callback comparator function
12
 * @param bool         $preserveKeys
13
 * @return \Generator
14
 */
15 12
function iterable_sort(iterable $iterable, $compare, bool $preserveKeys = false): \Generator
0 ignored issues
show
introduced by
Function Improved\iterable_sort() has parameter $iterable with no value type specified in iterable type iterable.
Loading history...
introduced by
Function Improved\iterable_sort() return type has no value type specified in iterable type Generator.
Loading history...
16
{
17 11
    type_check($compare, ['callable', 'int'], new \TypeError("Expected compare to be callable or integer, %s given"));
18
19 11
    $comparator = is_int($compare) ? null : $compare;
20 11
    $flags = is_int($compare) ? $compare : 0;
21
22 11
    ['keys' => $keys, 'values' => $values] = $preserveKeys
23 3
        ? iterable_separate($iterable)
24 8
        : ['keys' => null, 'values' => iterable_to_array($iterable, false)];
25
26 11
    if (!is_array($values)) {
27
        throw new \UnexpectedValueException("Values should be an array"); // @codeCoverageIgnore
28
    }
29
30 11
    isset($comparator)
31 3
        ? uasort($values, $comparator)
32 8
        : asort($values, $flags);
33
34 11
    $counter = 0;
35 11
    unset($iterable);
36
37 11
    foreach ($values as $index => $value) {
38 10
        $key = isset($keys) ? $keys[$index] : $counter++;
39 10
        yield $key => $value;
40
    }
41
}
42