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
|
|
|
|