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

PeclLitePacker   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 4

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 7
lcom 0
cbo 4
dl 0
loc 46
ccs 0
cts 27
cp 0
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A pack() 0 12 2
B unpack() 0 24 5
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