forked from tarantool-php/client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPurePacker.php
61 lines (51 loc) · 1.74 KB
/
PurePacker.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<?php
/**
* This file is part of the Tarantool Client package.
*
* (c) Eugene Leonovich <gen.work@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Tarantool\Client\Packer;
use MessagePack\BufferUnpacker;
use MessagePack\Exception\UnpackingFailedException;
use MessagePack\Packer;
use Tarantool\Client\Exception\UnpackingFailed;
use Tarantool\Client\Keys;
use Tarantool\Client\Packer\Packer as ClientPacker;
use Tarantool\Client\Request\Request;
use Tarantool\Client\Response;
final class PurePacker implements ClientPacker
{
private $packer;
private $unpacker;
public function __construct(?Packer $packer = null, ?BufferUnpacker $unpacker = null)
{
$this->packer = $packer ?: new Packer();
$this->unpacker = $unpacker ?: new BufferUnpacker();
}
public function pack(Request $request, ?int $sync = null) : string
{
$content = $this->packer->packMapHeader(2).
$this->packer->packInt(Keys::CODE).
$this->packer->packInt($request->getType()).
$this->packer->packInt(Keys::SYNC).
$this->packer->packInt($sync ?: 0).
$this->packer->packMap($request->getBody());
return PacketLength::pack(\strlen($content)).$content;
}
public function unpack(string $data) : Response
{
try {
$this->unpacker->reset($data);
return new Response(
$this->unpacker->unpackMap(),
$this->unpacker->unpackMap()
);
} catch (UnpackingFailedException $e) {
throw new UnpackingFailed('Unable to unpack response.', 0, $e);
}
}
}