Passed
Push — master ( 1940b1...c55a2e )
by Pol
03:56
created

Permutate::getPermutations()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 9
nc 3
nop 1
dl 0
loc 17
ccs 10
cts 10
cp 1
crap 4
rs 9.9666
c 1
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace loophp\collection\Operation;
6
7
use Closure;
8
use Generator;
9
use loophp\collection\Contract\Operation;
10
use loophp\collection\Transformation\All;
11
use loophp\collection\Transformation\Count;
12
13
use function count;
14
15
/**
16
 * Class Permutate.
17
 */
18
final class Permutate implements Operation
19
{
20
    /**
21
     * {@inheritdoc}
22
     */
23 1
    public function on(iterable $collection): Closure
24
    {
25
        $getPermutate = function (array $dataset): Generator {
26 1
            return $this->getPermutations($dataset);
27 1
        };
28
29
        return static function () use ($collection, $getPermutate): Generator {
30 1
            yield from $getPermutate((new All())->on($collection));
31 1
        };
32
    }
33
34
    /**
35
     * @param array<mixed> $dataset
36
     *
37
     * @return Generator<array<mixed>>
38
     */
39 1
    private function getPermutations(array $dataset): Generator
40
    {
41 1
        foreach ($dataset as $key => $firstItem) {
42 1
            $remaining = $dataset;
43
44 1
            array_splice($remaining, $key, 1);
45
46 1
            if (0 === count($remaining)) {
47 1
                yield [$firstItem];
48
49 1
                continue;
50
            }
51
52 1
            foreach ($this->getPermutations($remaining) as $Permutate) {
53 1
                array_unshift($Permutate, $firstItem);
54
55 1
                yield $Permutate;
56
            }
57
        }
58 1
    }
59
}
60