Completed
Pull Request — master (#37)
by Eugene
05:31
created

PeclPacker::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1.008

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 4
cts 5
cp 0.8
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1.008
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 PeclPacker implements Packer
22
{
23
    private $packer;
24
    private $unpacker;
25
26 28
    public function __construct(bool $phpOnly = true)
27
    {
28 28
        $this->packer = new \MessagePack($phpOnly);
29 28
        $this->unpacker = new \MessagePackUnpacker($phpOnly);
30 28
    }
31
32 3
    public function pack(Request $request, ?int $sync = null) : string
33
    {
34
        // @see https://github.com/msgpack/msgpack-php/issues/45
35 3
        $content = \pack('C*', 0x82, IProto::CODE, $request->getType(), IProto::SYNC).
36 3
            $this->packer->pack($sync ?: 0).
37 3
            $this->packer->pack($request->getBody());
38
39 3
        return PackUtils::packLength(\strlen($content)).$content;
40
    }
41
42 2
    public function unpack(string $data) : Response
43
    {
44 2
        $this->unpacker->feed($data);
45
46 2
        if (!$this->unpacker->execute()) {
47
            throw UnpackingFailed::invalidResponse();
48
        }
49
50 2
        $header = $this->unpacker->data();
51 2
        if (!\is_array($header)) {
52 2
            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
            return new Response($header, $body);
62
        }
63
        if ($body instanceof \stdClass) {
64
            return new Response($header, (array) $body);
65
        }
66
67
        throw UnpackingFailed::invalidResponse();
68
    }
69
}
70