Passed
Push — master ( bab290...961f54 )
by Magnar Ovedal
03:07
created

Leetspeak::convert()   B

Complexity

Conditions 7
Paths 13

Size

Total Lines 19
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 7

Importance

Changes 0
Metric Value
cc 7
eloc 12
nc 13
nop 1
dl 0
loc 19
ccs 13
cts 13
cp 1
crap 7
rs 8.8333
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
     * {@inheritDoc}
54
     */
55 2
    public function convert(string $word): Traversable
56
    {
57 2
        if ($word === '') {
58 2
            yield '';
59 2
            return;
60
        }
61
62 2
        $decodeMap = [];
63 2
        foreach ($this->decodeMap as $encodedChar => $chars) {
64 2
            if ((string)$encodedChar === mb_substr($word, 0, mb_strlen((string)$encodedChar))) {
65 2
                $decodeMap[$encodedChar] = $chars;
66
            }
67
        }
68 2
        $decodeMap[mb_substr($word, 0, 1)][] = mb_substr($word, 0, 1);
69
70 2
        foreach ($decodeMap as $encodedChar => $chars) {
71 2
            foreach ($this->convert(mb_substr($word, mb_strlen((string)$encodedChar))) as $suffix) {
72 2
                foreach ($chars as $char) {
73 2
                    yield $char.$suffix;
74
                }
75
            }
76
        }
77 2
    }
78
}
79