Passed
Push — master ( 61e06e...7fa9d3 )
by Arnaud
05:31
created

Date   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 36
Duplicated Lines 0 %

Test Coverage

Coverage 84.62%

Importance

Changes 2
Bugs 1 Features 0
Metric Value
eloc 12
c 2
b 1
f 0
dl 0
loc 36
ccs 11
cts 13
cp 0.8462
rs 10
wmc 7

2 Methods

Rating   Name   Duplication   Size   Complexity  
A isValid() 0 5 2
A toDatetime() 0 19 5
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of Cecil.
7
 *
8
 * Copyright (c) Arnaud Ligny <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Cecil\Util;
15
16
class Date
17
{
18
    /**
19
     * Checks if a date is valid.
20
     */
21 1
    public static function isValid(string $date, string $format = 'Y-m-d'): bool
22
    {
23 1
        $d = \DateTime::createFromFormat($format, $date);
24
25 1
        return $d && $d->format($format) === $date;
26
    }
27
28
    /**
29
     * Date to DateTime.
30
     *
31
     * @param mixed $date
32
     */
33 1
    public static function toDatetime($date): \DateTime
34
    {
35 1
        if ($date === null) {
36
            throw new \Exception('$date can\'t be null.');
37
        }
38
        // DateTime
39 1
        if ($date instanceof \DateTime) {
40 1
            return $date;
41
        }
42
        // DateTimeImmutable
43 1
        if ($date instanceof \DateTimeImmutable) {
44 1
            return \DateTime::createFromImmutable($date);
45
        }
46
        // timestamp
47 1
        if (\is_int($date)) {
48
            return (new \DateTime())->setTimestamp($date);
49
        }
50
51 1
        return new \DateTime($date);
52
    }
53
}
54