Completed
Push — master ( b567c3...a654e3 )
by Lorenzo
02:32
created

string.php ➔ numberToWord()   F

Complexity

Conditions 23
Paths 2240

Size

Total Lines 70
Code Lines 56

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 23
eloc 56
c 0
b 0
f 0
nc 2240
nop 2
dl 0
loc 70
rs 2.6272

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * Generate random string (password) from a different charset based on $secLevel.
5
 * $secLevel=0 [a-z] charset.
6
 * $secLevel=1 [a-z0-9] charset.
7
 * $secLevel=2 [A-Za-z0-9] charset.
8
 * $secLevel=3 [A-Za-z0-9-_$!+&%?=*#@] charset.
9
 * @param int $length
10
 * @param int $secLevel
11
 * @return string
12
 */
13
function generateRandomPassword(int $length = 10, int $secLevel = 2) : string
14
{
15
    $charset = 'abcdefghijklmnopqrstuvwxyz';
16
    if ($secLevel == 1) {
17
        $charset = 'abcdefghijklmnopqrstuvwxyz1234567890';
18
    } elseif ($secLevel == 2) {
19
        $charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
20
    } elseif ($secLevel >= 3) {
21
        $charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890-_$!+&%?=*#@';
22
    }
23
24
    return generateRandomString($length, '', $charset);
25
}
26
27
/**
28
 * Generate random string from [0-9A-Za-z] charset.
29
 * You may extend charset by passing $extChars (i.e. add these chars to existing).
30
 * Ex.: $extChars='-_$!' implies that the final charset is [0-9A-Za-z-_$!]
31
 * If $newChars is set, the default charset are replaced by this and $extChars was ignored.
32
 * Ex.: $newChars='0123456789' implies that the final charset is [0123456789]
33
 * @param int $length
34
 * @param string $extChars
35
 * @param string $newChars
36
 * @return string
37
 */
38
function generateRandomString(int $length = 10, string $extChars = '', string $newChars = '') : string
39
{
40
    if ($length < 1) {
41
        $length = 1;
42
    }
43
44
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
45
    if ($newChars !== null && $newChars != '') {
46
        $characters = $newChars;
47
    } elseif ($extChars !== null && $extChars != '') {
48
        $characters .= $extChars;
49
    }
50
51
    $charactersLength = strlen($characters);
52
    $randomString = '';
53
54
    for ($i = 0; $i < $length; $i++) {
55
        $randomString .= $characters[random_int(0, $charactersLength - 1)];
56
    }
57
58
    return $randomString;
59
}
60
61
/**
62
 * *****************************************************
63
 * LARAVEL STRING HELPERS
64
 * With some adjustments
65
 * *****************************************************
66
 */
67
68
if (!function_exists('preg_replace_sub')) {
69
    /**
70
     * Replace a given pattern with each value in the array in sequentially.
71
     *
72
     * @param  string $pattern
73
     * @param  array $replacements
74
     * @param  string $subject
75
     * @return string
76
     */
77
    function preg_replace_sub($pattern, &$replacements, $subject)
78
    {
79
        return preg_replace_callback($pattern, function () use (&$replacements) {
80
            return array_shift($replacements);
81
        }, $subject);
82
    }
83
}
84
85
if (!function_exists('snake_case')) {
86
    /**
87
     * Convert a string to snake case.
88
     *
89
     * @param  string $value
90
     * @param  string $delimiter
91
     * @return string
92
     */
93
    function snake_case($value, $delimiter = '_')
94
    {
95
        $snakeCache = [];
96
        $key = $value . $delimiter;
97
        if (isset($snakeCache[$key])) {
98
            return $snakeCache[$key];
99
        }
100
        if (!ctype_lower($value)) {
101
            $value = strtolower(preg_replace('/(.)(?=[A-Z])/', '$1' . $delimiter, $value));
102
        }
103
        return $snakeCache[$key] = $value;
104
    }
105
}
106
107
if (!function_exists('str_random')) {
108
    /**
109
     * Generate a more truly "random" alpha-numeric string with openssl.
110
     * If openssl_random_pseudo_bytes not exists, use simple legacy function
111
     *
112
     * @param  int $length
113
     * @return string
114
     *
115
     * @throws \RuntimeException
116
     */
117
    function str_random(int $length = 16)
118
    {
119
        if ($length < 0) {
120
            $length = 16;
121
        }
122
123
        if (!function_exists('openssl_random_pseudo_bytes')) {
124
            return generateRandomString($length);
125
        }
126
        $bytes = openssl_random_pseudo_bytes($length * 2);
127
        if ($bytes === false) {
128
            throw new RuntimeException('Unable to generate random string.');
129
        }
130
        return substr(str_replace(array('/', '+', '='), '', base64_encode($bytes)), 0, $length);
131
    }
132
}
133
134
if (!function_exists('ends_with')) {
135
    /**
136
     * Determine if a given string ends with a given substring.
137
     *
138
     * @param  string $haystack
139
     * @param  string|array $needles
140
     * @return bool
141
     */
142
    function ends_with($haystack, $needles)
143
    {
144
        if (isNullOrEmpty($haystack) || isNullOrEmpty($needles)) {
145
            return false;
146
        }
147
148
        foreach ((array)$needles as $needle) {
149
            if ((string)$needle === substr($haystack, -strlen($needle))) {
150
                return true;
151
            }
152
        }
153
        return false;
154
    }
155
}
156
157
if (!function_exists('starts_with')) {
158
    /**
159
     * Determine if a given string starts with a given substring.
160
     *
161
     * @param  string $haystack
162
     * @param  string|array $needles
163
     * @return bool
164
     */
165
    function starts_with($haystack, $needles)
166
    {
167
        if (isNullOrEmpty($haystack) || isNullOrEmpty($needles)) {
168
            return false;
169
        }
170
171
        foreach ((array)$needles as $needle) {
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...
172
            if ($needle != '' && strpos($haystack, $needle) === 0) {
173
                return true;
174
            }
175
        }
176
        return false;
177
    }
178
}
179
180
if (!function_exists('str_contains')) {
181
    /**
182
     * Determine if a given string contains a given substring.
183
     *
184
     * @param  string $haystack
185
     * @param  string|array $needles
186
     * @return bool
187
     */
188
    function str_contains($haystack, $needles)
189
    {
190
        foreach ((array)$needles as $needle) {
191
            if ($needle != '' && strpos($haystack, $needle) !== false) {
192
                return true;
193
            }
194
        }
195
        return false;
196
    }
197
}
198
199
if (!function_exists('str_finish')) {
200
    /**
201
     * Cap a string with a single instance of a given value.
202
     *
203
     * @param  string $value
204
     * @param  string $cap
205
     * @return string
206
     */
207
    function str_finish($value, $cap)
208
    {
209
        $quoted = preg_quote($cap, '/');
210
        return preg_replace('/(?:' . $quoted . ')+$/', '', $value) . $cap;
211
    }
212
}
213
214
if (!function_exists('str_is')) {
215
    /**
216
     * Determine if a given string matches a given pattern.
217
     *
218
     * @param  string $pattern
219
     * @param  string $value
220
     * @return bool
221
     */
222
    function str_is($pattern, $value)
223
    {
224
        if ($pattern == $value) {
225
            return true;
226
        }
227
        $pattern = preg_quote($pattern, '#');
228
        // Asterisks are translated into zero-or-more regular expression wildcards
229
        // to make it convenient to check if the strings starts with the given
230
        // pattern such as "library/*", making any string check convenient.
231
        $pattern = str_replace('\*', '.*', $pattern) . '\z';
232
        return preg_match('#^' . $pattern . '#', $value) === 1;
233
    }
234
}
235
if (!function_exists('str_limit')) {
236
    /**
237
     * Limit the number of characters in a string.
238
     *
239
     * @param  string $value
240
     * @param  int $limit
241
     * @param  string $end append in
242
     * @return string
243
     */
244
    function str_limit(string $value, int $limit = 100, string $end = '...', bool $wordsafe = false) : string
245
    {
246
        $limit = max($limit, 0);
247
        if (mb_strlen($value) <= $limit) {
248
            return $value;
249
        }
250
251
        $string = rtrim(mb_substr($value, 0, $limit, 'UTF-8'));
252
        if ($wordsafe) {
253
            $string = preg_replace('/\s+?(\S+)?$/', '', $string);
254
        }
255
        return $string . $end;
256
    }
257
}
258
259
if (!function_exists('str_replace_array')) {
260
    /**
261
     * Replace a given value in the string sequentially with an array.
262
     *
263
     * @param  string $search
264
     * @param  array $replace
265
     * @param  string $subject
266
     * @return string
267
     */
268
    function str_replace_array($search, array $replace, $subject)
269
    {
270
        foreach ($replace as $value) {
271
            $subject = preg_replace('/' . $search . '/', $value, $subject, 1);
272
        }
273
        return $subject;
274
    }
275
}
276
277
if (!function_exists('studly_case')) {
278
    /**
279
     * Convert a value to studly caps case.
280
     *
281
     * @param  string $value
282
     * @return string
283
     */
284
    function studly_case($value)
285
    {
286
        $studlyCache = [];
287
        $key = $value;
288
        if (isset($studlyCache[$key])) {
289
            return $studlyCache[$key];
290
        }
291
        $value = ucwords(str_replace(array('-', '_'), ' ', $value));
292
        return $studlyCache[$key] = str_replace(' ', '', $value);
293
    }
294
}
295
296
if (!function_exists('studly')) {
297
    /**
298
     * Convert a value to studly caps case.
299
     * Alias of studly_case
300
     *
301
     * @param  string $value
302
     * @return string
303
     */
304
    function studly($value)
305
    {
306
        return studly_case($value);
307
    }
308
}
309
310
if (!function_exists('camel_case')) {
311
    /**
312
     * Convert a value to camel case.
313
     *
314
     * @param  string $value
315
     * @return string
316
     */
317
    function camel_case($value)
318
    {
319
        $camelCache = [];
320
        if (isset($camelCache[$value])) {
321
            return $camelCache[$value];
322
        }
323
        return $camelCache[$value] = lcfirst(studly($value));
324
    }
325
}
326
327
/**
328
 * Replace underscores with dashes in the string.
329
 * @param string $word
330
 * @return string
331
 */
332
function underscore2dash(string $word) : string
333
{
334
    return str_replace('_', '-', $word);
335
}
336
337
/**
338
 * Make an underscored, lowercase form from the expression in the string.
339
 * @param string $word
340
 * @return string
341
 */
342
function dash2underscore(string $word) : string
343
{
344
    $word = preg_replace('/([A-Z]+)([A-Z][a-z])/', '\1_\2', $word);
345
    $word = preg_replace('/([a-z])([A-Z])/', '\1_\2', $word);
346
    return str_replace('-', '_', strtolower($word));
347
}
348
349
if (!function_exists('str_replace_multiple_space')) {
350
351
    /**
352
     * Replace multiple spaces with one space.
353
     * @param string $str
354
     * @return string
355
     */
356
    function str_replace_multiple_space(string $str) : string
357
    {
358
        return preg_replace('/\s+/', ' ', $str);
359
    }
360
}
361
362
if (!function_exists('str_replace_last')) {
363
    /**
364
     * Replace last occurrence ($search) of a string ($subject) with $replace string.
365
     * @param string $search
366
     * @param string $replace
367
     * @param string $subject
368
     * @return string
369
     */
370
    function str_replace_last(string $search, string $replace, string $subject) : string
371
    {
372
        if ($search == '') {
373
            return $subject;
374
        }
375
        $position = strrpos($subject, $search);
376
        if ($position === false) {
377
            return $subject;
378
        }
379
        return substr_replace($subject, $replace, $position, strlen($search));
380
    }
381
}
382
if (!function_exists('segment')) {
383
384
    /**
385
     * Get a segment from a string based on a delimiter.
386
     * Returns an empty string when the offset doesn't exist.
387
     * Use a negative index to start counting from the last element.
388
     *
389
     * @param string $delimiter
390
     * @param int $index
391
     * @param string $subject
392
     *
393
     * @return string
394
     * @see https://github.com/spatie/string/blob/master/src/Str.php
395
     */
396
    function segment($delimiter, $index, $subject)
397
    {
398
        $segments = explode($delimiter, $subject);
399
        if ($index < 0) {
400
            $segments = array_reverse($segments);
401
            $index = (int)abs($index) - 1;
402
        }
403
        $segment = isset($segments[$index]) ? $segments[$index] : '';
404
        return $segment;
405
    }
406
}
407
if (!function_exists('firstSegment')) {
408
409
    /**
410
     * Get the first segment from a string based on a delimiter.
411
     *
412
     * @param string $delimiter
413
     * @param string $subject
414
     *
415
     * @return string
416
     * @see https://github.com/spatie/string/blob/master/src/Str.php
417
     */
418
    function firstSegment($delimiter, $subject) : string
419
    {
420
        return segment($delimiter, 0, $subject);
421
    }
422
}
423
424
if (!function_exists('lastSegment')) {
425
426
    /**
427
     * Get the last segment from a string based on a delimiter.
428
     *
429
     * @param string $delimiter
430
     * @param string $subject
431
     *
432
     * @return string
433
     * @see https://github.com/spatie/string/blob/master/src/Str.php
434
     */
435
    function lastSegment($delimiter, $subject) : string
436
    {
437
        return segment($delimiter, -1, $subject);
438
    }
439
}
440
/**
441
 * Return true if $subject is null or empty string ('').
442
 * @param $subject
443
 * @return bool
444
 */
445
function isNullOrEmpty($subject) : bool
446
{
447
    return $subject === null || $subject == '';
448
}
449
450
/**
451
 * Return true if $subject is not null and is not empty string ('').
452
 * @param $subject
453
 * @return bool
454
 */
455
function isNotNullOrEmpty($subject) : bool
456
{
457
    return !isNullOrEmpty($subject);
458
}
459
460
461
/**
462
 * Convert number to word representation.
463
 *
464
 * @param int $number number to convert to word
465
 * @param string $locale default 'IT' support only IT or EN
466
 *
467
 * @return string converted string
468
 * @see https://github.com/ngfw/Recipe/blob/master/src/ngfw/Recipe.php
469
 */
470
function numberToWord(int $number, string $locale = 'IT') : string
471
{
472
    if (isNullOrEmpty($locale) || (strtoupper($locale) != 'IT' && strtoupper($locale) != 'EN')) {
473
        $locale = 'IT';
474
    } else {
475
        $locale = strtoupper($locale);
476
    }
477
478
    $hyphen = $locale == 'EN' ? '-' : '';
479
    $conjunction = $locale == 'EN' ? ' and ' : ' ';
480
    $separator = ', ';
481
    $negative = $locale == 'EN' ? 'negative ' : 'negativo ';
482
    $decimal = $locale == 'EN' ? ' point ' : ' punto ';
483
    $fraction = null;
484
    $dictionary = $locale == 'EN' ? NUMBERS_EN_ARR : NUMBERS_ITA_ARR;
485
    if (!is_numeric($number)) {
486
        return '';
487
    }
488
    if (!isInteger($number, false, true)) {
489
        trigger_error('numberToWord only accepts numbers between -' . PHP_INT_MAX . ' and ' . PHP_INT_MAX,
490
            E_USER_WARNING);
491
        return '';
492
    }
493
    if ($number < 0) {
494
        return $negative . numberToWord(abs($number), $locale);
495
    }
496
    if (strpos($number, '.') !== false) {
497
        list($number, $fraction) = explode('.', $number);
498
    }
499
    switch (true) {
500
        case $number < 21:
501
            $string = $dictionary[$number];
502
            break;
503
        case $number < 100:
504
            $tens = ((int)($number / 10)) * 10;
505
            $units = $number % 10;
506
            $string = $dictionary[$tens];
507
            if ($units) {
508
                $string .= $hyphen . $dictionary[$units];
509
            }
510
            break;
511
        case $number < 1000:
512
            $hundreds = $number / 100;
513
            $remainder = $number % 100;
514
            $string = $dictionary[$hundreds] . ' ' . $dictionary[100];
515
            if ($remainder) {
516
                $string .= $conjunction . numberToWord($remainder, $locale);
517
            }
518
            break;
519
        default:
520
            $baseUnit = pow(1000, floor(log($number, 1000)));
521
            $numBaseUnits = (int)($number / $baseUnit);
522
            $remainder = $number % $baseUnit;
523
            $string = numberToWord($numBaseUnits, $locale) . ' ' . $dictionary[$baseUnit];
524
            if ($remainder) {
525
                $string .= $remainder < 100 ? $conjunction : $separator;
526
                $string .= numberToWord($remainder, $locale);
527
            }
528
            break;
529
    }
530
    if (null !== $fraction && is_numeric($fraction)) {
531
        $string .= $decimal;
532
        $words = [];
533
        foreach (str_split((string)$fraction) as $number) {
534
            $words[] = $dictionary[$number];
535
        }
536
        $string .= implode(' ', $words);
537
    }
538
    return $string;
539
}
540
541
/**
542
 * Convert seconds to real time.
543
 *
544
 * @param int $seconds time in seconds
545
 * @param bool $returnAsWords return time in words (example one minute and 20 seconds) if value is True or (1 minute and 20 seconds) if value is false, default false
546
 * @param string $locale 'IT' default, or 'EN'
547
 *
548
 * @return string
549
 * @see https://github.com/ngfw/Recipe/blob/master/src/ngfw/Recipe.php
550
 */
551
function secondsToText(int $seconds, bool $returnAsWords = false, string $locale = 'IT') : string
552
{
553
    $parts = [];
554
    $arrPeriod = ($locale == 'EN' ? PERIOD_IN_SECONDS_EN_ARR : PERIOD_IN_SECONDS_ITA_ARR);
555
    foreach ($arrPeriod as $name => $dur) {
556
        $div = floor($seconds / $dur);
557
        if ($div == 0) {
558
            continue;
559
        }
560
        if ($div == 1) {
561
            $parts[] = ($returnAsWords ? numberToWord($div, $locale) : $div) . ' ' . $name;
562
        } else {
563
            $parts[] = ($returnAsWords ? numberToWord($div,
564
                    $locale) : $div) . ' ' . ($locale == 'EN' ? $name : PERIOD_SINGULAR_PLURAL_ITA_ARR[$name]) . (strtoupper($locale) == 'EN' ? 's' : '');
565
        }
566
        $seconds %= $dur;
567
    }
568
    $last = array_pop($parts);
569
    if (isNullOrEmptyArray($parts)){
570
        return $last;
571
    }
572
    return implode(', ', $parts) . (strtoupper($locale) == 'EN' ? ' and ' : ' e ') . $last;
573
}
574
575
576
/**
577
 * Convert minutes to real time.
578
 *
579
 * @param float $minutes time in minutes
580
 * @param bool $returnAsWords return time in words (example one hour and 20 minutes) if value is True or (1 hour and 20 minutes) if value is false, default false
581
 * @param string $locale 'IT' (default) or 'EN'
582
 *
583
 * @return string
584
 * @see https://github.com/ngfw/Recipe/blob/master/src/ngfw/Recipe.php
585
 */
586
function minutesToText(float $minutes, bool $returnAsWords = false, string $locale = 'IT') : string
587
{
588
    $seconds = $minutes * 60;
589
    return secondsToText($seconds, $returnAsWords, $locale);
590
}
591
592
/**
593
 * Convert hours to real time.
594
 *
595
 * @param float $hours time in hours
596
 * @param bool $returnAsWords return time in words (example one hour) if value is True or (1 hour) if value is false, default false
597
 * @param string $locale 'IT' (default) or 'EN'
598
 *
599
 * @return string
600
 * @see https://github.com/ngfw/Recipe/blob/master/src/ngfw/Recipe.php
601
 */
602
function hoursToText(float $hours, bool $returnAsWords = false, string $locale = 'IT') : string
603
{
604
    $seconds = $hours * 3600;
605
    return secondsToText($seconds, $returnAsWords, $locale);
606
}
607