Completed
Pull Request — master (#37)
by Eugene
02:41
created

Pure::pack()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 11
ccs 8
cts 8
cp 1
rs 9.9
c 0
b 0
f 0
cc 2
nc 1
nop 2
crap 2
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 128
    public function __construct(MsgPacker $packer = null, BufferUnpacker $unpacker = null)
30
    {
31 128
        $this->packer = $packer ?: new MsgPacker();
32 128
        $this->unpacker = $unpacker ?: new BufferUnpacker();
33 128
    }
34
35 104
    public function pack(Request $request, int $sync = null) : string
36
    {
37 104
        $content = $this->packer->packMapHeader(2).
38 104
            $this->packer->packInt(IProto::CODE).
39 104
            $this->packer->packInt($request->getType()).
40 104
            $this->packer->packInt(IProto::SYNC).
41 104
            $this->packer->packInt($sync ?: 0).
42 104
            $this->packer->packMap($request->getBody());
43
44 104
        return PackUtils::packLength(\strlen($content)).$content;
45
    }
46
47 103
    public function unpack(string $data) : Response
48
    {
49
        try {
50 103
            $this->unpacker->reset($data);
51
52 103
            return new Response(
53 103
                $this->unpacker->unpackMap(),
54 101
                $this->unpacker->unpackMap()
55
            );
56 2
        } catch (PureUnpackingFailedException $e) {
57 2
            throw new UnpackingFailed('Unable to unpack response.', 0, $e);
58
        }
59
    }
60
}
61