Passed
Push — master ( bc3133...da8a8a )
by Mr
02:32
created

Clean::compileRegexp()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
eloc 1
nc 1
nop 1
1
<?php
2
3
namespace DrMVC\Helpers;
4
5
/**
6
 * Clean variables from bad content
7
 * @package DrMVC\Helpers
8
 */
9
class Clean
10
{
11
    const INT = '0-9';
12
    const FLOAT = self::INT . '\,\.';
13
    const CHARS_RUS = 'а-яё';
14
    const CHARS_ENG = 'a-z';
15
    const SUPER = '\*\#\ \n\r';
16
17
    /**
18
     * Convert quotes to save format
19
     *
20
     * @param   string $value
21
     * @return  string
22
     */
23
    private static function fixQuotes(string $value): string
24
    {
25
        return htmlspecialchars(addslashes($value), ENT_QUOTES);
26
    }
27
28
    /**
29
     * Compile regexp from string
30
     *
31
     * @param   string $line
32
     * @return  string
33
     */
34
    private static function compileRegexp(string $line): string
35
    {
36
        return '#[^' . $line . ']#iu';
37
    }
38
39
    /**
40
     * Cleanup the value
41
     *
42
     * @param   string $value
43
     * @param   string $type
44
     * @return  mixed
45
     */
46
    public static function run(string $value, string $type = null)
47
    {
48
        switch ($type) {
49
            case 'int':
50
                $regexp = self::compileRegexp(self::INT);
51
                break;
52
            case 'float':
53
                $regexp = self::compileRegexp(self::FLOAT);
54
                break;
55
            case 'text':
56
                $value = self::fixQuotes($value);
57
                $regexp = self::compileRegexp(self::CHARS_RUS . self::CHARS_ENG);
58
                break;
59
            default:
60
                $value = self::fixQuotes($value);
61
                $regexp = self::compileRegexp(
62
                    self::CHARS_RUS . self::CHARS_ENG . self::FLOAT .
63
                    '—~`@%[]/:<>;?&()_!$^-+=' . self::SUPER
64
                );
65
                break;
66
        }
67
68
        return preg_replace($regexp, '', $value);
69
    }
70
71
}
72