Completed
Push — master ( 060a6c...9bcf1c )
by Chris
02:52
created

datetimeinterface_to_nanotime()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 1
cts 1
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
3
namespace DaveRandom\LibLifxLan;
4
5
const UINT32_MIN = 0;
6
const UINT32_MAX = 0xffffffff;
7
8
// @codeCoverageIgnoreStart
9
foreach (['g', 'f', 'e'] as $format) {
10
    if (\pack($format, -0.0) === "\x00\x00\x00\x80") {
11
        \define(__NAMESPACE__ . '\\FLOAT32_CODE', $format);
12
        break;
13
    }
14
}
15
16
if (!\defined(__NAMESPACE__ . '\\FLOAT32_CODE')) {
17
    /** @noinspection PhpUnhandledExceptionInspection */
18
    throw new \Error('Cannot pack()/unpack() floating point numbers to a 32-bit little-endian representation');
19
}
20
// @codeCoverageIgnoreEnd
21
22
/**
23
 * @param \DateTimeInterface $dateTime
24
 * @return \DateTimeImmutable
25
 */
26
function datetimeinterface_to_datetimeimmutable(\DateTimeInterface $dateTime): \DateTimeImmutable
27
{
28 44
    if ($dateTime instanceof \DateTimeImmutable) {
29 19
        return $dateTime;
30
    }
31
32 25
    \assert($dateTime instanceof \DateTime, new \Error('DateTimeInterface is not DateTimeImmutable or DateTime???'));
33
34 25
    return \DateTimeImmutable::createFromMutable($dateTime);
35
}
36
37
/**
38
 * @param int $timestamp
39
 * @return \DateTimeImmutable
40
 */
41
function nanotime_to_datetimeimmutable(int $timestamp): \DateTimeImmutable
42
{
43 1
    static $utcTimeZone;
44
45 1
    $usecs = \abs((int)(($timestamp % 1000000000) / 1000));
46 1
    $secs = (int)($timestamp / 1000000000);
47
48 1
    $result = \DateTimeImmutable::createFromFormat(
49 1
        'u U',
50 1
        \sprintf("%06d %d", $usecs, $secs),
51 1
        $utcTimeZone ?? ($utcTimeZone = new \DateTimeZone('UTC'))
52
    );
53
54 1
    \assert($result !== false, new \Error("Could not convert nanotime to DateTimeImmutable instance"));
55
56 1
    return $result;
1 ignored issue
show
Bug Best Practice introduced by
The expression return $result could return the type false which is incompatible with the type-hinted return DateTimeImmutable. Consider adding an additional type-check to rule them out.
Loading history...
57
}
58
59
function datetimeinterface_to_nanotime(\DateTimeInterface $dateTime): int
60
{
61 2
    return (int)$dateTime->format('Uu000');
62
}
63
64
function int16_to_uint16(int $signed): int
65
{
66 2
    return $signed < 0
67 2
        ? ($signed & 0x7fff) + ($signed & 0x8000)
68 2
        : $signed & 0x7fff;
69
}
70
71
function uint16_to_int16(int $unsigned): int
72
{
73 2
    return $unsigned >= 0x8000
74 2
        ? ($unsigned & 0x7fff) - ($unsigned & 0x8000)
75 2
        : $unsigned & 0x7fff;
76
}
77