Passed
Push — video ( 4405b6...c764a6 )
by Arnaud
09:44 queued 04:41
created

Date::durationToIso8601()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 5
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 8
rs 10
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
32
     */
33
    public static function toDatetime($date): \DateTime
34
    {
35
        if ($date === null) {
36
            throw new \Exception('$date can\'t be null.');
37
        }
38
        // DateTime
39
        if ($date instanceof \DateTime) {
40
            return $date;
41
        }
42
        // DateTimeImmutable
43
        if ($date instanceof \DateTimeImmutable) {
44
            return \DateTime::createFromImmutable($date);
45
        }
46
        // timestamp
47
        if (\is_int($date)) {
48
            return (new \DateTime())->setTimestamp($date);
49
        }
50
51
        return new \DateTime($date);
52
    }
53
54
    /**
55
     * Duration in seconds to ISO 8601.
56
     * e.g.: '00:00:46.70' -> 'T0M46S'
57
     */
58
    public static function durationToIso8601(string $duration): string
59
    {
60
        $time = new \DateTime($duration);
61
        $midnight = new \DateTime();
62
        $midnight->setTime(0, 0);
63
        $period = $midnight->diff($time);
64
65
        return $period->format('T%iM%SS');
66
    }
67
}
68