DateUtil::tryParseDate()   A
last analyzed

Complexity

Conditions 4
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 3
c 1
b 0
f 0
nc 2
nop 2
dl 0
loc 7
rs 10
1
<?php
2
3
namespace Ipag\Sdk\Util;
4
5
use DateTime;
6
use DateTimeInterface;
7
use InvalidArgumentException;
8
9
abstract class DateUtil
10
{
11
    public const ISO_DATE_FORMAT = 'Y-m-d';
12
13
    public static function parseDate($date, string $format = self::ISO_DATE_FORMAT): DateTimeInterface
14
    {
15
        $date = self::tryParseDate($date, $format);
16
17
        if (!$date) {
0 ignored issues
show
introduced by
$date is of type DateTimeInterface, thus it always evaluated to true.
Loading history...
18
            throw new InvalidArgumentException("Invalid date format ($date does not conform to $format)");
19
        }
20
21
        return $date;
22
    }
23
24
    public static function tryParseDate($date, string $format = self::ISO_DATE_FORMAT): ?DateTimeInterface
25
    {
26
        if (is_null($date) || $date instanceof DateTimeInterface) {
27
            return $date;
28
        }
29
30
        return DateTime::createFromFormat($format, $date) ?: null;
31
    }
32
}
33