Passed
Push — master ( 29aa9e...847fe9 )
by Magnar Ovedal
02:49
created

Leetspeak::getDecodeMap()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
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 11
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\WordConverter;
6
7
use Traversable;
8
9
final class Leetspeak implements WordConverterInterface
10
{
11
    /**
12
     * @var array<string, string[]>
13
     */
14
    private $encodeMap = [
15
        'A' => ['4', '@', '∂'],
16
        'B' => ['8', 'ß'],
17
        'C' => ['(', '¢', '<', '[', '©'],
18
        'D' => ['∂'],
19
        'E' => ['3', '€', 'є'],
20
        'F' => ['ƒ'],
21
        'G' => ['6', '9'],
22
        'H' => ['#'],
23
        'I' => ['1', '!', '|', ':'],
24
        'J' => ['¿'],
25
        'K' => ['X'],
26
        'L' => ['1', '£', 'ℓ'],
27
        'O' => ['0', '°'],
28
        'R' => ['2', '®', 'Я'],
29
        'S' => ['5', '$', '§'],
30
        'T' => ['7', '†'],
31
        'U' => ['µ'],
32
        'W' => ['vv'],
33
        'X' => ['×'],
34
        'Y' => ['φ', '¥'],
35
        'Z' => ['2', '≥'],
36
    ];
37
38
    /**
39
     * @var array<string, string[]>
40
     */
41
    private $decodeMap = [];
42
43 1
    public function __construct()
44
    {
45 1
        foreach ($this->encodeMap as $char => $encodedChars) {
46 1
            foreach ($encodedChars as $encodedChar) {
47 1
                $this->decodeMap[$encodedChar][] = $char;
48
            }
49
        }
50 1
    }
51
52
    /**
53
     * @param string $word Word to get decode map for.
54
     * @return array<string, string[]> Map for decoding the word prefix.
55
     */
56 2
    private function getDecodeMap(string $word): array
57
    {
58 2
        $decodeMap = [];
59 2
        foreach ($this->decodeMap as $encodedChar => $chars) {
60 2
            if ((string)$encodedChar === mb_substr($word, 0, mb_strlen((string)$encodedChar))) {
61 2
                $decodeMap[$encodedChar] = $chars;
62
            }
63
        }
64 2
        $decodeMap[mb_substr($word, 0, 1)][] = mb_substr($word, 0, 1);
65
66 2
        return $decodeMap;
67
    }
68
69
    /**
70
     * {@inheritDoc}
71
     */
72 2
    public function convert(string $word): Traversable
73
    {
74 2
        if ($word === '') {
75 2
            yield '';
76 2
            return;
77
        }
78
79 2
        foreach ($this->getDecodeMap($word) as $encodedChar => $chars) {
80 2
            foreach ($this->convert(mb_substr($word, mb_strlen((string)$encodedChar))) as $suffix) {
81 2
                foreach ($chars as $char) {
82 2
                    yield $char.$suffix;
83
                }
84
            }
85
        }
86 2
    }
87
}
88