Completed
Push — master ( 904fb3...48b549 )
by Sebastian
07:01
created

Escape::htmlEscape()   B

Complexity

Conditions 3
Paths 3

Size

Total Lines 25
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 15
nc 3
nop 1
dl 0
loc 25
ccs 11
cts 11
cp 1
crap 3
rs 8.8571
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * Linna Filter
5
 *
6
 * @author Sebastian Rapetti <[email protected]>
7
 * @copyright (c) 2018, Sebastian Rapetti
8
 * @license http://opensource.org/licenses/MIT MIT License
9
 */
10
declare(strict_types = 1);
11
12
namespace Linna\Filter\Rules;
13
14
/**
15
 * Return html entities.
16
 */
17
class Escape
18
{
19
    /**
20
     * @var array Arguments expected.
21
     */
22
    private $arguments = [];
0 ignored issues
show
introduced by
The private property $arguments is not used, and could be removed.
Loading history...
23
    
24
    /**
25
     * Sanitize.
26
     *
27
     * @param mixed $value
28
     */
29 12
    public function sanitize(&$value): void
30
    {
31 12
        $value = $this->htmlEscape($value);
32 12
    }
33
    
34
    /**
35
     * Return numerical part of the HTML encoding of the Unicode character.
36
     *
37
     * @param string $char
38
     * @return int
39
     */
40 12
    private function ordutf8(string $char): int
41
    {
42 12
        $code = ord(substr($char, 0, 1));
43
44 12
        if ($code > 239) {
45 3
            return ((ord(substr($char, 1, 1)) - 128) *
46 3
                    64 + ord(substr($char, 2, 1)) - 128) *
47 3
                    64 + ord(substr($char, 3, 1)) - 128;
48
        }
49
50 10
        if ($code > 223) {
51 2
            return (($code - 224) * 64 + ord(substr($char, 1, 1)) - 128)
52 2
                    * 64 + ord(substr($char, 2, 1)) - 128;
53
        }
54
55 9
        if ($code > 127) {
56 2
            return ($code - 192) * 64 + ord(substr($char, 1, 1)) - 128;
57
        }
58
59 7
        return $code;
60
    }
61
62
    /**
63
     * Convert char to html entities.
64
     *
65
     * @param string $string
66
     * @return string
67
     */
68 12
    private function htmlEscape(string $string): string
69
    {
70 12
        $chars = preg_split('//u', $string, 0, PREG_SPLIT_NO_EMPTY);
71 12
        $escaped = '';
72
73
        $permitted = [
74 12
            32,48,49,50,51,52,53,54,55,56,57,65,66,67,68,
75
            69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,
76
            84,85,86,87,88,89,90,97,98,99,100,101,102,103,
77
            104,105,106,107,108,109,110,111,112,113,114,
78
            115,116,117,118,119,120,121,122
79
        ];
80
81 12
        foreach ($chars as $char) {
82 12
            $ord = $this->ordutf8($char);
83
84 12
            if (!in_array($ord, $permitted)) {
85 9
                $escaped .= "&#{$ord};";
86 9
                continue;
87
            }
88
89 7
            $escaped .= $char;
90
        }
91
92 12
        return $escaped;
93
    }
94
}
95