DateTimeHelper   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 68
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 0
dl 0
loc 68
ccs 20
cts 20
cp 1
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A _createDateTime() 0 17 4
A _roundDownFractionalSeconds() 0 5 1
A _createTimeZone() 0 8 2
A _getLastDateTimeImmutableErrorsStr() 0 5 1
1
<?php
2
3
declare(strict_types = 1);
4
5
namespace X509\Feature;
6
7
/**
8
 * Helper trait for classes employing date and time handling.
9
 */
10
trait DateTimeHelper
11
{
12
    /**
13
     * Create DateTime object from time string and timezone.
14
     *
15
     * @param string|null $time Time string, default to 'now'
16
     * @param string|null $tz Timezone, default if omitted
17
     * @throws \RuntimeException
18
     * @return \DateTimeImmutable
19
     */
20 15
    private static function _createDateTime($time = null, $tz = null): \DateTimeImmutable
21
    {
22 15
        if (!isset($time)) {
23 4
            $time = 'now';
24
        }
25 15
        if (!isset($tz)) {
26 11
            $tz = date_default_timezone_get();
27
        }
28
        try {
29 15
            $dt = new \DateTimeImmutable($time, self::_createTimeZone($tz));
30 13
            return self::_roundDownFractionalSeconds($dt);
31 2
        } catch (\Exception $e) {
32 2
            throw new \RuntimeException(
33
                "Failed to create DateTime: " .
34 2
                     self::_getLastDateTimeImmutableErrorsStr(), 0, $e);
35
        }
36
    }
37
    
38
    /**
39
     * Rounds a \DateTimeImmutable value such that fractional
40
     * seconds are removed.
41
     *
42
     * @param \DateTimeImmutable $dt
43
     * @return \DateTimeImmutable
44
     */
45 14
    private static function _roundDownFractionalSeconds(\DateTimeImmutable $dt): \DateTimeImmutable
46
    {
47 14
        return \DateTimeImmutable::createFromFormat("Y-m-d H:i:s",
48 14
            $dt->format("Y-m-d H:i:s"), $dt->getTimezone());
49
    }
50
    
51
    /**
52
     * Create DateTimeZone object from string.
53
     *
54
     * @param string $tz
55
     * @throws \UnexpectedValueException
56
     * @return \DateTimeZone
57
     */
58 15
    private static function _createTimeZone(string $tz): \DateTimeZone
59
    {
60
        try {
61 15
            return new \DateTimeZone($tz);
62 1
        } catch (\Exception $e) {
63 1
            throw new \UnexpectedValueException("Invalid timezone.", 0, $e);
64
        }
65
    }
66
    
67
    /**
68
     * Get last error caused by DateTimeImmutable.
69
     *
70
     * @return string
71
     */
72 2
    private static function _getLastDateTimeImmutableErrorsStr(): string
73
    {
74 2
        $errors = \DateTimeImmutable::getLastErrors()["errors"];
75 2
        return implode(", ", $errors);
76
    }
77
}
78