1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Tarantool\Client\Packer; |
4
|
|
|
|
5
|
|
|
use Tarantool\Client\Exception\Exception; |
6
|
|
|
use Tarantool\Client\IProto; |
7
|
|
|
use Tarantool\Client\Request\Request; |
8
|
|
|
use Tarantool\Client\Response; |
9
|
|
|
|
10
|
|
|
class PeclLitePacker implements Packer |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* {@inheritdoc} |
14
|
|
|
*/ |
15
|
|
|
public function pack(Request $request, $sync = null) |
16
|
|
|
{ |
17
|
|
|
// @see https://github.com/msgpack/msgpack-php/issues/45 |
18
|
|
|
$content = pack('C*', 0x82, IProto::CODE, $request->getType(), IProto::SYNC); |
19
|
|
|
$content .= msgpack_pack((int) $sync); |
20
|
|
|
|
21
|
|
|
if (null !== $body = $request->getBody()) { |
22
|
|
|
$content .= msgpack_pack($body); |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
return PackUtils::packLength(strlen($content)).$content; |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* {@inheritdoc} |
30
|
|
|
*/ |
31
|
|
|
public function unpack($data) |
32
|
|
|
{ |
33
|
|
|
$headerSize = PackUtils::getHeaderSize($data); |
34
|
|
|
|
35
|
|
|
if (!$header = substr($data, 0, $headerSize)) { |
36
|
|
|
throw new Exception('Unable to unpack data.'); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
$header = msgpack_unpack($header); |
40
|
|
|
if (!is_array($header)) { |
41
|
|
|
throw new Exception('Unable to unpack data.'); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
$code = $header[IProto::CODE]; |
45
|
|
|
|
46
|
|
|
$body = substr($data, $headerSize); |
47
|
|
|
$body = msgpack_unpack($body); |
48
|
|
|
|
49
|
|
|
if ($code >= Request::TYPE_ERROR) { |
50
|
|
|
throw new Exception($body[IProto::ERROR], $code & (Request::TYPE_ERROR - 1)); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
return new Response($header[IProto::SYNC], $body ? $body[IProto::DATA] : null); |
54
|
|
|
} |
55
|
|
|
} |
56
|
|
|
|