Passed
Push — master ( ec05e1...ba420a )
by Magnar Ovedal
03:08
created

LeetspeakMap::getMap()   A

Complexity

Conditions 5
Paths 8

Size

Total Lines 19
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 5

Importance

Changes 0
Metric Value
cc 5
eloc 8
nc 8
nop 1
dl 0
loc 19
ccs 9
cts 9
cp 1
crap 5
rs 9.6111
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Stadly\PasswordPolice\CodeMap;
6
7
use Stadly\PasswordPolice\CharTree;
8
use Stadly\PasswordPolice\CodeMap;
9
10
final class LeetspeakMap implements CodeMap
11
{
12
    private const ENCODE_MAP = [
13
        'A' => ['4', '@', '∂'],
14
        'B' => ['8', 'ß'],
15
        'C' => ['(', '¢', '<', '[', '©'],
16
        'D' => ['∂'],
17
        'E' => ['3', '€', 'є'],
18
        'F' => ['ƒ'],
19
        'G' => ['6', '9'],
20
        'H' => ['#'],
21
        'I' => ['1', '!', '|', ':'],
22
        'J' => ['¿'],
23
        'K' => ['X'],
24
        'L' => ['1', '£', 'ℓ'],
25
        'O' => ['0', '°'],
26
        'R' => ['2', '®', 'Я'],
27
        'S' => ['5', '$', '§'],
28
        'T' => ['7', '†'],
29
        'U' => ['µ'],
30
        'W' => ['vv'],
31
        'X' => ['×'],
32
        'Y' => ['φ', '¥'],
33
        'Z' => ['2', '≥'],
34
    ];
35
36
    /**
37
     * @var array<int, array<string|int, string[]>> Leetspeak code map.
38
     */
39
    private $codeMap = [];
40
41
    /**
42
     * @param bool $encode Whether the map should encode or decode Leetspeak.
43
     */
44 2
    public function __construct($encode = false)
45
    {
46 2
        if ($encode) {
47 1
            foreach (self::ENCODE_MAP as $char => $codedChars) {
48 1
                $this->codeMap[mb_strlen($char)][mb_strtoupper($char)] = $codedChars;
49
            }
50
        } else {
51 1
            $codeMap = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $codeMap is dead and can be removed.
Loading history...
52 1
            foreach (self::ENCODE_MAP as $char => $codedChars) {
53 1
                foreach ($codedChars as $codedChar) {
54 1
                    $this->codeMap[mb_strlen($codedChar)][mb_strtoupper($codedChar)][] = $char;
55
                }
56
            }
57
        }
58 2
    }
59
60
    /**
61
     * {@inheritDoc}
62
     */
63 2
    public function getMap(CharTree $charTree): array
64
    {
65 2
        $codeMap = [];
66
67
        // Add coded characters.
68 2
        foreach ($this->codeMap as $length => $chars) {
69 2
            foreach ($charTree->getTreeTrimmedToLength($length) as $char) {
70 2
                if (isset($chars[mb_strtoupper($char)])) {
71 2
                    $codeMap[$char] = $chars[mb_strtoupper($char)];
72
                }
73
            }
74
        }
75
76
        // Add uncoded characters.
77 2
        foreach ($charTree->getTreeTrimmedToLength(1) as $char) {
78 2
            $codeMap[$char][] = $char;
79
        }
80
81 2
        return $codeMap;
82
    }
83
}
84