Passed
Push — master ( 9cee3b...c3dbdd )
by Magnar Ovedal
03:22
created

Coder::code()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 6
nc 3
nop 1
dl 0
loc 13
ccs 7
cts 7
cp 1
crap 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Stadly\PasswordPolice\Formatter;
6
7
use SplObjectStorage;
8
use Stadly\PasswordPolice\CharTree;
9
use Stadly\PasswordPolice\CodeMap;
10
use Stadly\PasswordPolice\Formatter;
11
12
final class Coder implements Formatter
13
{
14
    use Chaining;
15
16
    /**
17
     * @var CodeMap Code map for coding character trees.
18
     */
19
    private $codeMap;
20
21
    /**
22
     * @var SplObjectStorage Memoization for already coded character trees.
23
     */
24
    private $codeMemoization;
25
26
    /**
27
     * @param CodeMap $codeMap Code map for coding character trees.
28
     */
29 3
    public function __construct(CodeMap $codeMap)
30
    {
31 3
        $this->codeMap = $codeMap;
32 3
        $this->codeMemoization = new SplObjectStorage();
33 3
    }
34
35
    /**
36
     * @param CharTree $charTree Character tree to format.
37
     * @return CharTree Coded variant of the character tree.
38
     */
39 3
    protected function applyCurrent(CharTree $charTree): CharTree
40
    {
41 3
        return CharTree::fromArray($this->applyInternal($charTree));
42
    }
43
44
    /**
45
     * @param CharTree $charTree Character tree to format.
46
     * @return CharTree[] Coded variants of the character tree.
47
     */
48 3
    private function applyInternal(CharTree $charTree): array
49
    {
50 3
        if (!isset($this->codeMemoization[$charTree])) {
51 3
            $this->codeMemoization[$charTree] = $this->code($charTree);
52
        }
53
54 3
        return $this->codeMemoization[$charTree];
55
    }
56
57
    /**
58
     * @param CharTree $charTree Character tree to format.
59
     * @return CharTree[] Coded variants of the character tree. Memoization is not used.
60
     */
61 3
    private function code(CharTree $charTree): array
62
    {
63 3
        $charTrees = [];
64
65 3
        foreach ($this->codeMap->getMap($charTree) as $char => $codedChars) {
66 3
            $branches = $this->applyInternal($charTree->getBranchesAfterRoot((string)$char));
67
68 3
            foreach ($codedChars as $codedChar) {
69 3
                $charTrees[] = CharTree::fromString($codedChar, $branches);
70
            }
71
        }
72
73 3
        return $charTrees;
74
    }
75
}
76