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

PeclPacker::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 3
Bugs 0 Features 2
Metric Value
c 3
b 0
f 2
dl 0
loc 5
ccs 0
cts 5
cp 0
rs 9.4285
cc 1
eloc 3
nc 1
nop 1
crap 2
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 PeclPacker implements Packer
11
{
12
    private $packer;
13
    private $unpacker;
14
15
    public function __construct($phpOnly = true)
16
    {
17
        $this->packer = new \MessagePack($phpOnly);
18
        $this->unpacker = new \MessagePackUnpacker($phpOnly);
19
    }
20
21
    /**
22
     * {@inheritdoc}
23
     */
24
    public function pack(Request $request, $sync = null)
25
    {
26
        // @see https://github.com/msgpack/msgpack-php/issues/45
27
        $content = pack('C*', 0x82, IProto::CODE, $request->getType(), IProto::SYNC);
28
        $content .= $this->packer->pack((int) $sync);
29
30
        if (null !== $body = $request->getBody()) {
31
            $content .= $this->packer->pack($body);
32
        }
33
34
        return PackUtils::packLength(strlen($content)).$content;
35
    }
36
37
    /**
38
     * {@inheritdoc}
39
     */
40
    public function unpack($data)
41
    {
42
        $this->unpacker->feed($data);
43
44
        if (!$this->unpacker->execute()) {
45
            throw new Exception('Unable to unpack data.');
46
        }
47
48
        $header = $this->unpacker->data();
49
50
        if (!$this->unpacker->execute()) {
51
            throw new Exception('Unable to unpack data.');
52
        }
53
54
        $body = (array) $this->unpacker->data();
55
        $code = $header[IProto::CODE];
56
57
        if ($code >= Request::TYPE_ERROR) {
58
            throw new Exception($body[IProto::ERROR], $code & (Request::TYPE_ERROR - 1));
59
        }
60
61
        return new Response(
62
            $header[IProto::SYNC],
63
            isset($body[IProto::DATA]) ? $body[IProto::DATA] : null
64
        );
65
    }
66
}
67