Passed
Push — master ( de0a3f...b345b0 )
by
unknown
15:31
created

Date::durationToIso8601()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 5
nc 1
nop 1
dl 0
loc 8
ccs 6
cts 6
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * This file is part of Cecil.
5
 *
6
 * (c) Arnaud Ligny <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace Cecil\Util;
15
16
/**
17
 * Date utility class.
18
 *
19
 * This class provides utility methods for handling dates,
20
 * including validation, conversion to DateTime, and formatting durations.
21
 */
22
class Date
23
{
24
    /**
25
     * Checks if a date is valid.
26
     */
27 1
    public static function isValid(string $date, string $format = 'Y-m-d'): bool
28
    {
29 1
        $d = \DateTime::createFromFormat($format, $date);
30
31 1
        return $d && $d->format($format) === $date;
32
    }
33
34
    /**
35
     * Date to DateTime.
36
     *
37
     * @param mixed $date
38
     */
39 1
    public static function toDatetime($date): \DateTime
40
    {
41 1
        if ($date === null) {
42
            throw new \Exception('$date can\'t be null.');
43
        }
44
        // DateTime
45 1
        if ($date instanceof \DateTime) {
46 1
            return $date;
47
        }
48
        // DateTimeImmutable
49 1
        if ($date instanceof \DateTimeImmutable) {
50 1
            return \DateTime::createFromImmutable($date);
51
        }
52
        // timestamp
53 1
        if (\is_int($date)) {
54
            return (new \DateTime())->setTimestamp($date);
55
        }
56
57 1
        return new \DateTime($date);
58
    }
59
60
    /**
61
     * Duration in seconds to ISO 8601.
62
     * e.g.: '00:00:46.70' -> 'T0M46S'
63
     */
64 1
    public static function durationToIso8601(string $duration): string
65
    {
66 1
        $time = new \DateTime($duration);
67 1
        $midnight = new \DateTime();
68 1
        $midnight->setTime(0, 0);
69 1
        $period = $midnight->diff($time);
70
71 1
        return $period->format('T%iM%SS');
72
    }
73
}
74