Completed
Push — master ( ad65a7...54d45f )
by Renato
07:29
created

helpers.php ➔ storageFormat()   C

Complexity

Conditions 7
Paths 10

Size

Total Lines 27
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 24
CRAP Score 7

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 7
eloc 16
c 2
b 0
f 0
nc 10
nop 2
dl 0
loc 27
ccs 24
cts 24
cp 1
crap 7
rs 6.7272
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 5
                checkdate($date['month'], $date['day'], $date['year'])
48 7
            ) {
49 5
                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 2
            if (strtotime($value) !== false) {
60 1
                return (new Carbon($value));
61
            }
62 2
        }
63
64 2
        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 1
            $dateFormat = config('nwlaravel.date_format');
88 1
            $date = date_parse_from_format($dateFormat, $value);
89
90 1
            if (isset($date['error_count']) && $date['error_count'] == 0) {
91 1
                if (checkdate($date['month'], $date['day'], $date['year'])) {
92 1
                    $value = Carbon::createFromFormat($dateFormat, $value)->startOfDay();
93 1
                }
94
95 1
            } 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 1
            if (strtotime($value) !== false) {
103 1
                $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 1
            }
105 1
        }
106
107 2
        if ($value instanceof DateTime) {
108 2
            return $value->format($format);
109
        }
110
111 1
        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 20
    {
189 20
        $storage = trim($storage);
190 15
        if (!is_numeric($storage)) {
191 15
            return $storage;
192 20
        }
193 1
194 1
        $sizes = ['KB' => 1, 'MB' => 2, 'GB' => 3, 'TB' => 4, 'PB' => 5];
195 19
196 1
        if (!is_null($nivel) && array_key_exists(strtoupper($nivel), $sizes)) {
197 1
            $multi = 1024*pow(1000, $sizes[strtoupper($nivel)]);
198 18
            $storage = $storage * $multi;
199 1
            if ($storage >= $multi) {
200 1
                $storage = $storage / 1024;
201 17
            }
202 1
        }
203 1
204 16
        $sufix = 'B';
205 1
        foreach (array_keys($sizes) as $size) {
206 1
            if ($storage >= 1000) {
207 20
                $storage = $storage / 1000;
208
                $sufix = $size;
209 20
            }
210
        }
211 20
212 5
        return toFixed($storage, 1).$sufix;
213 5
    }
214
}
215 20
216 20
if (! function_exists('dateFormatter')) {
217 18
    /**
218 18
     * Date Formatter
219 18
     *
220
     * @param DateTime $date     Date Time
221 20
     * @param string   $dateType String Date Type
222 13
     * @param string   $timeType String Time Type
223 13
     *
224 13
     * @return string
225
     */
226 20
    function dateFormatter($date, $dateType, $timeType)
227 8
    {
228 8
        if ($date instanceof \DateTime) {
229 8
            $fmt = new \IntlDateFormatter(
230
                config('app.locale'),
231 20
                $dateType,
232 4
                $timeType,
233 4
                config('app.timezone')
234 4
            );
235
236 20
            return $fmt->format($date);
237 2
        }
238 2
239 2
        return $date;
240
    }
241 20
}
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
        return dateFormatter($date, \IntlDateFormatter::MEDIUM, \IntlDateFormatter::MEDIUM);
255
    }
256
}
257 2
258 2
if (! function_exists('formatTimeShort')) {
259 2
    /**
260 2
     * Format Time Short
261 2
     *
262 2
     * @param DateTime $date Date Time
263 2
     *
264
     * @return string
265 2
     * @example : HH:MIN
266
     */
267
    function formatTimeShort($date)
268 1
    {
269
        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 1
    {
284
        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 1
    {
299
        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 1
    {
314
        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 1
    {
329
        if ($date instanceof \DateTime) {
330
            $date = sprintf(
331
                '%s - %s',
332
                dateFormatter($date, \IntlDateFormatter::LONG, \IntlDateFormatter::NONE),
333
                dateFormatter($date, \IntlDateFormatter::NONE, \IntlDateFormatter::MEDIUM)
334
            );
335
        }
336
337
        return $date;
338
    }
339
}
340
341
if (! function_exists('formatDateFull')) {
342
    /**
343 1
     * 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
        return dateFormatter($date, \IntlDateFormatter::FULL, \IntlDateFormatter::NONE);
353
    }
354
}
355
356
if (! function_exists('formatDateTimeFull')) {
357
    /**
358 1
     * Format Date Time Full
359 1
     *
360 1
     * @param DateTime $date Date Time
361 1
     *
362 1
     * @return string
363 1
     * @example : [SEMANA], [DIA] de [MES] de [ANO] - HH:MIN:SS
364 1
     */
365
    function formatDateTimeFull($date)
366 1
    {
367
        if ($date instanceof \DateTime) {
368
            return sprintf(
369
                '%s - %s',
370
                dateFormatter($date, \IntlDateFormatter::FULL, \IntlDateFormatter::NONE),
371
                dateFormatter($date, \IntlDateFormatter::NONE, \IntlDateFormatter::MEDIUM)
372
            );
373
        }
374
375
        return $date;
376
    }
377
}
378
379
if (! function_exists('formatDateTimeShort')) {
380
    /**
381 1
     * 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
        return dateFormatter($date, \IntlDateFormatter::MEDIUM, \IntlDateFormatter::SHORT);
391
    }
392
}
393
394
if (! function_exists('diffForHumans')) {
395
    /**
396 1
     * Diff date for Humans
397 1
     *
398 1
     * @param string|DataTime $date     String\DateTime Date
399 1
     * @param string|DataTime $other    String\DateTime Other
400 1
     * @param boolean         $absolute Boolean Absolute
401 1
     *
402
     * @return string
403
     * @example : 7 minutos atras
404 1
     */
405
    function diffForHumans($date, $other = null, $absolute = false)
406
    {
407
        if ($date instanceof \DateTime) {
408
            $date = Carbon::instance($date);
409
            if (!$other instanceof Carbon) {
410
                $other = null;
411
            }
412
            return $date->diffForHumans($other, $absolute);
413
        }
414
415
        return '';
416
    }
417
}
418
419 1
if (! function_exists('now')) {
420
    /**
421
     * Now Date Time
422
     *
423
     * @return Carbon
424
     */
425
    function now()
426
    {
427
        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 1
     *
437 1
     * @return string
438 1
     * @example : formatCurrency(8712.335) = R$8.712,34
439 1
     */
440 1
    function formatCurrency($valor)
441 1
    {
442
        $fmt = new \NumberFormatter(config('app.locale'), \NumberFormatter::CURRENCY);
443
        return $fmt->format(floatval($valor));
444 1
    }
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 2
     */
457
    function formatNumber($valor, $decimais = 2)
458
    {
459
        $valor   = floatval($valor);
460
        $decimais = intval($decimais);
461
462
        $pattern = sprintf('#,##0.%s', str_pad('', $decimais, '0'));
463
464
        $fmt = new \NumberFormatter(config('app.locale'), \NumberFormatter::DECIMAL);
465
        $fmt->setPattern($pattern);
466
        return $fmt->format($valor);
467
    }
468
}
469
470
if (! function_exists('maskCpf')) {
471 1
    /**
472 1
     * 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
        $capture = '/^([0-9]{3})([0-9]{3})([0-9]{3})([0-9]{2})$/';
482
        $format = '$1.$2.$3-$4';
483
        $value = preg_replace('[^0-9]', '', $value);
484
        $result = preg_replace($capture, $format, $value);
485
        if (!is_null($result)) {
486
            $value = $result;
487
        }
488 1
        return $value;
489 1
    }
490
}
491 1
492
if (! function_exists('maskCnpj')) {
493 1
    /**
494 1
     * Cria a mascara do cnpj
495 1
     *
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
        $capture = '/^([0-9]{2,3})([0-9]{3})([0-9]{3})([0-9]{4})([0-9]{2})$/';
504
        $format = '$1.$2.$3/$4-$5';
505
        $value = preg_replace('[^0-9]', '', $value);
506
        $result = preg_replace($capture, $format, $value);
507
        if (!is_null($result)) {
508
            $value = $result;
509
        }
510 2
        return $value;
511 2
    }
512 2
}
513 2
514 2
if (! function_exists('maskCpfOrCnpj')) {
515 2
    /**
516 2
     * Cria a mascara do cpf ou cnpj
517 2
     *
518
     * @param string $value
519
     *
520
     * @return string
521
     */
522
    function maskCpfOrCnpj($value)
523
    {
524
        $value = preg_replace('[^0-9]', '', $value);
525
        if (strlen($value)==11) {
526
            return maskCpf($value);
527
        } else {
528
            return maskCnpj($value);
529
        }
530
    }
531
}
532 2
533 2
if (! function_exists('numberRoman')) {
534 2
    /**
535 2
     * Number integer to Roman
536 2
     *
537 2
     * @param integer $integer
538 2
     *
539 2
     * @return string
540
     */
541
    function numberRoman($integer)
542
    {
543
        $table = array(
544
            'M'  =>1000,
545
            'CM' =>900,
546
            'D'  =>500,
547
            'CD' =>400,
548
            'C'  =>100,
549
            'XC' =>90,
550
            'L'  =>50,
551
            'XL' =>40,
552
            'X'  =>10,
553 1
            'IX' =>9,
554 1
            'V'  =>5,
555 1
            'IV' =>4,
556
            'I'  =>1
557 1
        );
558
559
        if ($integer < 1 || $integer > 3999) {
560
            return $integer;
561
        }
562
563
        $return = '';
564
        while ($integer > 0) {
565
            foreach ($table as $rom => $arb) {
566
                if ($integer >= $arb) {
567
                    $integer -= $arb;
568
                    $return .= $rom;
569
                    break;
570
                }
571
            }
572
        }
573 1
574 1
        return $return;
575 1
    }
576 1
}
577 1
578 1
if (! function_exists('numberLetra')) {
579 1
    /**
580 1
     * Number to Letra
581 1
     *
582 1
     * @param integer    $number
583 1
     * @param array|null $letras
584 1
     * @param integer    $nivel
585
     *
586 1
     * @return string
587
     */
588 1
    function numberLetra($number, array $letras = null, $nivel = -1)
589 1
    {
590
        $number = trim($number);
591
        if (preg_match('/[^0-9]/', $number)) {
592 1
            return $number;
593 1
        }
594 1
595 1
        $num = intval($number);
596 1
597 1
        $letrasOrig = array(
598 1
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
599
            'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
600 1
        );
601 1
602
        if (is_null($letras)) {
603 1
            $letras = $letrasOrig;
604
        }
605
606
        $nivel++;
607
        if ($num > count($letras) && array_key_exists($nivel, $letras)) {
608
            $letraParent = $letras[$nivel];
609
            foreach ($letrasOrig as $value) {
610
                $letras[] = $letraParent.$value;
611
            }
612
613
            return numberLetra($num, $letras, $nivel);
614
        }
615
        
616
        $index = $num-1;
617
        if (array_key_exists($index, $letras)) {
618
            $return = $letras[$index];
619 1
        } else {
620 1
            $return = $number;
621 1
        }
622
623
        return $return;
624 1
    }
625
}
626
627 1
if (! function_exists('activePattern')) {
628 1
    /**
629 1
     * Return class $active, para url pattern,
630
     * caso contrario $inactive
631 1
     *
632 1
     * @param string $path     String Path
633 1
     * @param string $active   String Active
634
     * @param string $inactive String Inactive
635 1
     *
636 1
     * @return string
637 1
     */
638 1
    function activePattern($path, $active = 'active', $inactive = '')
639 1
    {
640 1
        $method = '\Illuminate\Support\Facades\Request::is';
641
        return call_user_func_array($method, (array) $path) ? $active : $inactive;
642 1
    }
643
}
644
645 1
if (! function_exists('activeRoute')) {
646 1
    /**
647 1
     * Return class $active, para route currentRoute
648 1
     * caso contrario $inactive
649 1
     *
650
     * @param string $route    String Route
651
     * @param string $active   String Active
652 1
     * @param string $inactive String Inactive
653
     *
654
     * @return string
655
     */
656
    function activeRoute($route, $active = 'active', $inactive = '')
657
    {
658
        $method = '\Illuminate\Support\Facades\Route::currentRouteName';
659
        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 1
     * @param string $class String Class
670 1
     *
671
     * @return string
672
     */
673
    function linkRoute($route, $label, $class = '')
674
    {
675
        return sprintf('<a href="%s" class="%s">%s</a>', route($route), $class?:activeRoute($route), $label);
676
    }
677
}
678
679
if (! function_exists('fileSystemAsset')) {
680
    /**
681
     * File System Asset
682
     *
683
     * @param string $path String Path
684
     *
685
     * @return string
686
     */
687 4
    function fileSystemAsset($path)
688 4
    {
689
        $default = config('filesystems.default');
690
691
        switch ($default) {
692
            case 'ftp':
693
                $url = trim(config('filesystems.disks.ftp.url'), '/').'/'.$path;
694
                break;
695
            case 'sftp':
696
                $url = trim(config('filesystems.disks.sftp.url'), '/').'/'.$path;
697
                break;
698
            case 's3':
699
                $url = trim(config('filesystems.disks.s3.url'), '/').'/'.$path;
700
                break;
701
            case 'local':
702
            default:
703
                $url = asset('storage/'.$path);
704 3
        }
705
706
        return $url;
707
    }
708
}
709