Test Failed
Push — master ( f4b790...99250c )
by Alexey
04:49
created

Tools::rusPrice()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 2
dl 0
loc 4
ccs 0
cts 0
cp 0
crap 6
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * Tools object
5
 *
6
 * Toolkit with most needed functions
7
 *
8
 * @author Alexey Krupskiy <[email protected]>
9
 * @link http://inji.ru/
10
 * @copyright 2015 Alexey Krupskiy
11
 * @license https://github.com/injitools/cms-Inji/blob/master/LICENSE
12
 */
13
class Tools extends Model {
14
15
    /**
16
     * Return random string
17
     *
18
     * @param int $length
19
     * @param string $characters
20
     * @return string
21
     */
22
    public static function randomString($length = 20, $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') {
23
        $charactersLength = strlen($characters);
24
        $randomString = '';
25
        for ($i = 0; $i < $length; $i++) {
26
            $randomString .= $characters[rand(0, $charactersLength - 1)];
27
        }
28
        return $randomString;
29
    }
30
31
    /**
32
     * Clean and return user query params
33
     *
34
     * @param string $uri
35
     * @return array
36
     */
37
    public static function uriParse($uri) {
38
        $answerPos = strpos($uri, '?');
39
        $params = array_slice(explode('/', substr($uri, 0, $answerPos ? $answerPos : strlen($uri))), 1);
40
41
        foreach ($params as $key => $param) {
42
            if ($param != '') {
43
                $params[$key] = urldecode($param);
44
            } else {
45
                unset($params[$key]);
46
            }
47
        }
48
        return $params;
49
    }
50
51
    /**
52
     * Recursive create dir
53
     *
54
     * @param string $path
55
     * @return boolean
56
     */
57
    public static function createDir($path) {
58
        if (file_exists($path)) {
59
            return true;
60
        }
61
        $root = rtrim(str_replace(DIRECTORY_SEPARATOR, '/', $_SERVER['DOCUMENT_ROOT']), '/') . '/';
62
        if (strpos($path, $root) === 0) {
63
            $path = str_replace($root, '', $path);
64
        }
65
        $path = explode('/', $path);
66
        $cur = '';
67
        foreach ($path as $item) {
68
            $cur .= $item . '/';
69
            if (!file_exists($cur)) {
70
                mkdir($cur);
71
            }
72
        }
73
        return true;
74
    }
75
76
    public static function delDir($dir) {
77
        if (!file_exists($dir)) {
78
            return true;
79
        }
80
        $files = array_diff(scandir($dir), array('.', '..'));
81
        foreach ($files as $file) {
82
            is_dir("$dir/$file") ? self::delDir("$dir/$file") : unlink("$dir/$file");
83
        }
84
        return rmdir($dir);
85
    }
86
87
    /**
88
     * Resize image in path
89
     *
90
     * @param string $img_path
91
     * @param int $max_width
92
     * @param int $max_height
93
     * @param string|false $crop
94
     * @param string $pos
95
     * @return string
96
     */
97
    public static function resizeImage($img_path, $max_width = 1000, $max_height = 1000, $crop = false, $pos = 'center') {
98
        ini_set("gd.jpeg_ignore_warning", 1);
99
        if (!getimagesize($img_path)) {
100
            return false;
101
        }
102
        list($img_width, $img_height, $img_type, $img_tag) = getimagesize($img_path);
103
        switch ($img_type) {
104
            case 1:
105
                $img_type = 'gif';
106
                break;
107
            case 3:
108
                $img_type = 'png';
109
                break;
110
            case 2:
111
            default:
112
                $img_type = 'jpeg';
113
                break;
114
        }
115
        $imagecreatefromX = "imagecreatefrom{$img_type}";
116
        $src_res = @$imagecreatefromX($img_path);
117
        if (!$src_res) {
118
            return false;
119
        }
120
121
        if ($img_width / $max_width > $img_height / $max_height) {
122
            $separator = $img_width / $max_width;
123
        } else {
124
            $separator = $img_height / $max_height;
125
        }
126
127
        if ($crop === true || $crop == 'q') {
128
            if ($img_width > $img_height) {
129
                $imgX = floor(($img_width - $img_height) / 2);
130
                $imgY = 0;
131
                $img_width = $img_height;
132
                $new_width = $max_width;
133
                $new_height = $max_height;
134 View Code Duplication
            } else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
135
                $imgX = 0;
136
                $imgY = floor(($img_height - $img_width) / 2);
137
                $img_height = $img_width;
138
                $new_width = $max_width;
139
                $new_height = $max_height;
140
            }
141
            if ($pos == 'top') {
142
                $imgY = 0;
143
            }
144
        } elseif ($crop == 'c') {
145
//Вычисляем некий коэффициент масштабирования
146
            $k1 = $img_width / $max_width;
147
            $k2 = $img_height / $max_height;
148
            $k = $k1 > $k2 ? $k2 : $k1;
149
            $ow = $img_width;
150
            $oh = $img_height;
151
//Вычисляем размеры области для нового изображения
152
            $img_width = intval($max_width * $k);
153
            $img_height = intval($max_height * $k);
154
            $new_width = $max_width;
155
            $new_height = $max_height;
156
//Находим начальные координаты (центрируем новое изображение)
157
            $imgX = (int) (($ow / 2) - ($img_width / 2));
158
            if ($pos == 'center') {
159
                $imgY = (int) (($oh / 2) - ($img_height / 2));
160
            } else {
161
                $imgY = 0;
162
            }
163 View Code Duplication
        } else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
164
            $imgX = 0;
165
            $imgY = 0;
166
            $new_width = floor($img_width / $separator);
167
            $new_height = floor($img_height / $separator);
168
        }
169
170
        $new_res = imagecreatetruecolor($new_width, $new_height);
171
        imageAlphaBlending($new_res, false);
172
        imagesavealpha($new_res, true);
173
        imagecopyresampled($new_res, $src_res, 0, 0, $imgX, $imgY, $new_width, $new_height, $img_width, $img_height);
174
175
        if ($img_type == 'jpeg') {
176
            imageinterlace($new_res, 1); // чересстрочное формирование изображение
177
            imagejpeg($new_res, $img_path, 85);
178
        } else {
179
            $imageX = "image{$img_type}";
180
            $imageX($new_res, $img_path);
181
        }
182
183
        imagedestroy($new_res);
184
        imagedestroy($src_res);
185
        return $img_type;
186
    }
187
188
    /**
189
     * Send mail
190
     *
191
     * @param string $from
192
     * @param string $to
193
     * @param string $subject
194
     * @param string $text
195
     * @param string $charset
196
     * @param string $ctype
197
     * @return boolean
198
     */
199
    public static function sendMail($from, $to, $subject, $text, $charset = 'utf-8', $ctype = 'text/html') {
200
        $msg = compact('from', 'to', 'subject', 'text', 'charset', 'ctype');
201
        $msg = Inji::$inst->event('sendMail', $msg);
202
        if (is_array($msg)) {
203
            $headers = "From: {$msg['from']}\r\n";
204
            $headers .= "Content-type: {$msg['ctype']}; charset={$msg['charset']}\r\n";
205
            $headers .= "Mime-Version: 1.0\r\n";
206
            return mail($msg['to'], $msg['subject'], $msg['text'], $headers);
207
        }
208
        return $msg;
209
    }
210
211
    /**
212
     * Redirect user from any place of code
213
     *
214
     * Also add message to message query for view
215
     *
216
     * @param string $href
217
     * @param string $text
218
     * @param string $status
219
     */
220
    public static function redirect($href = null, $text = false, $status = 'info') {
221
        if ($href === null) {
222
            $href = $_SERVER['REQUEST_URI'];
223
        }
224
        if ($text !== false) {
225
            Msg::add($text, $status);
226
        }
227
        if (!headers_sent()) {
228
            header("Location: {$href}");
229
        } else {
230
            echo '\'"><script>window.location="' . $href . '";</script>';
231
        }
232
        exit("Перенаправление на: <a href = '{$href}'>{$href}</a>");
233
    }
234
235
    /**
236
     * Функция возвращает окончание для множественного числа слова на основании числа и массива окончаний
237
     * @param  Integer $number Число на основе которого нужно сформировать окончание
238
     * @param  String[] $endingArray Массив слов или окончаний для чисел (1, 4, 5),
239
     *         например ['яблоко', 'яблока', 'яблок']
240
     * @return String
241
     */
242
    public static function getNumEnding($number, $endingArray) {
243
        $number = $number % 100;
244
        if ($number >= 11 && $number <= 19) {
245
            $ending = $endingArray[2];
246
        } else {
247
            $i = $number % 10;
248
            switch ($i) {
249
                case (1):
250
                    $ending = $endingArray[0];
251
                    break;
252
                case (2):
253
                case (3):
254
                case (4):
255
                    $ending = $endingArray[1];
256
                    break;
257
                default:
258
                    $ending = $endingArray[2];
259
            }
260
        }
261
        return $ending;
262
    }
263
264
    /**
265
     * Clean request path
266
     *
267
     * @param string $path
268
     * @return string
269
     */
270
    public static function parsePath($path) {
271
        $path = str_replace('\\', '/', $path);
272
        $pathArray = explode('/', $path);
273
        $cleanPathArray = [];
274
        do {
275
            $changes = 0;
276
            foreach ($pathArray as $pathItem) {
277
                if (trim($pathItem) === '' || $pathItem == '.') {
278
                    $changes++;
279
                    continue;
280
                }
281
                if ($pathItem == '..') {
282
                    array_pop($cleanPathArray);
283
                    $changes++;
284
                    continue;
285
                }
286
                $cleanPathArray[] = $pathItem;
287
            }
288
            $pathArray = $cleanPathArray;
289
            $cleanPathArray = [];
290
        } while ($changes);
291
        return (strpos($path, '/') === 0 ? '/' : '') . implode('/', $pathArray);
292
    }
293
294
    /**
295
     * Show date in rus
296
     *
297
     * @param string $date
298
     * @return string
299
     */
300
    public static function toRusDate($date) {
301
        $yy = (int) substr($date, 0, 4);
302
        $mm = (int) substr($date, 5, 2);
303
        $dd = (int) substr($date, 8, 2);
304
305
        $hours = substr($date, 11, 5);
306
307
        $month = array('января', 'февраля', 'марта', 'апреля', 'мая', 'июня', 'июля', 'августа', 'сентября', 'октября', 'ноября', 'декабря');
308
        if (empty($month[$mm - 1])) {
309
            return 'Не указано';
310
        }
311
        return ($dd > 0 ? $dd . " " : '') . $month[$mm - 1] . " " . $yy . " " . $hours;
312
    }
313
314
    /**
315
     * Set header
316
     *
317
     * @param string $code
318
     * @param boolean $exit
319
     */
320
    public static function header($code, $exit = false) {
321
        if (!headers_sent()) {
322
            switch ($code) {
323
                case '404':
324
                    header('HTTP/1.1 404 Not Found');
325
                    break;
326
                default:
327
                    header($code);
328
            }
329
        }
330
        if ($exit) {
331
            exit;
332
        }
333
    }
334
335
    /**
336
     * Return exist path from array
337
     *
338
     * If no exist path in array - return default
339
     *
340
     * @param array $paths
341
     * @param string|boolean $default
342
     * @return string|boolean
343
     */
344
    public static function pathsResolve($paths = [], $default = false) {
345
        foreach ($paths as $path) {
346
            if (file_exists($path)) {
347
                return $path;
348
            }
349
        }
350
        return $default;
351
    }
352
353
    /**
354
     * Convert acronyms to bites
355
     *
356
     * @param string $val
357
     * @return int
358
     */
359
    public static function toBytes($val) {
360
        $val = trim($val);
361
        $last = strtolower($val[strlen($val) - 1]);
362
        switch ($last) {
363
            case 'g':
364
                $val *= 1024;
365
            // no break
366
            case 'm':
367
                $val *= 1024;
368
            // no break
369
            case 'k':
370
                $val *= 1024;
371
        }
372
373
        return $val;
374
    }
375
376
    /**
377
     * Recursive copy directories and files
378
     *
379
     * @param string $from
380
     * @param string $to
381
     */
382
    public static function copyFiles($from, $to) {
383
        $from = rtrim($from, '/');
384
        $to = rtrim($to, '/');
385
        self::createDir($to);
386
        $files = scandir($from);
387
        foreach ($files as $file) {
388
            if (in_array($file, ['.', '..'])) {
389
                continue;
390
            }
391
            if (is_dir($from . '/' . $file)) {
392
                self::copyFiles($from . '/' . $file, $to . '/' . $file);
393
            } else {
394
                copy($from . '/' . $file, $to . '/' . $file);
395
            }
396
        }
397
    }
398
399
    /**
400
     * Translit function
401
     *
402
     * @param string $str
403
     * @return string
404
     */
405
    public static function translit($str) {
406
        $rus = array('А', 'Б', 'В', 'Г', 'Д', 'Е', 'Ё', 'Ж', 'З', 'И', 'Й', 'К', 'Л', 'М', 'Н', 'О', 'П', 'Р', 'С', 'Т', 'У', 'Ф', 'Х', 'Ц', 'Ч', 'Ш', 'Щ', 'Ъ', 'Ы', 'Ь', 'Э', 'Ю', 'Я', 'а', 'б', 'в', 'г', 'д', 'е', 'ё', 'ж', 'з', 'и', 'й', 'к', 'л', 'м', 'н', 'о', 'п', 'р', 'с', 'т', 'у', 'ф', 'х', 'ц', 'ч', 'ш', 'щ', 'ъ', 'ы', 'ь', 'э', 'ю', 'я');
407
        $lat = array('A', 'B', 'V', 'G', 'D', 'E', 'E', 'Gh', 'Z', 'I', 'Y', 'K', 'L', 'M', 'N', 'O', 'P', 'R', 'S', 'T', 'U', 'F', 'H', 'C', 'Ch', 'Sh', 'Sch', 'Y', 'Y', 'Y', 'E', 'Yu', 'Ya', 'a', 'b', 'v', 'g', 'd', 'e', 'e', 'gh', 'z', 'i', 'y', 'k', 'l', 'm', 'n', 'o', 'p', 'r', 's', 't', 'u', 'f', 'h', 'c', 'ch', 'sh', 'sch', 'y', 'y', 'y', 'e', 'yu', 'ya');
408
        return str_replace($rus, $lat, $str);
409
    }
410
411
    /**
412
     * get youtube video ID from URL
413
     *
414
     * @author http://stackoverflow.com/a/6556662
415
     * @param string $url
416
     * @return string Youtube video id or FALSE if none found.
417
     */
418
    public static function youtubeIdFromUrl($url) {
419
        $pattern = '%^# Match any youtube URL
420
        (?:https?://)?  # Optional scheme. Either http or https
421
        (?:www\.)?      # Optional www subdomain
422
        (?:             # Group host alternatives
423
          youtu\.be/    # Either youtu.be,
424
        | youtube\.com  # or youtube.com
425
          (?:           # Group path alternatives
426
            /embed/     # Either /embed/
427
          | /v/         # or /v/
428
          | /watch\?v=  # or /watch\?v=
429
          )             # End path alternatives.
430
        )               # End host alternatives.
431
        ([\w-]{10,12})  # Allow 10-12 for 11 char youtube id.
432
        $%x';
433
        $result = preg_match($pattern, $url, $matches);
434
        if (false !== $result) {
435
            return $matches[1];
436
        }
437
        return false;
438
    }
439
440
    /**
441
     * check array is associative
442
     *
443
     * @author http://stackoverflow.com/a/173479
444
     * @param array $arr
445
     * @return boolean
446
     */
447
    public static function isAssoc(&$arr) {
448
        return array_keys($arr) !== range(0, count($arr) - 1);
449
    }
450
451
    public static function defValue(&$link, $defValue = '') {
452
        return isset($link) ? $link : $defValue;
453
    }
454
455
    public static function rusPrice($price, $zeroEnding = false) {
0 ignored issues
show
Unused Code introduced by
The parameter $zeroEnding is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
456
        $afterDot = $price == (int) $price ? 0 : 2;
457
        return number_format($price, $afterDot, '.', ' ');
458
    }
459
}