iterable_group()   A
last analyzed

Complexity

Conditions 4
Paths 6

Size

Total Lines 21
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 11
nc 6
nop 2
dl 0
loc 21
ccs 12
cts 12
cp 1
crap 4
rs 9.9
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Improved;
6
7
/**
8
 * Group elements of an array or iterator.
9
 *
10
 * @param iterable $iterable
11
 * @param callable $grouping
12
 * @return \Generator
13
 */
14 9
function iterable_group(iterable $iterable, callable $grouping): \Generator
0 ignored issues
show
introduced by
Function Improved\iterable_group() has parameter $iterable with no value type specified in iterable type iterable.
Loading history...
introduced by
Function Improved\iterable_group() return type has no value type specified in iterable type Generator.
Loading history...
15
{
16 8
    $groups = [];
17 8
    $values = [];
18
19 8
    foreach ($iterable as $key => $value) {
20 7
        $group = call_user_func($grouping, $value, $key);
21
22 7
        $index = array_search($group, $groups, true);
23
24 7
        if ($index === false) {
25 7
            $index = array_push($groups, $group) - 1;
26
        }
27
28 7
        $values[$index][] = $value;
29
    }
30
31 8
    unset($iterable);
32
33 8
    foreach ($groups as $index => $group) {
34 7
        yield $group => $values[$index];
35
    }
36
}
37