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

Permutate   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 13
dl 0
loc 38
ccs 15
cts 15
cp 1
rs 10
c 1
b 0
f 0
wmc 5

2 Methods

Rating   Name   Duplication   Size   Complexity  
A getPermutations() 0 17 4
A on() 0 8 1
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