|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Stadly\PasswordPolice\Formatter; |
|
6
|
|
|
|
|
7
|
|
|
use Stadly\PasswordPolice\CharTree; |
|
8
|
|
|
use Stadly\PasswordPolice\CharTree\Cutter; |
|
9
|
|
|
use Stadly\PasswordPolice\CodeMap; |
|
10
|
|
|
use Stadly\PasswordPolice\Formatter; |
|
11
|
|
|
|
|
12
|
|
|
abstract class Coder implements Formatter |
|
13
|
|
|
{ |
|
14
|
|
|
/** |
|
15
|
|
|
* @var CodeMap Code map for coding character trees. |
|
16
|
|
|
*/ |
|
17
|
|
|
private $codeMap; |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* @var Cutter Character tree cutter for extracting the first character. |
|
21
|
|
|
*/ |
|
22
|
|
|
private $charExtractor; |
|
23
|
|
|
|
|
24
|
|
|
/** |
|
25
|
|
|
* @param CodeMap $codeMap Code map for coding character trees. |
|
26
|
|
|
*/ |
|
27
|
5 |
|
public function __construct(CodeMap $codeMap) |
|
28
|
|
|
{ |
|
29
|
5 |
|
$this->codeMap = $codeMap; |
|
30
|
5 |
|
$this->charExtractor = new Cutter(); |
|
31
|
5 |
|
} |
|
32
|
|
|
|
|
33
|
|
|
/** |
|
34
|
|
|
* @param CharTree $charTree Character tree to format. |
|
35
|
|
|
* @return CharTree Coded variant of the character tree. |
|
36
|
|
|
*/ |
|
37
|
|
|
abstract protected function applyCurrent(CharTree $charTree): CharTree; |
|
38
|
|
|
|
|
39
|
|
|
/** |
|
40
|
|
|
* @param CharTree $charTree Character tree to format. |
|
41
|
|
|
* @return CharTree Coded variant of the character tree. Memoization is not used. |
|
42
|
|
|
*/ |
|
43
|
31 |
|
protected function format(CharTree $charTree): CharTree |
|
44
|
|
|
{ |
|
45
|
31 |
|
if ($charTree->getRoot() === null) { |
|
46
|
7 |
|
return $charTree; |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
27 |
|
$formatted = []; |
|
50
|
|
|
|
|
51
|
27 |
|
foreach ($this->codeMap->getLengths() as $length) { |
|
52
|
27 |
|
foreach ($this->charExtractor->cut($charTree, $length) as [$root, $tree]) { |
|
53
|
22 |
|
assert(is_string($root)); |
|
54
|
22 |
|
assert(is_object($tree)); |
|
55
|
|
|
|
|
56
|
22 |
|
$branch = $this->applyCurrent($tree); |
|
57
|
22 |
|
foreach ($this->codeMap->code($root) as $codedChar) { |
|
58
|
27 |
|
$formatted[] = CharTree::fromString($codedChar, [$branch]); |
|
59
|
|
|
} |
|
60
|
|
|
} |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
27 |
|
return CharTree::fromString('', $formatted); |
|
64
|
|
|
} |
|
65
|
|
|
} |
|
66
|
|
|
|