Frequency::__invoke()   A
last analyzed

Complexity

Conditions 4
Paths 1

Size

Total Lines 39
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 20
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 17
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 39
ccs 20
cts 20
cp 1
crap 4
rs 9.7
1
<?php
2
3
declare(strict_types=1);
4
5
namespace loophp\collection\Operation;
6
7
use Closure;
8
use Generator;
9
10
/**
11
 * @immutable
12
 *
13
 * @template TKey
14
 * @template T
15
 */
16
final class Frequency extends AbstractOperation
17
{
18
    /**
19
     * @return Closure(iterable<TKey, T>): Generator<int, T>
20
     */
21 5
    public function __invoke(): Closure
22
    {
23 5
        $reduceCallback =
24
            /**
25
             * @param array<int, array{0: int, 1: T}> $storage
26
             * @param T $value
27
             *
28
             * @return array<int, array{0: int, 1: T}>
29
             */
30 5
            static function (array $storage, $value): array {
31 5
                $added = false;
32
33 5
                foreach ($storage as $key => $data) {
34 5
                    if ($data[1] !== $value) {
35 4
                        continue;
36
                    }
37
38 4
                    ++$storage[$key][0];
39 4
                    $added = true;
40
41 4
                    break;
42
                }
43
44 5
                if (true !== $added) {
45 5
                    $storage[] = [1, $value];
46
                }
47
48 5
                return $storage;
49 5
            };
50
51
        /** @var Closure(iterable<TKey, T>): Generator<int, T> $pipe */
52 5
        $pipe = (new Pipe())()(
53 5
            (new Reduce())()($reduceCallback)([]),
54 5
            (new Flatten())()(1),
55 5
            (new Unpack())()
56 5
        );
57
58
        // Point free style.
59 5
        return $pipe;
60
    }
61
}
62