Passed
Push — master ( 85a2d4...167ff7 )
by Dāvis
04:44
created

Helper::validatePersonCode()   B

Complexity

Conditions 7
Paths 5

Size

Total Lines 21
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 10
nc 5
nop 1
dl 0
loc 21
rs 7.551
c 0
b 0
f 0
1
<?php
2
3
namespace Sludio\HelperBundle\Script\Utils;
4
5
use Symfony\Component\HttpFoundation\Request;
6
7
class Helper
8
{
9
    // @formatter:off
10
    /**
11
     * Cyrillic mapping.
12
     *
13
     * @var array
14
     */
15
    protected static $cyrMap = array(
16
        'е', 'ё', 'ж', 'х', 'ц', 'ч', 'ш', 'щ', 'ю', 'я',
17
        'Е', 'Ё', 'Ж', 'Х', 'Ц', 'Ч', 'Ш', 'Щ', 'Ю', 'Я',
18
        'а', 'б', 'в', 'г', 'д', 'з', 'и', 'й', 'к', 'л', 'м', 'н', 'о', 'п', 'р', 'с', 'т', 'у', 'ф', 'ъ', 'ы', 'ь', 'э',
19
        'А', 'Б', 'В', 'Г', 'Д', 'З', 'И', 'Й', 'К', 'Л', 'М', 'Н', 'О', 'П', 'Р', 'С', 'Т', 'У', 'Ф', 'Ъ', 'Ы', 'Ь', 'Э'
20
    );
21
22
    /**
23
     * Latin mapping.
24
     *
25
     * @var array
26
     */
27
    protected static $latMap = array(
28
        'ye', 'ye', 'zh', 'kh', 'ts', 'ch', 'sh', 'shch', 'yu', 'ya',
29
        'Ye', 'Ye', 'Zh', 'Kh', 'Ts', 'Ch', 'Sh', 'Shch', 'Yu', 'Ya',
30
        'a', 'b', 'v', 'g', 'd', 'z', 'i', 'y', 'k', 'l', 'm', 'n', 'o', 'p', 'r', 's', 't', 'u', 'f', 'ʺ', 'y', '–', 'e',
31
        'A', 'B', 'V', 'G', 'D', 'Z', 'I', 'Y', 'K', 'L', 'M', 'N', 'O', 'P', 'R', 'S', 'T', 'U', 'F', 'ʺ', 'Y', '–', 'E'
32
    );
33
    // @formatter:on
34
35
    public static function toCamelCase($string)
36
    {
37
        return preg_replace('~\s+~', '', lcfirst(ucwords(str_replace('_', ' ', $string))));
38
    }
39
40
    public static function fromCamelCase($string, $separator = '_')
41
    {
42
        return strtolower(preg_replace('/(?!^)[[:upper:]]+/', $separator.'$0', $string));
43
    }
44
45
    public static function isEmpty($variable)
46
    {
47
        $result = true;
48
49
        if (\is_array($variable) && \count($variable) > 0) {
50
            foreach ($variable as $value) {
51
                $result = $result && self::isEmpty($value);
52
            }
53
        } else {
54
            $result = empty($variable);
55
        }
56
57
        return $result;
58
    }
59
60
    public static function getUniqueId($length = 20)
61
    {
62
        try {
63
            $output = bin2hex(random_bytes($length));
64
        } catch (\Exception $exception) {
65
            $output = substr(str_shuffle(str_repeat($x = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', (int)ceil((int)($length / \strlen($x))))), 1, $length);
66
        }
67
68
        return $output;
69
    }
70
71
    public static function validatePersonCode($personCode = null)
72
    {
73
        if ($personCode !== null) {
74
            $personCode = str_replace('-', '', $personCode);
75
76
            if (\strlen($personCode) !== 11) {
77
                return 'error_length';
78
            }
79
80
            if (preg_match('/^\d+$/', $personCode) === null) {
81
                return 'error_symbols';
82
            }
83
84
            if (((int)substr($personCode, 0, 2) === 32 && !self::newPKValidate($personCode)) || !self::validateDate($personCode)) {
85
                return 'error_invalid';
86
            }
87
88
            return true;
89
        }
90
91
        return 'error_empty';
92
    }
93
94
    public static function validateDate($date)
95
    {
96
        $date = str_replace('-', '', $date);
97
        $day = (int)substr($date, 0, 2);
98
        $month = (int)substr($date, 2, 2);
99
100
        if ($month < 0 || $month > 12) {
101
            return false;
102
        }
103
        // @formatter:off
104
        $months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
105
        // @formatter:on
106
        if ((int)substr($date, 4, 2) % 4 === 0) {
107
            $months[1] = 29;
108
        }
109
110
        return $day > 0 && $day <= $months[$month - 1];
111
    }
112
113
    public static function validateDate2($date, $format = 'd-m-Y H:i:s')
114
    {
115
        $object = \DateTime::createFromFormat($format, $date);
116
117
        return $object && $object->format($format) === $date;
118
    }
119
120
    public static function excelDate($timestamp, $format = 'd-m-Y H:i:s')
121
    {
122
        $base = 25569;
123
        if ($timestamp >= $base) {
124
            $unix = ($timestamp - $base) * 86400;
125
            $date = gmdate($format, $unix);
126
            if (self::validateDate2($date, $format)) {
127
                return $date;
128
            }
129
        }
130
131
        return $timestamp;
132
    }
133
134
    public static function newPKValidate($personCode)
135
    {
136
        $personCode = str_replace('-', '', $personCode);
137
138
        // @formatter:off
139
        $calculations = [1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
140
        // @formatter:on
141
142
        $sum = 0;
143
        foreach ($calculations as $key => $calculation) {
144
            $sum += ($personCode[$key] * $calculation);
145
        }
146
147
        $remainder = $sum % 11;
148
149
        if (1 - $remainder < -1) {
150
            return $personCode[10] === (1 - $remainder + 11);
151
        }
152
153
        return $personCode[10] === (1 - $remainder);
154
    }
155
156
    public static function swap(&$foo, &$bar)
157
    {
158
        $tmp = $foo;
159
        $foo = $bar;
160
        $bar = $tmp;
161
    }
162
163
    public static function removeDuplicates(&$array)
164
    {
165
        $array = array_map('unserialize', array_unique(array_map('serialize', $array)));
166
    }
167
168
    public static function cleanText($text)
169
    {
170
        return html_entity_decode(self::oneSpace(str_replace(' ?', '', mb_convert_encoding(strip_tags($text), 'UTF-8', 'UTF-8'))));
171
    }
172
173
    public static function oneSpace($text)
174
    {
175
        return preg_replace('/\s+/S', ' ', $text);
176
    }
177
178
    /**
179
     * Transliterates cyrillic text to latin.
180
     *
181
     * @param  string $text cyrillic text
182
     *
183
     * @return string latin text
184
     */
185
    public static function translit2($text)
186
    {
187
        return str_replace(self::$cyrMap, self::$latMap, $text);
188
    }
189
190
    /**
191
     * Transliterates latin text to cyrillic.
192
     *
193
     * @param  string $text latin text
194
     *
195
     * @return string cyrillic text
196
     */
197
    public static function translit4($text)
198
    {
199
        return str_replace(self::$latMap, self::$cyrMap, $text);
200
    }
201
202
    public static function multiple(array $keys)
203
    {
204
        foreach ($keys as $key) {
205
            if (!\is_array($key)) {
206
                return false;
207
            }
208
        }
209
210
        return true;
211
    }
212
213
    public static function multiset(array $keys)
214
    {
215
        foreach ($keys as $key) {
216
            if ($key === null) {
217
                return false;
218
            }
219
        }
220
221
        return true;
222
    }
223
224
    public static function useHttps(Request $request)
225
    {
226
        return $request->server->get('HTTPS') || ($request->server->get('HTTP_X_FORWARDED_PROTO') && $request->server->get('HTTP_X_FORWARDED_PROTO') === 'https');
227
    }
228
}
229