1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Tarantool\Client\Packer; |
4
|
|
|
|
5
|
|
|
use MessagePack\BufferUnpacker; |
6
|
|
|
use MessagePack\Packer as MessagePackPacker; |
7
|
|
|
use Tarantool\Client\Exception\Exception; |
8
|
|
|
use Tarantool\Client\IProto; |
9
|
|
|
use Tarantool\Client\Request\Request; |
10
|
|
|
use Tarantool\Client\Response; |
11
|
|
|
|
12
|
|
|
class PurePacker implements Packer |
13
|
|
|
{ |
14
|
|
|
private $packer; |
15
|
|
|
private $unpacker; |
16
|
|
|
|
17
|
58 |
|
public function __construct() |
18
|
|
|
{ |
19
|
58 |
|
$this->packer = new MessagePackPacker(); |
20
|
58 |
|
$this->unpacker = new BufferUnpacker(); |
21
|
58 |
|
} |
22
|
|
|
|
23
|
108 |
|
public function pack(Request $request, $sync = null) |
24
|
|
|
{ |
25
|
108 |
|
$content = $this->packer->packMap([ |
26
|
108 |
|
IProto::CODE => $request->getType(), |
27
|
108 |
|
IProto::SYNC => (int) $sync, |
28
|
|
|
]); |
29
|
|
|
|
30
|
108 |
|
if (null !== $body = $request->getBody()) { |
31
|
99 |
|
$content .= $this->packer->packMap($body); |
32
|
|
|
} |
33
|
|
|
|
34
|
108 |
|
return PackUtils::packLength(strlen($content)).$content; |
35
|
|
|
} |
36
|
|
|
|
37
|
106 |
|
public function unpack($data) |
38
|
|
|
{ |
39
|
106 |
|
$message = $this->unpacker->reset($data)->tryUnpack(); |
40
|
|
|
|
41
|
106 |
|
if (2 !== count($message)) { |
42
|
2 |
|
throw new Exception('Unable to unpack data.'); |
43
|
|
|
} |
44
|
|
|
|
45
|
104 |
|
list($header, $body) = $message; |
46
|
|
|
|
47
|
104 |
|
$code = $header[IProto::CODE]; |
48
|
|
|
|
49
|
104 |
|
if ($code >= Request::TYPE_ERROR) { |
50
|
24 |
|
throw new Exception($body[IProto::ERROR], $code & (Request::TYPE_ERROR - 1)); |
51
|
|
|
} |
52
|
|
|
|
53
|
83 |
|
return new Response($header[IProto::SYNC], $body ? $body[IProto::DATA] : null); |
54
|
|
|
} |
55
|
|
|
} |
56
|
|
|
|