Completed
Push — master ( 9426d5...32c10e )
by Renato
09:25
created

helpers.php ➔ fileSystemAsset()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 21
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 5

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 16
c 1
b 0
f 0
nc 5
nop 1
dl 0
loc 21
ccs 15
cts 15
cp 1
crap 5
rs 8.7624

1 Method

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