Completed
Push — master ( b62ab8...a91d24 )
by Renato
05:32
created

helpers.php ➔ maskCep()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 8
nc 2
nop 1
dl 0
loc 11
ccs 8
cts 8
cp 1
crap 2
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * Arquivo de funções
5
 *
6
 * @license MIT
7
 * @package NwLaravel
8
 */
9
10
use \Carbon\Carbon;
11
use \Illuminate\Database\Eloquent\Model;
12
use \Illuminate\Support\Facades\DB;
13
14
if (! function_exists('asCurrency')) {
15
    /**
16
     * Return a timestamp as DateTime object.
17
     *
18
     * @param mixed $value Mixed Value
19
     *
20
     * @return Carbon
21
     */
22
    function asCurrency($value)
23
    {
24
        // Numeric Pt
25 41
        $matchPt = (bool) preg_match('/^[0-9]{1,3}(\.[0-9]{3})*(\,[0-9]+)?$/', $value);
26 41
        $matchNumericPt = (bool) preg_match('/^[0-9]+(\,[0-9]+)$/', $value);
27 41
        if ($matchPt || $matchNumericPt) {
28 15
            $value = str_replace('.', '', $value);
29 15
            $value = str_replace(',', '.', $value);
30 15
        }
31
32 41
        $matchEn = (bool) preg_match('/^[0-9]{1,3}(,[0-9]{3})*(\.[0-9]+)?$/', $value);
33 41
        if ($matchEn) {
34 17
            $value = str_replace(',', '', $value);
35 17
        }
36
37 41
        $matchNumeric = (bool) preg_match('/^[0-9]+(\.[0-9]+)?$/', $value);
38 41
        if ($matchNumeric) {
39 27
            return doubleval($value);
40
        }
41
42 15
        return null;
43
    }
44
}
45
46
if (! function_exists('asDateTime')) {
47
    /**
48
     * Return a timestamp as DateTime object.
49
     *
50
     * @param mixed $value Mixed Value
51
     *
52
     * @return Carbon
53
     */
54
    function asDateTime($value)
55
    {
56 7
        if (empty($value)) {
57 1
            return null;
58
        }
59
60 7
        if ($value instanceof DateTime) {
61 1
            return Carbon::instance($value);
62
        }
63
64 7
        if (is_numeric($value)) {
65 1
            return Carbon::createFromTimestamp($value);
66
        }
67
68 7
        if (is_string($value) && preg_match('/^(\d{4})-(\d{2})-(\d{2})$/', $value)) {
69 1
            return Carbon::createFromFormat('Y-m-d', $value)->startOfDay();
70
        }
71
72 7
        if (is_string($value)) {
73 7
            $format = config('nwlaravel.date_format');
74
75 7
            $date = date_parse_from_format($format, $value);
76 7
            if ($format &&
77 7
                isset($date['error_count']) &&
78 7
                $date['error_count'] == 0 &&
79 6
                checkdate($date['month'], $date['day'], $date['year'])
80 7
            ) {
81 6
                return Carbon::createFromFormat($format, $value)->startOfDay();
82
83
            } else {
84 4
                $format = DB::getQueryGrammar()->getDateFormat();
85 4
                $date = date_parse_from_format($format, $value);
86 4
                if (isset($date['error_count']) && $date['error_count'] == 0) {
87 3
                    return Carbon::createFromFormat($format, $value);
88
                }
89
            }
90
91 3
            if (strtotime($value) !== false) {
92 1
                return (new Carbon($value));
93
            }
94 3
        }
95
96 3
        return null;
97
    }
98
}
99
100
if (! function_exists('fromDateTime')) {
101
    /**
102
     * Convert a DateTime to a storable string.
103
     *
104
     * @param mixed $value Mixed Value
105
     *
106
     * @return string
107
     */
108
    function fromDateTime($value)
109
    {
110 2
        $format = DB::getQueryGrammar()->getDateFormat();
111
112 2
        if (is_numeric($value)) {
113 1
            $value = Carbon::createFromTimestamp($value);
114
115 2
        } elseif (is_string($value) && preg_match('/^(\d{4})-(\d{2})-(\d{2})$/', $value)) {
116 1
            $value = Carbon::createFromFormat('Y-m-d', $value)->startOfDay();
117
118 2
        } elseif (is_string($value)) {
119 2
            $dateFormat = config('nwlaravel.date_format');
120 2
            $date = date_parse_from_format($dateFormat, $value);
121
122 2
            if (isset($date['error_count']) && $date['error_count'] == 0) {
123 2
                if (checkdate($date['month'], $date['day'], $date['year'])) {
124 2
                    $value = Carbon::createFromFormat($dateFormat, $value)->startOfDay();
125 2
                }
126
127 2
            } else {
128 1
                $date = date_parse_from_format($format, $value);
129 1
                if (isset($date['error_count']) && $date['error_count'] == 0) {
130 1
                    $value = Carbon::createFromFormat($format, $value);
131 1
                }
132
            }
133
134 2
            if (strtotime($value) !== false) {
135 2
                $value = new Carbon($value);
0 ignored issues
show
Bug introduced by
It seems like $value defined by new \Carbon\Carbon($value) on line 135 can also be of type object<Carbon\Carbon>; however, Carbon\Carbon::__construct() does only seem to accept string|null, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
136 2
            }
137 2
        }
138
139 2
        if ($value instanceof DateTime) {
140 2
            return $value->format($format);
141
        }
142
143 2
        return null;
144
    }
145
}
146
147
if (! function_exists('toFixed')) {
148
    /**
149
     * To Fixed
150
     *
151
     * @param int   $number  Integer Number
152
     * @param float $decimal Float Decimal
153
     *
154
     * @return float
155
     */
156
    function toFixed($number, $decimal = 0)
157
    {
158 21
        $number = strval($number);
159 21
        $pos = strpos($number.'', ".");
160
161 21
        if ($pos > 0) {
162 13
            $int_str = substr($number, 0, $pos);
163 13
            $dec_str = substr($number, $pos+1);
164 13
            if (strlen($dec_str)>$decimal) {
165 11
                return floatval($int_str.($decimal>0?'.':'').substr($dec_str, 0, $decimal));
166
            } else {
167 3
                return floatval($number);
168
            }
169
        } else {
170 9
            return floatval($number);
171
        }
172
    }
173
}
174
175
if (! function_exists('numberHumans')) {
176
    /**
177
     * Number Humans
178
     *
179
     * @param float $number Number
180
     *
181
     * @return string
182
     */
183
    function numberHumans($number)
184
    {
185 1
        $sufix = '';
186 1
        if ($number >= 1000) {
187 1
            $number = $number / 1000;
188 1
            $sufix = 'K';
189 1
        }
190
191 1
        if ($number >= 1000) {
192 1
            $number = $number / 1000;
193 1
            $sufix = 'M';
194 1
        }
195
196 1
        if ($number >= 1000) {
197 1
            $number = $number / 1000;
198 1
            $sufix = 'B';
199 1
        }
200
201 1
        if ($number >= 1000) {
202 1
            $number = $number / 1000;
203 1
            $sufix = 'T';
204 1
        }
205
206 1
        return toFixed($number, 1).$sufix;
207
    }
208
}
209
210
if (! function_exists('storageFormat')) {
211
    /**
212
     * Storage Format
213
     *
214
     * @param float  $storage Integer Storage
215
     * @param string $nivel   Nivel Storage
216
     *
217
     * @return string
218
     */
219
    function storageFormat($storage, $nivel = null)
220
    {
221 22
        $storage = trim($storage);
222 22
        if (!is_numeric($storage)) {
223 2
            return $storage;
224
        }
225
226 20
        $sizes = ['KB' => 1, 'MB' => 2, 'GB' => 3, 'TB' => 4, 'PB' => 5];
227
228 20
        if (!is_null($nivel) && array_key_exists(strtoupper($nivel), $sizes)) {
229 5
            $multi = 1024*pow(1000, $sizes[strtoupper($nivel)]);
230 5
            $storage = $storage * $multi;
231 5
            if ($storage >= $multi) {
232 5
                $storage = $storage / 1024;
233 5
            }
234 5
        }
235
236 20
        $sufix = 'B';
237 20
        foreach (array_keys($sizes) as $size) {
238 20
            if ($storage >= 1000) {
239 18
                $storage = $storage / 1000;
240 18
                $sufix = $size;
241 18
            }
242 20
        }
243
244 20
        return toFixed($storage, 1).$sufix;
245
    }
246
}
247
248
if (! function_exists('dateFormatter')) {
249
    /**
250
     * Date Formatter
251
     *
252
     * @param DateTime $date     Date Time
253
     * @param string   $dateType String Date Type
254
     * @param string   $timeType String Time Type
255
     *
256
     * @return string
257
     */
258
    function dateFormatter($date, $dateType, $timeType)
259
    {
260 2
        if ($date instanceof \DateTime) {
261 2
            $fmt = new \IntlDateFormatter(
262 2
                config('app.locale'),
263 2
                $dateType,
264 2
                $timeType,
265 2
                config('app.timezone')
266 2
            );
267
268 2
            return $fmt->format($date);
269
        }
270
271 1
        return $date;
272
    }
273
}
274
275
if (! function_exists('formatDateTime')) {
276
    /**
277
     * Format Date Time
278
     *
279
     * @param DateTime $date Date Time
280
     *
281
     * @return string
282
     * @example : DD/MM/YYYY HH:MIN:SS
283
     */
284
    function formatDateTime($date)
285
    {
286 1
        return dateFormatter($date, \IntlDateFormatter::MEDIUM, \IntlDateFormatter::MEDIUM);
287
    }
288
}
289
290
if (! function_exists('formatTimeShort')) {
291
    /**
292
     * Format Time Short
293
     *
294
     * @param DateTime $date Date Time
295
     *
296
     * @return string
297
     * @example : HH:MIN
298
     */
299
    function formatTimeShort($date)
300
    {
301 1
        return dateFormatter($date, \IntlDateFormatter::NONE, \IntlDateFormatter::SHORT);
302
    }
303
}
304
305
if (! function_exists('formatDate')) {
306
    /**
307
     * Format Date
308
     *
309
     * @param DateTime $date Date Time
310
     *
311
     * @return string
312
     * @example : DD/MM/YYYY
313
     */
314
    function formatDate($date)
315
    {
316 1
        return dateFormatter($date, \IntlDateFormatter::MEDIUM, \IntlDateFormatter::NONE);
317
    }
318
}
319
320
if (! function_exists('formatTime')) {
321
    /**
322
     * Format Time
323
     *
324
     * @param DateTime $date Date Time
325
     *
326
     * @return string
327
     * @example : HH:MIN:SS
328
     */
329
    function formatTime($date)
330
    {
331 1
        return dateFormatter($date, \IntlDateFormatter::NONE, \IntlDateFormatter::MEDIUM);
332
    }
333
}
334
335
if (! function_exists('formatDateLong')) {
336
    /**
337
     * Format Date Long
338
     *
339
     * @param DateTime $date Date Time
340
     *
341
     * @return string
342
     * @example : [DIA] de [MES] de [ANO]
343
     */
344
    function formatDateLong($date)
345
    {
346 1
        return dateFormatter($date, \IntlDateFormatter::LONG, \IntlDateFormatter::NONE);
347
    }
348
}
349
350
if (! function_exists('formatDateTimeLong')) {
351
    /**
352
     * Format Date Time Long
353
     *
354
     * @param DateTime $date Date Time
355
     *
356
     * @return string
357
     * @example : [DIA] de [MES] de [ANO] - HH:MIN:SS
358
     */
359
    function formatDateTimeLong($date)
360
    {
361 1
        if ($date instanceof \DateTime) {
362 1
            $date = sprintf(
363 1
                '%s - %s',
364 1
                dateFormatter($date, \IntlDateFormatter::LONG, \IntlDateFormatter::NONE),
365 1
                dateFormatter($date, \IntlDateFormatter::NONE, \IntlDateFormatter::MEDIUM)
366 1
            );
367 1
        }
368
369 1
        return $date;
370
    }
371
}
372
373
if (! function_exists('formatDateFull')) {
374
    /**
375
     * Format Date Full
376
     *
377
     * @param DateTime $date Date Time
378
     *
379
     * @return string
380
     * @example : [SEMANA], [DIA] de [MES] de [ANO]
381
     */
382
    function formatDateFull($date)
383
    {
384 1
        return dateFormatter($date, \IntlDateFormatter::FULL, \IntlDateFormatter::NONE);
385
    }
386
}
387
388
if (! function_exists('formatDateTimeFull')) {
389
    /**
390
     * Format Date Time Full
391
     *
392
     * @param DateTime $date Date Time
393
     *
394
     * @return string
395
     * @example : [SEMANA], [DIA] de [MES] de [ANO] - HH:MIN:SS
396
     */
397
    function formatDateTimeFull($date)
398
    {
399 1
        if ($date instanceof \DateTime) {
400 1
            return sprintf(
401 1
                '%s - %s',
402 1
                dateFormatter($date, \IntlDateFormatter::FULL, \IntlDateFormatter::NONE),
403 1
                dateFormatter($date, \IntlDateFormatter::NONE, \IntlDateFormatter::MEDIUM)
404 1
            );
405
        }
406
407 1
        return $date;
408
    }
409
}
410
411
if (! function_exists('formatDateTimeShort')) {
412
    /**
413
     * Format Date Time Short
414
     *
415
     * @param DateTime $date Date Time
416
     *
417
     * @return string
418
     * @example : DD/MM/YYYY HH:MIN
419
     */
420
    function formatDateTimeShort($date)
421
    {
422 1
        return dateFormatter($date, \IntlDateFormatter::MEDIUM, \IntlDateFormatter::SHORT);
423
    }
424
}
425
426
if (! function_exists('diffForHumans')) {
427
    /**
428
     * Diff date for Humans
429
     *
430
     * @param string|DataTime $date     String\DateTime Date
431
     * @param string|DataTime $other    String\DateTime Other
432
     * @param boolean         $absolute Boolean Absolute
433
     *
434
     * @return string
435
     * @example : 7 minutos atras
436
     */
437
    function diffForHumans($date, $other = null, $absolute = false)
438
    {
439 1
        if ($date instanceof \DateTime) {
440 1
            $date = Carbon::instance($date);
441 1
            if (!$other instanceof Carbon) {
442 1
                $other = null;
443 1
            }
444 1
            return $date->diffForHumans($other, $absolute);
445
        }
446
447 1
        return '';
448
    }
449
}
450
451
if (! function_exists('now')) {
452
    /**
453
     * Now Date Time
454
     *
455
     * @return Carbon
456
     */
457
    function now()
458
    {
459 2
        return Carbon::now();
460
    }
461
}
462
463
if (! function_exists('formatCurrency')) {
464
    /**
465
     * Formato moeda conforme locale
466
     *
467
     * @param float $valor Float Valor
468
     *
469
     * @return string
470
     * @example : formatCurrency(8712.335) = R$8.712,34
471
     */
472
    function formatCurrency($valor)
473
    {
474 1
        $fmt = new \NumberFormatter(config('app.locale'), \NumberFormatter::CURRENCY);
475 1
        return $fmt->format(floatval($valor));
476
    }
477
}
478
479
if (! function_exists('formatNumber')) {
480
    /**
481
     * Formato numero conforme locale
482
     *
483
     * @param int   $valor    Integer Valor
484
     * @param float $decimais Float Decimais
485
     *
486
     * @return string
487
     * @example : formatNumber(8712.335) = 8.712,34
488
     */
489
    function formatNumber($valor, $decimais = 2)
490
    {
491 1
        $valor   = floatval($valor);
492 1
        $decimais = intval($decimais);
493
494 1
        $pattern = sprintf('#,##0.%s', str_pad('', $decimais, '0'));
495
496 1
        $fmt = new \NumberFormatter(config('app.locale'), \NumberFormatter::DECIMAL);
497 1
        $fmt->setPattern($pattern);
498 1
        return $fmt->format($valor);
499
    }
500
}
501
502
if (! function_exists('maskCep')) {
503
    /**
504
     * Cria a mascara do cep
505
     *
506
     * @param string $value
507
     *
508
     * @return string
509
     * @example : maskCep(12345678) = 12345-678
510
     */
511
    function maskCep($value)
512
    {
513 1
        $capture = '/^([0-9]{5})([0-9]{3})$/';
514 1
        $format = '$1-$2';
515 1
        $value = preg_replace('[^0-9]', '', $value);
516 1
        $result = preg_replace($capture, $format, $value);
517 1
        if (!is_null($result)) {
518 1
            $value = $result;
519 1
        }
520 1
        return $value;
521
    }
522
}
523
524
if (! function_exists('maskCpf')) {
525
    /**
526
     * Cria a mascara do cpf
527
     *
528
     * @param string $value
529
     *
530
     * @return string
531
     * @example : maskCpf(12345678901) = 123.456.789-01
532
     */
533
    function maskCpf($value)
534
    {
535 2
        $capture = '/^([0-9]{3})([0-9]{3})([0-9]{3})([0-9]{2})$/';
536 2
        $format = '$1.$2.$3-$4';
537 2
        $value = preg_replace('[^0-9]', '', $value);
538 2
        $result = preg_replace($capture, $format, $value);
539 2
        if (!is_null($result)) {
540 2
            $value = $result;
541 2
        }
542 2
        return $value;
543
    }
544
}
545
546
if (! function_exists('maskCnpj')) {
547
    /**
548
     * Cria a mascara do cnpj
549
     *
550
     * @param string $value
551
     *
552
     * @return string
553
     * @example : maskCpf(00123456/0001-78) = 00.123.456/0001-78
554
     */
555
    function maskCnpj($value)
556
    {
557 2
        $capture = '/^([0-9]{2,3})([0-9]{3})([0-9]{3})([0-9]{4})([0-9]{2})$/';
558 2
        $format = '$1.$2.$3/$4-$5';
559 2
        $value = preg_replace('[^0-9]', '', $value);
560 2
        $result = preg_replace($capture, $format, $value);
561 2
        if (!is_null($result)) {
562 2
            $value = $result;
563 2
        }
564 2
        return $value;
565
    }
566
}
567
568
if (! function_exists('maskCpfOrCnpj')) {
569
    /**
570
     * Cria a mascara do cpf ou cnpj
571
     *
572
     * @param string $value
573
     *
574
     * @return string
575
     */
576
    function maskCpfOrCnpj($value)
577
    {
578 1
        $value = preg_replace('[^0-9]', '', $value);
579 1
        if (strlen($value)==11) {
580 1
            return maskCpf($value);
581
        } else {
582 1
            return maskCnpj($value);
583
        }
584
    }
585
}
586
587
if (! function_exists('numberRoman')) {
588
    /**
589
     * Number integer to Roman
590
     *
591
     * @param integer $integer
592
     *
593
     * @return string
594
     */
595
    function numberRoman($integer)
596
    {
597
        $table = array(
598 1
            'M'  =>1000,
599 1
            'CM' =>900,
600 1
            'D'  =>500,
601 1
            'CD' =>400,
602 1
            'C'  =>100,
603 1
            'XC' =>90,
604 1
            'L'  =>50,
605 1
            'XL' =>40,
606 1
            'X'  =>10,
607 1
            'IX' =>9,
608 1
            'V'  =>5,
609 1
            'IV' =>4,
610
            'I'  =>1
611 1
        );
612
613 1
        if ($integer < 1 || $integer > 3999) {
614 1
            return $integer;
615
        }
616
617 1
        $return = '';
618 1
        while ($integer > 0) {
619 1
            foreach ($table as $rom => $arb) {
620 1
                if ($integer >= $arb) {
621 1
                    $integer -= $arb;
622 1
                    $return .= $rom;
623 1
                    break;
624
                }
625 1
            }
626 1
        }
627
628 1
        return $return;
629
    }
630
}
631
632
if (! function_exists('numberLetra')) {
633
    /**
634
     * Number to Letra
635
     *
636
     * @param integer    $number
637
     * @param array|null $letras
638
     * @param integer    $nivel
639
     *
640
     * @return string
641
     */
642
    function numberLetra($number, array $letras = null, $nivel = -1)
643
    {
644 1
        $number = trim($number);
645 1
        if (preg_match('/[^0-9]/', $number)) {
646 1
            return $number;
647
        }
648
649 1
        $num = intval($number);
650
651
        $letrasOrig = array(
652 1
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
653 1
            'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
654 1
        );
655
656 1
        if (is_null($letras)) {
657 1
            $letras = $letrasOrig;
658 1
        }
659
660 1
        $nivel++;
661 1
        if ($num > count($letras) && array_key_exists($nivel, $letras)) {
662 1
            $letraParent = $letras[$nivel];
663 1
            foreach ($letrasOrig as $value) {
664 1
                $letras[] = $letraParent.$value;
665 1
            }
666
667 1
            return numberLetra($num, $letras, $nivel);
668
        }
669
        
670 1
        $index = $num-1;
671 1
        if (array_key_exists($index, $letras)) {
672 1
            $return = $letras[$index];
673 1
        } else {
674 1
            $return = $number;
675
        }
676
677 1
        return $return;
678
    }
679
}
680
681
if (! function_exists('activePattern')) {
682
    /**
683
     * Return class $active, para url pattern,
684
     * caso contrario $inactive
685
     *
686
     * @param string $path     String Path
687
     * @param string $active   String Active
688
     * @param string $inactive String Inactive
689
     *
690
     * @return string
691
     */
692
    function activePattern($path, $active = 'active', $inactive = '')
693
    {
694 1
        $method = '\Illuminate\Support\Facades\Request::is';
695 1
        return call_user_func_array($method, (array) $path) ? $active : $inactive;
696
    }
697
}
698
699
if (! function_exists('activeRoute')) {
700
    /**
701
     * Return class $active, para route currentRoute
702
     * caso contrario $inactive
703
     *
704
     * @param string $route    String Route
705
     * @param string $active   String Active
706
     * @param string $inactive String Inactive
707
     *
708
     * @return string
709
     */
710
    function activeRoute($route, $active = 'active', $inactive = '')
711
    {
712 4
        $method = '\Illuminate\Support\Facades\Route::currentRouteName';
713 4
        return call_user_func_array($method, [])==$route ? $active : $inactive;
714
    }
715
}
716
717
if (! function_exists('linkRoute')) {
718
    /**
719
     * Cria o link com currentRoute
720
     *
721
     * @param string $route String Route
722
     * @param string $label String Label
723
     * @param string $class String Class
724
     *
725
     * @return string
726
     */
727
    function linkRoute($route, $label, $class = '')
728
    {
729 3
        return sprintf('<a href="%s" class="%s">%s</a>', route($route), $class?:activeRoute($route), $label);
730
    }
731
}
732
733
if (! function_exists('activity')) {
734
    /**
735
     * Log activity
736
     *
737
     * @param string    $action
738
     * @param string    $description
739
     * @param \Eloquent $model
740
     *
741
     * @return bool
742
     */
743
    function activity($action, $description, $model = null)
744
    {
745 1
        return app('nwlaravel.activity')->log($action, $description, $model);
746
    }
747
}
748