Test Failed
Push — master ( 965da0...97ed9f )
by Vítězslav
04:38
created

Functions::recursiveIconv()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 5
c 1
b 0
f 0
nc 2
nop 3
dl 0
loc 10
rs 10
1
<?php
2
/**
3
 * Misc functions holder 
4
 * 
5
 * @category Common
6
 * 
7
 * @author    Vitex <[email protected]>
8
 * @copyright 2019 [email protected] (G)
9
 * @license https://opensource.org/licenses/MIT GPL-2
10
 * 
11
 * PHP 7
12
 */
13
14
namespace Ease;
15
16
/**
17
 * Description of Functions
18
 *
19
 * @author Vítězslav Dvořák <[email protected]>
20
 */
21
class Functions
22
{
23
    /**
24
     * Returns PATH modified for current operating system.
25
     *
26
     * @param string $path
27
     *
28
     * @return string
29
     */
30
    public static function sysFilename($path)
31
    {
32
        return str_replace(['\\', '/'], constant('DIRECTORY_SEPARATOR'), $path);
33
    }
34
35
36
    
37
    
38
    /**
39
     * Add params to url
40
     *
41
     * @param string  $url      originall url
42
     * @param array   $addParams   value to add
43
     * @param boolean $override replace already existing values ?
44
     * 
45
     * @return string url with parameters added
46
     */
47
    public static function addUrlParams($url, $addParams, $override = false)
48
    {
49
        $urlParts = parse_url($url);
50
        $urlFinal = '';
51
        if (array_key_exists('scheme', $urlParts)) {
52
            $urlFinal .= $urlParts['scheme'].'://'.$urlParts['host'];
53
        }
54
        if (array_key_exists('port', $urlParts)) {
55
            $urlFinal .= ':'.$urlParts['port'];
56
        }
57
        if (array_key_exists('path', $urlParts)) {
58
            $urlFinal .= $urlParts['path'];
59
        }
60
        if (array_key_exists('query', $urlParts)) {
61
            parse_str($urlParts['query'], $queryUrlParams);
62
            $urlParams = $override ? array_merge($queryUrlParams, $addParams) : array_merge($addParams,
63
                    $queryUrlParams);
64
        } else {
65
            $urlParams = $addParams;
66
        }
67
68
        if (!empty($urlParams)) {
69
            $urlFinal .= '?';
70
            if (is_array($urlParams)) {
0 ignored issues
show
introduced by
The condition is_array($urlParams) is always true.
Loading history...
71
                $urlFinal .= http_build_query($urlParams);
72
            } else {
73
                $urlFinal .= $urlParams;
74
            }
75
        }
76
        return $urlFinal;
77
    }
78
79
    /**
80
     * Turn all URLs in clickable links.
81
     * 
82
     * @author Arnold Daniels <[email protected]>
83
     * 
84
     * @param string $value
85
     * @param array  $protocols  http/https, ftp, mail, twitter
86
     * @param array  $attributes
87
     * @param string $mode       normal or all
88
     * 
89
     * @return string
90
     */
91
    public static function linkify($value, $protocols = array('http', 'mail'),
92
                                   array $attributes = array())
93
    {
94
        // Link attributes
95
        $attr = '';
96
        foreach ($attributes as $key => $val) {
97
            $attr = ' '.$key.'="'.htmlentities($val).'"';
98
        }
99
100
        $links = array();
101
102
        // Extract existing links and tags
103
        $value = preg_replace_callback('~(<a .*?>.*?</a>|<.*?>)~i',
104
            function ($match) use (&$links) {
105
            return '<'.array_push($links, $match[1]).'>';
106
        }, $value);
107
108
        // Extract text links for each protocol
109
        foreach ((array) $protocols as $protocol) {
110
            switch ($protocol) {
111
                case 'http':
112
                case 'https': $value = preg_replace_callback('~(?:(https?)://([^\s<]+)|(www\.[^\s<]+?\.[^\s<]+))(?<![\.,:])~i',
113
                        function ($match) use ($protocol, &$links, $attr) {
114
                        if ($match[1]) $protocol = $match[1];
115
                        $link     = $match[2] ?: $match[3];
116
                        return '<'.array_push($links,
117
                                "<a $attr href=\"$protocol://$link\">$link</a>").'>';
118
                    }, $value);
119
                    break;
120
                case 'mail': $value = preg_replace_callback('~([^\s<]+?@[^\s<]+?\.[^\s<]+)(?<![\.,:])~',
121
                        function ($match) use (&$links, $attr) {
122
                        return '<'.array_push($links,
123
                                "<a $attr href=\"mailto:{$match[1]}\">{$match[1]}</a>").'>';
124
                    }, $value);
125
                    break;
126
                case 'twitter': $value = preg_replace_callback('~(?<!\w)[@#](\w++)~',
127
                        function ($match) use (&$links, $attr) {
128
                        return '<'.array_push($links,
129
                                "<a $attr href=\"https://twitter.com/".($match[0][0]
130
                                == '@' ? '' : 'search/%23').$match[1]."\">{$match[0]}</a>").'>';
131
                    }, $value);
132
                    break;
133
                default: $value = preg_replace_callback('~'.preg_quote($protocol,
134
                            '~').'://([^\s<]+?)(?<![\.,:])~i',
135
                        function ($match) use ($protocol, &$links, $attr) {
136
                        return '<'.array_push($links,
137
                                "<a $attr href=\"$protocol://{$match[1]}\">{$match[1]}</a>").'>';
138
                    }, $value);
139
                    break;
140
            }
141
        }
142
143
        // Insert all link
144
        return preg_replace_callback('/<(\d+)>/',
145
            function ($match) use (&$links) {
146
            return $links[$match[1] - 1];
147
        }, $value);
148
    }
149
    
150
    /**
151
     * Z datového pole $SourceArray přemístí políčko $ColumName do pole
152
     * $destinationArray.
153
     *
154
     * @param array  $sourceArray      zdrojové pole dat
155
     * @param array  $destinationArray cílové pole dat
156
     * @param string $columName        název položky k převzetí
157
     */
158
    public static function divDataArray(&$sourceArray, &$destinationArray,
159
                                        $columName)
160
    {
161
        $result = false;
162
        if (array_key_exists($columName, $sourceArray)) {
163
            $destinationArray[$columName] = $sourceArray[$columName];
164
            unset($sourceArray[$columName]);
165
166
            $result = true;
167
        }
168
169
        return $result;
170
    }
171
172
    /**
173
     * Test for associative array.
174
     *
175
     * @param array $arr
176
     *
177
     * @return bool
178
     */
179
    public static function isAssoc(array $arr)
180
    {
181
        return array_keys($arr) !== range(0, count($arr) - 1);
182
    }
183
184
    /**
185
     * Odstraní z textu diakritiku.
186
     *
187
     * @param string $text
188
     */
189
    public static function rip($text)
190
    {
191
        $convertTable = [
192
            'ä' => 'a',
193
            'Ä' => 'A',
194
            'á' => 'a',
195
            'Á' => 'A',
196
            'à' => 'a',
197
            'À' => 'A',
198
            'ã' => 'a',
199
            'Ã' => 'A',
200
            'â' => 'a',
201
            'Â' => 'A',
202
            'č' => 'c',
203
            'Č' => 'C',
204
            'ć' => 'c',
205
            'Ć' => 'C',
206
            'ď' => 'd',
207
            'Ď' => 'D',
208
            'ě' => 'e',
209
            'Ě' => 'E',
210
            'é' => 'e',
211
            'É' => 'E',
212
            'ë' => 'e',
213
            'Ë' => 'E',
214
            'è' => 'e',
215
            'È' => 'E',
216
            'ê' => 'e',
217
            'Ê' => 'E',
218
            'í' => 'i',
219
            'Í' => 'I',
220
            'ï' => 'i',
221
            'Ï' => 'I',
222
            'ì' => 'i',
223
            'Ì' => 'I',
224
            'î' => 'i',
225
            'Î' => 'I',
226
            'ľ' => 'l',
227
            'Ľ' => 'L',
228
            'ĺ' => 'l',
229
            'Ĺ' => 'L',
230
            'ń' => 'n',
231
            'Ń' => 'N',
232
            'ň' => 'n',
233
            'Ň' => 'N',
234
            'ñ' => 'n',
235
            'Ñ' => 'N',
236
            'ó' => 'o',
237
            'Ó' => 'O',
238
            'ö' => 'o',
239
            'Ö' => 'O',
240
            'ô' => 'o',
241
            'Ô' => 'O',
242
            'ò' => 'o',
243
            'Ò' => 'O',
244
            'õ' => 'o',
245
            'Õ' => 'O',
246
            'ő' => 'o',
247
            'Ő' => 'O',
248
            'ř' => 'r',
249
            'Ř' => 'R',
250
            'ŕ' => 'r',
251
            'Ŕ' => 'R',
252
            'š' => 's',
253
            'Š' => 'S',
254
            'ś' => 's',
255
            'Ś' => 'S',
256
            'ť' => 't',
257
            'Ť' => 'T',
258
            'ú' => 'u',
259
            'Ú' => 'U',
260
            'ů' => 'u',
261
            'Ů' => 'U',
262
            'ü' => 'u',
263
            'Ü' => 'U',
264
            'ù' => 'u',
265
            'Ù' => 'U',
266
            'ũ' => 'u',
267
            'Ũ' => 'U',
268
            'û' => 'u',
269
            'Û' => 'U',
270
            'ý' => 'y',
271
            'Ý' => 'Y',
272
            'ž' => 'z',
273
            'Ž' => 'Z',
274
            'ź' => 'z',
275
            'Ź' => 'Z',
276
        ];
277
278
        return @iconv('UTF-8', 'ASCII//TRANSLIT', strtr($text, $convertTable));
279
    }
280
281
    /**
282
     * Encrypt.
283
     * Šifrování.
284
     *
285
     * @param string $textToEncrypt plaintext
286
     * @param string $encryptKey    klíč
287
     *
288
     * @return string encrypted text
289
     */
290
    public static function easeEncrypt($textToEncrypt, $encryptKey)
291
    {
292
        $encryption_key = base64_decode($encryptKey);
293
        $iv             = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
294
        $encrypted      = openssl_encrypt($textToEncrypt, 'aes-256-cbc',
295
            $encryption_key, 0, $iv);
296
        return base64_encode($encrypted.'::'.$iv);
297
    }
298
299
    /**
300
     * Decrypt
301
     * Dešifrování.
302
     *
303
     * @param string $textToDecrypt šifrovaný text
304
     * @param string $encryptKey    šifrovací klíč
305
     *
306
     * @return string
307
     */
308
    public static function easeDecrypt($textToDecrypt, $encryptKey)
309
    {
310
        $encryption_key = base64_decode($encryptKey);
311
        list($encrypted_data, $iv) = explode('::',
312
            base64_decode($textToDecrypt), 2);
313
        return openssl_decrypt($encrypted_data, 'aes-256-cbc', $encryption_key,
314
            0, $iv);
315
    }
316
317
    /**
318
     * Generování náhodného čísla.
319
     *
320
     * @param int $minimal
321
     * @param int $maximal
322
     *
323
     * @return float
324
     */
325
    public static function randomNumber($minimal = null, $maximal = null)
326
    {
327
        mt_srand((float) microtime() * 1000000);
0 ignored issues
show
Bug introduced by
(double)microtime() * 1000000 of type double is incompatible with the type integer expected by parameter $seed of mt_srand(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

327
        mt_srand(/** @scrutinizer ignore-type */ (float) microtime() * 1000000);
Loading history...
328
        if (isset($minimal) && isset($maximal)) {
329
            if ($minimal >= $maximal) {
330
                $rand = false;
331
            } else {
332
                $rand = mt_rand($minimal, $maximal);
333
            }
334
        } else {
335
            $rand = mt_rand();
336
        }
337
338
        return $rand;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $rand could also return false which is incompatible with the documented return type double. Did you maybe forget to handle an error condition?

If the returned type also contains false, it is an indicator that maybe an error condition leading to the specific return statement remains unhandled.

Loading history...
339
    }
340
341
    /**
342
     * Vrací náhodný řetězec dané délky.
343
     *
344
     * @param int $length
345
     *
346
     * @return string
347
     */
348
    public static function randomString($length = 6)
349
    {
350
        return substr(str_shuffle('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'),
351
            0, $length);
352
    }
353
354
    /**
355
     * Rekurzivně překóduje pole.
356
     *
357
     * @param string $in_charset
358
     * @param string $out_charset
359
     * @param array  $arr         originální pole
360
     *
361
     * @return array překódované pole
362
     */
363
    public static function recursiveIconv($in_charset, $out_charset, $arr)
364
    {
365
        if (!is_array($arr)) {
0 ignored issues
show
introduced by
The condition is_array($arr) is always true.
Loading history...
366
            return \iconv($in_charset, $out_charset, $arr);
367
        }
368
        $ret = $arr;
369
        
370
        array_walk_recursive($ret, '\Ease\Functions::arrayIconv', [$in_charset, $out_charset, $arr]  );
371
372
        return $ret;
373
    }
374
375
    /**
376
     * Pomocná funkce pro překódování vícerozměrného pole.
377
     *
378
     * @see recursiveIconv
379
     *
380
     * @param mixed  $val
381
     * @param string $key
382
     * @param mixed  $encodings
383
     */
384
    public static function arrayIconv(&$val, $key, $encodings)
0 ignored issues
show
Unused Code introduced by
The parameter $key is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

384
    public static function arrayIconv(&$val, /** @scrutinizer ignore-unused */ $key, $encodings)

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

Loading history...
385
    {
386
        $val = iconv($encodings[0], $encodings[1], $val);
387
    }
388
389
    /**
390
     * Zobrazí velikost souboru v srozumitelném tvaru.
391
     *
392
     * @param int $filesize bytů
393
     *
394
     * @return string
395
     */
396
    public static function humanFilesize($filesize)
397
    {
398
        if (is_numeric($filesize)) {
0 ignored issues
show
introduced by
The condition is_numeric($filesize) is always true.
Loading history...
399
            $decr   = 1024;
400
            $step   = 0;
401
            $prefix = ['Byte', 'KB', 'MB', 'GB', 'TB', 'PB'];
402
403
            while (($filesize / $decr) > 0.9) {
404
                $filesize = $filesize / $decr;
405
                ++$step;
406
            }
407
408
            return round($filesize, 2).' '.$prefix[$step];
409
        } else {
410
            return 'NaN';
411
        }
412
    }
413
414
    /**
415
     * Reindex Array by given key.
416
     *
417
     * @param array  $data    array to reindex
418
     * @param string $indexBy one of columns in array
419
     *
420
     * @return array
421
     */
422
    public static function reindexArrayBy($data, $indexBy = null)
423
    {
424
        $reindexedData = [];
425
426
        foreach ($data as $dataID => $data) {
0 ignored issues
show
introduced by
$data is overwriting one of the parameters of this function.
Loading history...
427
            if (array_key_exists($indexBy, $data)) {
428
                $reindexedData[$data[$indexBy]] = $data;
429
            } else {
430
                throw new \Exception(sprintf('Data row does not contain column %s for reindexing',
431
                        $indexBy));
432
            }
433
        }
434
435
        return $reindexedData;
436
    }
437
438
    /**
439
     * Filter Only letters from string.
440
     * Pouze malé a velké písmena.
441
     *
442
     * @return string text bez zvláštních znaků
443
     */
444
    public static function lettersOnly($text)
445
    {
446
        return preg_replace('/[^(a-zA-Z0-9)]*/', '', $text);
447
    }
448
449
    /**
450
     * Confirm that string is serialized
451
     * 
452
     * @param string $data
453
     *
454
     * @return boolean
455
     */
456
    public static function isSerialized($data)
457
    {
458
        // if it isn't a string, it isn't serialized
459
        if (!is_string($data)) return false;
0 ignored issues
show
introduced by
The condition is_string($data) is always true.
Loading history...
460
        $data = trim($data);
461
        if ('N;' == $data) return true;
462
        if (!preg_match('/^([adObis]):/', $data, $badions)) return false;
463
        switch ($badions[1]) {
464
            case 'a' :
465
            case 'O' :
466
            case 's' :
467
                if (preg_match("/^{$badions[1]}:[0-9]+:.*[;}]\$/s", $data))
468
                        return true;
469
                break;
470
            case 'b' :
471
            case 'i' :
472
            case 'd' :
473
                if (preg_match("/^{$badions[1]}:[0-9.E-]+;\$/", $data))
474
                        return true;
475
                break;
476
        }
477
        return false;
478
    }
479
480
    /**
481
     * Get Classname without namespace prefix
482
     * 
483
     * @param object $object
484
     * 
485
     * @return string
486
     */
487
    static public function baseClassName($object)
488
    {
489
        return is_object($object) ? basename(str_replace('\\', '/',
490
                    get_class($object))) : null;
491
    }    
492
    
493
}
494