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

Pecl::pack()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 9
ccs 0
cts 7
cp 0
rs 9.9666
c 0
b 0
f 0
cc 2
nc 1
nop 2
crap 6
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 Tarantool\Client\Exception\UnpackingFailed;
17
use Tarantool\Client\IProto;
18
use Tarantool\Client\Request\Request;
19
use Tarantool\Client\Response;
20
21
final class Pecl implements Packer
22
{
23
    private $packer;
24
    private $unpacker;
25
26
    public function __construct($phpOnly = true)
27
    {
28
        $this->packer = new \MessagePack($phpOnly);
29
        $this->unpacker = new \MessagePackUnpacker($phpOnly);
30
    }
31
32
    public function pack(Request $request, int $sync = null) : string
33
    {
34
        // @see https://github.com/msgpack/msgpack-php/issues/45
35
        $content = \pack('C*', 0x82, IProto::CODE, $request->getType(), IProto::SYNC).
36
            $this->packer->pack($sync ?: 0).
37
            $this->packer->pack($request->getBody());
38
39
        return PackUtils::packLength(\strlen($content)).$content;
40
    }
41
42
    public function unpack(string $data) : Response
43
    {
44
        $this->unpacker->feed($data);
45
46
        if (!$this->unpacker->execute()) {
47
            throw UnpackingFailed::invalidResponse();
48
        }
49
50
        $header = $this->unpacker->data();
51
        if (!\is_array($header)) {
52
            throw UnpackingFailed::invalidResponse();
53
        }
54
55
        if (!$this->unpacker->execute()) {
56
            throw UnpackingFailed::invalidResponse();
57
        }
58
59
        $body = $this->unpacker->data();
60
        if (!\is_array($body)) {
61
            throw UnpackingFailed::invalidResponse();
62
        }
63
64
        return new Response($header, $body);
65
    }
66
}
67