Completed
Push — master ( bdeb81...7f157d )
by Eugene
06:32
created

PeclPacker::pack()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 2
dl 0
loc 9
rs 9.9666
c 0
b 0
f 0
ccs 5
cts 5
cp 1
crap 1
1
<?php
2
3
/**
4
 * This file is part of the Tarantool Client package.
5
 *
6
 * (c) Eugene Leonovich <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace Tarantool\Client\Packer;
15
16
use Tarantool\Client\Keys;
17
use Tarantool\Client\Request\Request;
18
use Tarantool\Client\Response;
19
20
final class PeclPacker implements Packer
21
{
22
    /** @var \MessagePack */
23
    private $packer;
24
25
    /** @var \MessagePackUnpacker */
26
    private $unpacker;
27
28 172
    public function __construct(bool $phpOnly = true)
29
    {
30 172
        $this->packer = new \MessagePack($phpOnly);
31 172
        $this->unpacker = new \MessagePackUnpacker($phpOnly);
32 172
    }
33
34 133
    public function pack(Request $request, int $sync) : string
35
    {
36
        // @see https://github.com/msgpack/msgpack-php/issues/45
37 133
        $packet = \pack('C*', 0x82, Keys::CODE, $request->getType(), Keys::SYNC).
38 133
            $this->packer->pack($sync).
39 133
            $this->packer->pack($request->getBody());
40
41 133
        return PacketLength::pack(\strlen($packet)).$packet;
42
    }
43
44 124
    public function unpack(string $packet) : Response
45
    {
46 124
        $this->unpacker->feed($packet);
47
48 124
        if (!$this->unpacker->execute()) {
49 6
            throw new \RuntimeException('Unable to unpack response header');
50
        }
51 118
        $header = $this->unpacker->data();
52
53 118
        if (!$this->unpacker->execute()) {
54 3
            throw new \RuntimeException('Unable to unpack response body');
55
        }
56 115
        $body = $this->unpacker->data();
57
58
        // with PHP_ONLY = true an empty array
59
        // will be unpacked to stdClass
60 115
        if ($body instanceof \stdClass) {
61 20
            $body = (array) $body;
62
        }
63
64 115
        return new Response($header, $body);
65
    }
66
}
67