Passed
Push — variables ( 7d01df...502991 )
by Arnaud
07:26 queued 03:49
created

Date::toDatetime()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 5
nc 3
nop 1
dl 0
loc 12
rs 10
c 0
b 0
f 0
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
    public static function isValid(string $date, string $format = 'Y-m-d'): bool
22
    {
23
        $d = \DateTime::createFromFormat($format, $date);
24
25
        return $d && $d->format($format) === $date;
26
    }
27
28
    /**
29
     * Date to DateTime.
30
     *
31
     * @param mixed $date Can be a DateTIme object, a timestamp or a string
32
     */
33
    public static function toDatetime($date): \DateTime
34
    {
35
        // DateTime
36
        if ($date instanceof \DateTime) {
37
            return $date;
38
        }
39
        // timestamp or 'AAAA-MM-DD'
40
        if (is_numeric($date)) {
41
            return (new \DateTime())->setTimestamp($date);
42
        }
43
        // string (ie: '01/01/2019', 'today')
44
        return new \DateTime($date);
45
    }
46
}
47