DateTime::createFromMultipleFormats()   A
last analyzed

Complexity

Conditions 6
Paths 6

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 11
c 1
b 0
f 0
nc 6
nop 2
dl 0
loc 18
ccs 11
cts 11
cp 1
crap 6
rs 9.2222
1
<?php
2
3
namespace ThinKit\Helpers;
4
5
use Carbon\Carbon;
6
use Carbon\Exceptions\InvalidFormatException;
7
8
class DateTime
9
{
10
    /**
11
     * Create date object from multiple formats.
12
     *
13
     * @param  array  $formats
14
     * @param  string  $dateString
15
     * @return \Carbon\Carbon
16
     * @throws \Exception|\Carbon\Exceptions\InvalidFormatException
17
     */
18 2
    public static function createFromMultipleFormats(array $formats, string $dateString): Carbon
19
    {
20 2
        $dateObj   = null;
21 2
        $lastError = null;
22 2
        foreach ($formats as $format) {
23
            try {
24 2
                if ($dateObj = Carbon::createFromFormat($format, $dateString)) {
25 1
                    break;
26
                }
27 2
            } catch (InvalidFormatException $e) {
28 2
                $lastError = $e;
29
            }
30
        }
31 2
        if (!$dateObj && $lastError) {
32 1
            throw $lastError;
33
        }
34
35 1
        return $dateObj;
36
    }
37
}
38