TimestampExtension::pack()   A
last analyzed

Complexity

Conditions 5
Paths 6

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 5

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 9
c 1
b 0
f 0
nc 6
nop 2
dl 0
loc 16
ccs 10
cts 10
cp 1
crap 5
rs 9.6111
1
<?php
2
3
/**
4
 * This file is part of the rybakit/msgpack.php package.
5
 *
6
 * (c) Eugene Leonovich <[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
namespace MessagePack\Extension;
13
14
use MessagePack\BufferUnpacker;
15
use MessagePack\Extension;
16
use MessagePack\Packer;
17
use MessagePack\Type\Timestamp;
18
19
final class TimestampExtension implements Extension
20
{
21
    private const TYPE = -1;
22
23 341
    public function getType() : int
24
    {
25 341
        return self::TYPE;
26
    }
27
28 24
    public function pack(Packer $packer, $value) : ?string
29
    {
30 24
        if (!$value instanceof Timestamp) {
31 15
            return null;
32
        }
33
34 9
        $sec = $value->getSeconds();
35 9
        $nsec = $value->getNanoseconds();
36
37 9
        if ($sec >> 34) {
38 3
            return $packer->packExt(self::TYPE, \pack('NJ', $nsec, $sec));
39
        }
40
41 6
        return (0 === $nsec && $sec <= 0xffffffff)
42 3
            ? $packer->packExt(self::TYPE, \pack('N', $sec))
43 6
            : $packer->packExt(self::TYPE, \pack('J', ($nsec << 34) | $sec));
44
    }
45
46
    /**
47
     * @return Timestamp
48
     */
49 9
    public function unpackExt(BufferUnpacker $unpacker, int $extLength)
50
    {
51 9
        if (4 === $extLength) {
52 3
            $data = $unpacker->read(4);
53
54 3
            $sec = \ord($data[0]) << 24
55 3
                | \ord($data[1]) << 16
56 3
                | \ord($data[2]) << 8
57 3
                | \ord($data[3]);
58
59 3
            return new Timestamp($sec);
60
        }
61 6
        if (8 === $extLength) {
62 3
            $data = $unpacker->read(8);
63
64 3
            $num = \unpack('J', $data)[1];
65 3
            $nsec = $num >> 34;
66 3
            if ($nsec < 0) {
67 1
                $nsec += 0x40000000;
68
            }
69
70 3
            return new Timestamp($num & 0x3ffffffff, $nsec);
71
        }
72
73 3
        $data = $unpacker->read(12);
74
75 3
        $nsec = \ord($data[0]) << 24
76 3
            | \ord($data[1]) << 16
77 3
            | \ord($data[2]) << 8
78 3
            | \ord($data[3]);
79
80 3
        return new Timestamp(\unpack('J', $data, 4)[1], $nsec);
81
    }
82
}
83