Completed
Push — master ( 4815d7...3423e4 )
by Renato
05:34
created

helpers.php ➔ fromDateTime()   C

Complexity

Conditions 11
Paths 22

Size

Total Lines 36
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 25
CRAP Score 11

Importance

Changes 0
Metric Value
cc 11
eloc 22
nc 22
nop 1
dl 0
loc 36
ccs 25
cts 25
cp 1
crap 11
rs 5.2653
c 0
b 0
f 0

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