Passed
Push — master ( 2b3c7f...540fca )
by Chris
02:40
created

datetimeinterface_to_datetimeimmutable()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 23
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 6

Importance

Changes 0
Metric Value
cc 4
eloc 12
nc 4
nop 1
dl 0
loc 23
ccs 1
cts 2
cp 0.5
crap 6
rs 8.7972
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
3
namespace DaveRandom\LibLifxLan;
4
5
use DaveRandom\LibLifxLan\Exceptions\InvalidValueException;
6
7
if (\strlen(\pack('e', 0.1)) === 4) {
8
    \define(__NAMESPACE__ . '\\FLOAT32_CODE', 'e');
9
} else if (\strlen(\pack('g', 0.1)) === 4) {
10
    \define(__NAMESPACE__ . '\\FLOAT32_CODE', 'g');
11
} else {
12
    /** @noinspection PhpUnhandledExceptionInspection */
13
    throw new \Error('Cannot pack()/unpack() floating point numbers to a 32-bit little-endian representation');
14
}
15
16
\define(__NAMESPACE__ . '\\UINT32_MIN', \PHP_INT_SIZE === 4 ? \PHP_INT_MIN : 0);
17
\define(__NAMESPACE__ . '\\UINT32_MAX', \PHP_INT_SIZE === 4 ? \PHP_INT_MIN : 0xffffffff);
18
19 6
/**
20
 * @param \DateTimeInterface $dateTime
21
 * @return \DateTimeImmutable
22
 * @throws InvalidValueException
23 6
 */
24 6
function datetimeinterface_to_datetimeimmutable(\DateTimeInterface $dateTime): \DateTimeImmutable
25
{
26
    static $utcTimeZone;
27
28
    if ($dateTime instanceof \DateTimeImmutable) {
29
        return $dateTime;
30
    }
31
32
    if ($dateTime instanceof \DateTime) {
33
        return \DateTimeImmutable::createFromMutable($dateTime);
34
    }
35
36
    $result = \DateTimeImmutable::createFromFormat(
37
        'u U',
38
        $dateTime->format('u U'),
39
        $utcTimeZone ?? ($utcTimeZone = new \DateTimeZone('UTC'))
40
    );
41
42
    if ($result === false) {
43
        throw new InvalidValueException('Could not create DateTimeImmutable instance from DateTimeInterface instance');
44
    }
45
46
    return $result;
47
}
48