Clean   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 6
eloc 26
dl 0
loc 60
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A fixQuotes() 0 3 1
A compileRegexp() 0 3 1
A run() 0 23 4
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($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|int|null $value
43
     * @param   string $type
44
     * @return  mixed
45
     */
46
    public static function run($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