Completed
Push — master ( 769e25...bb4ee9 )
by Maxim
02:29
created

APIhelpers::cleanIDs()   C

Complexity

Conditions 8
Paths 9

Size

Total Lines 24
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 24
rs 5.7377
cc 8
eloc 16
nc 9
nop 3
1
<?php
2
3
/**
4
 * Class APIhelpers
5
 */
6
class APIhelpers
7
{
8
9
    /**
10
     * Преобразует первый символ в нижний регистр
11
     * @param $str
12
     * @param string $encoding - кодировка, по-умолчанию UTF-8
13
     * @return string
14
     */
15
    public static function mb_lcfirst($str, $encoding = 'UTF-8')
0 ignored issues
show
Coding Style introduced by
Method name "APIhelpers::mb_lcfirst" is not in camel caps format
Loading history...
Coding Style introduced by
This method is not in camel caps format.

This check looks for method names that are not written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection seeker becomes databaseConnectionSeeker.

Loading history...
16
    {
17
        return mb_strtolower(mb_substr($str, 0, 1, $encoding), $encoding) . mb_substr(
18
            $str,
19
            1,
20
            mb_strlen($str),
21
            $encoding
22
        );
23
    }
24
25
    /**
26
     * mb_ucfirst - преобразует первый символ в верхний регистр
27
     * @param string $str - строка
28
     * @param string $encoding - кодировка, по-умолчанию UTF-8
29
     * @return string
30
     */
31
    public static function mb_ucfirst($str, $encoding = 'UTF-8')
0 ignored issues
show
Coding Style introduced by
Method name "APIhelpers::mb_ucfirst" is not in camel caps format
Loading history...
Coding Style introduced by
This method is not in camel caps format.

This check looks for method names that are not written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection seeker becomes databaseConnectionSeeker.

Loading history...
32
    {
33
        $str = mb_ereg_replace('^[\ ]+', '', $str);
34
        $str = mb_strtoupper(mb_substr($str, 0, 1, $encoding), $encoding) . mb_substr(
35
            $str,
36
            1,
37
            mb_strlen($str),
38
            $encoding
39
        );
40
41
        return $str;
42
    }
43
44
    /**
45
     * Обрезание текста по длине с поиском последнего полностью вмещающегося слова и удалением лишних крайних знаков пунктуации.
46
     *
47
     * @author Agel_Nash <[email protected]>
48
     * @version 0.1
49
     *
50
     * @param string $html HTML текст
51
     * @param integer $len максимальная длина строки
52
     * @param string $encoding кодировка
53
     * @return string
54
     */
55
    public static function mb_trim_word($html, $len, $encoding = 'UTF-8')
0 ignored issues
show
Coding Style introduced by
Method name "APIhelpers::mb_trim_word" is not in camel caps format
Loading history...
Coding Style introduced by
This method is not in camel caps format.

This check looks for method names that are not written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection seeker becomes databaseConnectionSeeker.

Loading history...
56
    {
57
        $text = trim(preg_replace('|\s+|', ' ', strip_tags($html)));
58
        $text = mb_substr($text, 0, $len + 1, $encoding);
59
        if (mb_substr($text, -1, null, $encoding) == ' ') {
60
            $out = trim($text);
61
        } else {
62
            $out = mb_substr($text, 0, mb_strripos($text, ' ', null, $encoding), $encoding);
63
        }
64
65
        return preg_replace("/(([\.,\-:!?;\s])|(&\w+;))+$/ui", "", $out);
66
    }
67
68
    /**
69
     * Получение значения по ключу из массива, либо возврат значения по умолчанию
70
     *
71
     * @param mixed $data массив
72
     * @param string $key ключ массива
73
     * @param mixed $default null значение по умолчанию
74
     * @param Closure $validate null функция дополнительной валидации значения (должна возвращать true или false)
75
     * @return mixed
76
     */
77
    public static function getkey($data, $key, $default = null, $validate = null)
78
    {
79
        $out = $default;
80
        if (is_array($data) && (is_int($key) || is_string($key)) && $key !== '' && array_key_exists($key, $data)) {
81
            $out = $data[$key];
82
        }
83
        if (!empty($validate) && is_callable($validate)) {
0 ignored issues
show
Coding Style introduced by
There must be a single space after a NOT operator; 0 found
Loading history...
84
            $out = (($validate($out) === true) ? $out : $default);
85
        }
86
        return $out;
87
    }
88
89
    /**
90
     * Email validate
91
     *
92
     * @category   validate
93
     * @version    0.1
94
     * @license    GNU General Public License (GPL), http://www.gnu.org/copyleft/gpl.html
95
     * @param string $email проверяемый email
96
     * @param boolean $dns проверять ли DNS записи
97
     * @return boolean Результат проверки почтового ящика
98
     * @author Anton Shevchuk
99
     */
100
    public static function emailValidate($email, $dns = true)
101
    {
102
        if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
103
            list(, $domain) = explode("@", $email, 2);
104
            if (!$dns || ($dns && checkdnsrr($domain, "MX") && checkdnsrr($domain, "A"))) {
0 ignored issues
show
Coding Style introduced by
There must be a single space after a NOT operator; 0 found
Loading history...
105
                $error = false;
106
            } else {
107
                $error = 'dns';
108
            }
109
        } else {
110
            $error = 'format';
111
        }
112
113
        return $error;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $error also could return the type string which is incompatible with the documented return type boolean.
Loading history...
114
    }
115
116
    /**
117
     * Password generate
118
     *
119
     * @category   generate
120
     * @version   0.1
121
     * @license    GNU General Public License (GPL), http://www.gnu.org/copyleft/gpl.html
122
     * @param string $len длина пароля
123
     * @param string $data правила генерации пароля
124
     * @return string Строка с паролем
125
     * @author Agel_Nash <[email protected]>
126
     *
127
     * Расшифровка значений $data
128
     * "A": A-Z буквы
129
     * "a": a-z буквы
130
     * "0": цифры
131
     * ".": все печатные символы
132
     *
133
     * @example
134
     * $this->genPass(10,"Aa"); //nwlTVzFdIt
135
     * $this->genPass(8,"0"); //71813728
136
     * $this->genPass(11,"A"); //VOLRTMEFAEV
137
     * $this->genPass(5,"a0"); //4hqi7
138
     * $this->genPass(5,"."); //2_Vt}
139
     * $this->genPass(20,"."); //AMV,>&?J)v55,(^g}Z06
140
     * $this->genPass(20,"aaa0aaa.A"); //rtvKja5xb0\KpdiRR1if
141
     */
142
    public static function genPass($len, $data = '')
143
    {
144
        if ($data == '') {
145
            $data = 'Aa0.';
146
        }
147
        $opt = strlen($data);
148
        $pass = array();
149
150
        for ($i = $len; $i > 0; $i--) {
151
            switch ($data[rand(0, ($opt - 1))]) {
152
                case 'A':
153
                    $tmp = rand(65, 90);
154
                    break;
155
                case 'a':
156
                    $tmp = rand(97, 122);
157
                    break;
158
                case '0':
159
                    $tmp = rand(48, 57);
160
                    break;
161
                default:
162
                    $tmp = rand(33, 126);
163
            }
164
            $pass[] = chr($tmp);
165
        }
166
        $pass = implode("", $pass);
167
168
        return $pass;
169
    }
170
171
    /**
172
     * @param $data
173
     * @return bool|false|string
174
     */
175
    public static function getEnv($data)
176
    {
177
        switch (true) {
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing $tmp = getenv($data) of type string to the boolean true. If you are specifically checking for a non-empty string, consider using the more explicit !== '' instead.
Loading history...
178
            case (isset($_SERVER[$data])):
179
                $out = $_SERVER[$data];
180
                break;
181
            case (isset($_ENV[$data])):
182
                $out = $_ENV[$data];
183
                break;
184
            case ($tmp = getenv($data)):
185
                $out = $tmp;
186
                break;
187
            case (function_exists('apache_getenv') && $tmp = apache_getenv($data, true)):
188
                $out = $tmp;
189
                break;
190
            default:
191
                $out = false;
192
        }
193
        unset($tmp);
194
195
        return $out;
196
    }
197
198
    /**
199
     * User IP
200
     *
201
     * @category   validate
202
     * @version   0.1
203
     * @license    GNU General Public License (GPL), http://www.gnu.org/copyleft/gpl.html
204
     * @param string $default IP адрес который будет отдан функцией, если больше ничего не обнаружено
205
     * @return string IP пользователя
206
     * @author Agel_Nash <[email protected]>
207
     *
208
     * @see http://stackoverflow.com/questions/5036443/php-how-to-block-proxies-from-my-site
209
     */
210
    public static function getUserIP($default = '127.0.0.1')
0 ignored issues
show
Coding Style introduced by
This method is not in camel caps format.

This check looks for method names that are not written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection seeker becomes databaseConnectionSeeker.

Loading history...
211
    {
212
        //Порядок условий зависит от приоритетов
213
        switch (true) {
214
            case ($tmp = self::getEnv('HTTP_COMING_FROM')):
215
                $out = $tmp;
216
                break;
217
            case ($tmp = self::getEnv('HTTP_X_COMING_FROM')):
218
                $out = $tmp;
219
                break;
220
            case ($tmp = self::getEnv('HTTP_VIA')):
221
                $out = $tmp;
222
                break;
223
            case ($tmp = self::getEnv('HTTP_FORWARDED')):
224
                $out = $tmp;
225
                break;
226
            case ($tmp = self::getEnv('HTTP_FORWARDED_FOR')):
227
                $out = $tmp;
228
                break;
229
            case ($tmp = self::getEnv('HTTP_X_FORWARDED')):
230
                $out = $tmp;
231
                break;
232
            case ($tmp = self::getEnv('HTTP_X_FORWARDED_FOR')):
233
                $out = $tmp;
234
                break;
235
            case (!empty($_SERVER['REMOTE_ADDR'])):
0 ignored issues
show
Coding Style introduced by
There must be a single space after a NOT operator; 0 found
Loading history...
236
                $out = $_SERVER['REMOTE_ADDR'];
237
                break;
238
            default:
239
                $out = false;
240
        }
241
        unset($tmp);
242
243
        return (false !== $out && preg_match('|^(?:[0-9]{1,3}\.){3,3}[0-9]{1,3}$|', $out, $matches)) ? $out : $default;
244
    }
245
246
    /**
247
     * @param $data
248
     * @param string $charset
249
     * @param array $chars
250
     * @return array|mixed|string
251
     */
252
    public static function sanitarTag(
253
        $data,
254
        $charset = 'UTF-8',
255
        $chars = array(
256
            '['   => '&#91;',
257
            '%5B' => '&#91;',
258
            ']'   => '&#93;',
259
            '%5D' => '&#93;',
260
            '{'   => '&#123;',
261
            '%7B' => '&#123;',
262
            '}'   => '&#125;',
263
            '%7D' => '&#125;',
264
            '`'   => '&#96;',
265
            '%60' => '&#96;'
266
        )
267
    ) {
268
        switch (true) {
269
            case is_scalar($data):
270
                $out = str_replace(
271
                    array_keys($chars),
272
                    array_values($chars),
273
                    is_null($charset) ? $data : self::e($data, $charset)
0 ignored issues
show
introduced by
The condition is_null($charset) is always false.
Loading history...
274
                );
275
                break;
276
            case is_array($data):
277
                $out = $data;
278
                foreach ($out as $key => &$val) {
279
                    $val = self::sanitarTag($val, $charset, $chars);
280
                }
281
                break;
282
            default:
283
                $out = '';
284
        }
285
286
        return $out;
287
    }
288
289
    /**
290
     * @param $text
291
     * @param string $charset
292
     * @return string
293
     */
294
    public static function e($text, $charset = 'UTF-8')
295
    {
296
        return is_scalar($text) ? htmlspecialchars($text, ENT_QUOTES, $charset, false) : '';
297
    }
298
299
    /**
300
     * Проверка строки на наличе запрещенных символов
301
     * Проверка конечно круто, но валидация русских символов в строке порой завершается не удачей по разным причинам
302
     * (начиная от кривых настроек сервера и заканчивая кривыми настройками кодировки на сайте)
303
     *
304
     * @param string $value Проверяемая строка
305
     * @param int $minLen Минимальная длина строки
306
     * @param array $alph Разрешенные алфавиты
307
     * @param array $mixArray Примесь символов, которые так же могут использоваться в строке
308
     * @return bool
309
     */
310
    public static function checkString($value, $minLen = 1, $alph = array(), $mixArray = array())
0 ignored issues
show
Coding Style introduced by
Function's nesting level (5) exceeds 3; consider refactoring the function
Loading history...
311
    {
312
        $flag = true;
313
        $len = mb_strlen($value, 'UTF-8');
314
        $value = trim($value);
315
        if (mb_strlen($value, 'UTF-8') == $len) {
316
            $data = is_array($mixArray) ? $mixArray : array();
0 ignored issues
show
introduced by
The condition is_array($mixArray) is always true.
Loading history...
317
            $alph = is_array($alph) ? array_unique($alph) : array();
0 ignored issues
show
introduced by
The condition is_array($alph) is always true.
Loading history...
318
            foreach ($alph as $item) {
319
                $item = strtolower($item);
320
                switch ($item) {
321
                    case 'rus':
322
                        $data = array_merge($data, array(
323
                            'А',
324
                            'Б',
325
                            'В',
326
                            'Г',
327
                            'Д',
328
                            'Е',
329
                            'Ё',
330
                            'Ж',
331
                            'З',
332
                            'И',
333
                            'Й',
334
                            'К',
335
                            'Л',
336
                            'М',
337
                            'Н',
338
                            'О',
339
                            'П',
340
                            'Р',
341
                            'С',
342
                            'Т',
343
                            'У',
344
                            'Ф',
345
                            'Х',
346
                            'Ц',
347
                            'Ч',
348
                            'Ш',
349
                            'Щ',
350
                            'Ъ',
351
                            'Ы',
352
                            'Ь',
353
                            'Э',
354
                            'Ю',
355
                            'Я'
356
                        ));
357
                        break;
358
                    case 'num':
359
                        $tmp = range('0', '9');
360
                        foreach ($tmp as $t) {
361
                            $data[] = (string)$t;
362
                        }
363
                        break;
364
                    case 'eng':
365
                        $data = array_merge($data, range('A', 'Z'));
366
                        break;
367
                }
368
            }
369
            for ($i = 0; $i < $len; $i++) {
370
                $chr = mb_strtoupper(mb_substr($value, $i, 1, 'UTF-8'), 'UTF-8');
371
                if (!in_array($chr, $data, true)) {
0 ignored issues
show
Coding Style introduced by
There must be a single space after a NOT operator; 0 found
Loading history...
372
                    $flag = false;
373
                    break;
374
                }
375
            }
376
            $flag = ($flag && $len >= $minLen);
377
        } else {
378
            $flag = false;
379
        }
380
381
        return $flag;
382
    }
383
384
    /**
385
     * @param $IDs
386
     * @param string $sep
387
     * @param integer[] $ignore
388
     * @return array
389
     * @throws Exception
390
     */
391
    public static function cleanIDs($IDs, $sep = ',', $ignore = array())
0 ignored issues
show
Coding Style introduced by
This method is not in camel caps format.

This check looks for method names that are not written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection seeker becomes databaseConnectionSeeker.

Loading history...
392
    {
393
        $out = array();
394
        if (!is_array($IDs)) {
0 ignored issues
show
Coding Style introduced by
There must be a single space after a NOT operator; 0 found
Loading history...
395
            if (is_scalar($IDs)) {
396
                $IDs = explode($sep, $IDs);
397
            } else {
398
                $IDs = array();
399
                throw new Exception('Invalid IDs list <pre>' . print_r($IDs, 1) . '</pre>');
400
            }
401
        }
402
        foreach ($IDs as $item) {
403
            $item = trim($item);
404
            if (is_scalar($item) && (int)$item >= 0) { //Fix 0xfffffffff
405
                if (!empty($ignore) && in_array((int)$item, $ignore, true)) {
0 ignored issues
show
Coding Style introduced by
There must be a single space after a NOT operator; 0 found
Loading history...
406
                    $this->log[] = 'Ignore id ' . (int)$item;
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using $this inside a static method is generally not recommended and can lead to errors in newer PHP versions.
Loading history...
Bug Best Practice introduced by
The property log does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
407
                } else {
408
                    $out[] = (int)$item;
409
                }
410
            }
411
        }
412
        $out = array_unique($out);
413
414
        return $out;
415
    }
416
417
    /**
418
     * Переменовывание элементов массива
419
     *
420
     * @param array $data массив с данными
421
     * @param string $prefix префикс ключей
422
     * @param string $suffix суффикс ключей
423
     * @param string $addPS разделитель суффиксов, префиксов и ключей массива
424
     * @param string $sep разделитель ключей при склейке многомерных массивов
425
     * @return array массив с переименованными ключами
426
     */
427
    public static function renameKeyArr($data, $prefix = '', $suffix = '', $addPS = '.', $sep = '.')
0 ignored issues
show
Coding Style introduced by
Function's nesting level (4) exceeds 3; consider refactoring the function
Loading history...
428
    {
429
        $out = array();
430
        if ($prefix == '' && $suffix == '') {
431
            $out = $data;
432
        } else {
433
            $InsertPrefix = ($prefix != '') ? ($prefix . $addPS) : '';
434
            $InsertSuffix = ($suffix != '') ? ($addPS . $suffix) : '';
435
            foreach ($data as $key => $item) {
436
                $key = $InsertPrefix . $key;
437
                $val = null;
438
                switch (true) {
439
                    case is_scalar($item):
440
                        $val = $item;
441
                        break;
442
                    case is_array($item):
443
                        $val = self::renameKeyArr($item, $key . $sep, $InsertSuffix, '', $sep);
444
                        $out = array_merge($out, $val);
445
                        $val = '';
446
                        break;
447
                }
448
                $out[$key . $InsertSuffix] = $val;
449
            }
450
        }
451
452
        return $out;
453
    }
454
}
455