Completed
Push — master ( 326602...e591d7 )
by Renato
07:39
created

helpers.php ➔ currencySymbol()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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