Completed
Push — master ( d06bab...02e31a )
by Eugene
03:46
created

PeclLitePacker::unpack()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 24
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 0
loc 24
ccs 0
cts 18
cp 0
rs 8.5125
cc 5
eloc 13
nc 4
nop 1
crap 30
1
<?php
2
3
namespace Tarantool\Client\Packer;
4
5
use Tarantool\Client\Exception\Exception;
6
use Tarantool\Client\IProto;
7
use Tarantool\Client\Request\Request;
8
use Tarantool\Client\Response;
9
10
class PeclLitePacker implements Packer
11
{
12
    /**
13
     * {@inheritdoc}
14
     */
15
    public function pack(Request $request, $sync = null)
16
    {
17
        // @see https://github.com/msgpack/msgpack-php/issues/45
18
        $content = pack('C*', 0x82, IProto::CODE, $request->getType(), IProto::SYNC);
19
        $content .= msgpack_pack((int) $sync);
20
21
        if (null !== $body = $request->getBody()) {
22
            $content .= msgpack_pack($body);
23
        }
24
25
        return PackUtils::packLength(strlen($content)).$content;
26
    }
27
28
    /**
29
     * {@inheritdoc}
30
     */
31
    public function unpack($data)
32
    {
33
        $headerSize = PackUtils::getHeaderSize($data);
34
35
        if (!$header = substr($data, 0, $headerSize)) {
36
            throw new Exception('Unable to unpack data.');
37
        }
38
39
        $header = msgpack_unpack($header);
40
        if (!is_array($header)) {
41
            throw new Exception('Unable to unpack data.');
42
        }
43
44
        $code = $header[IProto::CODE];
45
46
        $body = substr($data, $headerSize);
47
        $body = msgpack_unpack($body);
48
49
        if ($code >= Request::TYPE_ERROR) {
50
            throw new Exception($body[IProto::ERROR], $code & (Request::TYPE_ERROR - 1));
51
        }
52
53
        return new Response($header[IProto::SYNC], $body ? $body[IProto::DATA] : null);
54
    }
55
}
56