Completed
Push — master ( c35302...4815d7 )
by Renato
05:32
created

helpers.php ➔ fromDateTime()   D

Complexity

Conditions 10
Paths 18

Size

Total Lines 33
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 22
CRAP Score 10

Importance

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