Passed
Push — master ( 2c25f8...c0741a )
by
unknown
05:43
created

Date   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Test Coverage

Coverage 88.24%

Importance

Changes 0
Metric Value
eloc 15
dl 0
loc 47
ccs 15
cts 17
cp 0.8824
rs 10
c 0
b 0
f 0
wmc 8

3 Methods

Rating   Name   Duplication   Size   Complexity  
A toDatetime() 0 19 5
A isValid() 0 5 2
A durationToIso8601() 0 6 1
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
     */
63 1
    public static function durationToIso8601(float $duration): string
64
    {
65 1
        $duration = (int) round($duration);
66 1
        $dateInterval = \DateInterval::createFromDateString("$duration seconds");
67
68 1
        return $dateInterval->format('PT%HH%IM%SS');
69
    }
70
}
71