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

PurePacker   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 6

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 7
lcom 2
cbo 6
dl 0
loc 44
ccs 20
cts 20
cp 1
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A pack() 0 13 2
A unpack() 0 18 4
1
<?php
2
3
namespace Tarantool\Client\Packer;
4
5
use MessagePack\BufferUnpacker;
6
use MessagePack\Packer as MessagePackPacker;
7
use Tarantool\Client\Exception\Exception;
8
use Tarantool\Client\IProto;
9
use Tarantool\Client\Request\Request;
10
use Tarantool\Client\Response;
11
12
class PurePacker implements Packer
13
{
14
    private $packer;
15
    private $unpacker;
16
17 58
    public function __construct()
18
    {
19 58
        $this->packer = new MessagePackPacker();
20 58
        $this->unpacker = new BufferUnpacker();
21 58
    }
22
23 108
    public function pack(Request $request, $sync = null)
24
    {
25 108
        $content = $this->packer->packMap([
26 108
            IProto::CODE => $request->getType(),
27 108
            IProto::SYNC => (int) $sync,
28
        ]);
29
30 108
        if (null !== $body = $request->getBody()) {
31 99
            $content .= $this->packer->packMap($body);
32
        }
33
34 108
        return PackUtils::packLength(strlen($content)).$content;
35
    }
36
37 106
    public function unpack($data)
38
    {
39 106
        $message = $this->unpacker->reset($data)->tryUnpack();
40
41 106
        if (2 !== count($message)) {
42 2
            throw new Exception('Unable to unpack data.');
43
        }
44
45 104
        list($header, $body) = $message;
46
47 104
        $code = $header[IProto::CODE];
48
49 104
        if ($code >= Request::TYPE_ERROR) {
50 24
            throw new Exception($body[IProto::ERROR], $code & (Request::TYPE_ERROR - 1));
51
        }
52
53 83
        return new Response($header[IProto::SYNC], $body ? $body[IProto::DATA] : null);
54
    }
55
}
56