Completed
Pull Request — master (#37)
by Eugene
06:07
created

Pure::__construct()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 4
cts 4
cp 1
rs 10
c 0
b 0
f 0
cc 3
nc 4
nop 2
crap 3
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Tarantool Client package.
7
 *
8
 * (c) Eugene Leonovich <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Tarantool\Client\Packer;
15
16
use MessagePack\BufferUnpacker;
17
use MessagePack\Exception\UnpackingFailedException as PureUnpackingFailedException;
18
use MessagePack\Packer as MsgPacker;
19
use Tarantool\Client\Exception\UnpackingFailed;
20
use Tarantool\Client\IProto;
21
use Tarantool\Client\Request\Request;
22
use Tarantool\Client\Response;
23
24
final class Pure implements Packer
25
{
26
    private $packer;
27
    private $unpacker;
28
29 130
    public function __construct(MsgPacker $packer = null, BufferUnpacker $unpacker = null)
30
    {
31 130
        $this->packer = $packer ?: new MsgPacker();
32 130
        $this->unpacker = $unpacker ?: new BufferUnpacker();
33 130
    }
34
35 106
    public function pack(Request $request, int $sync = null) : string
36
    {
37 106
        $content = $this->packer->packMapHeader(2).
38 106
            $this->packer->packInt(IProto::CODE).
39 106
            $this->packer->packInt($request->getType()).
40 106
            $this->packer->packInt(IProto::SYNC).
41 106
            $this->packer->packInt($sync ?: 0).
42 106
            $this->packer->packMap($request->getBody());
43
44 106
        return PackUtils::packLength(\strlen($content)).$content;
45
    }
46
47 105
    public function unpack(string $data) : Response
48
    {
49
        try {
50 105
            $this->unpacker->reset($data);
51
52 105
            return new Response(
53 105
                $this->unpacker->unpackMap(),
54 103
                $this->unpacker->unpackMap()
55
            );
56 2
        } catch (PureUnpackingFailedException $e) {
57 2
            throw new UnpackingFailed('Unable to unpack response.', 0, $e);
58
        }
59
    }
60
}
61