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

Coder   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 16
dl 0
loc 62
ccs 17
cts 17
cp 1
rs 10
c 0
b 0
f 0
wmc 7

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A code() 0 13 3
A applyInternal() 0 7 2
A applyCurrent() 0 3 1
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