Completed
Push — master ( 29a805...bdeb81 )
by Eugene
06:00
created

DefaultHandler::getPacker()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 4
ccs 0
cts 4
cp 0
crap 2
rs 10
c 0
b 0
f 0
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\Handler;
15
16
use Tarantool\Client\Connection\Connection;
17
use Tarantool\Client\Exception\RequestFailed;
18
use Tarantool\Client\Exception\UnexpectedResponse;
19
use Tarantool\Client\Packer\Packer;
20
use Tarantool\Client\Request\Request;
21
use Tarantool\Client\Response;
22
23
final class DefaultHandler implements Handler
24
{
25
    private $connection;
26
    private $packer;
27
28
    public function __construct(Connection $connection, Packer $packer)
29
    {
30
        $this->connection = $connection;
31
        $this->packer = $packer;
32
    }
33
34
    public function handle(Request $request) : Response
35
    {
36
        $packet = $this->packer->pack($request, $sync = \mt_rand());
37
        $this->connection->open();
38
        $packet = $this->connection->send($packet);
39
40
        $response = $this->packer->unpack($packet);
41
42
        if ($sync !== $response->getSync()) {
43
            $this->connection->close();
44
            throw UnexpectedResponse::outOfSync($sync, $response->getSync());
45
        }
46
47
        if ($response->isError()) {
48
            throw RequestFailed::fromErrorResponse($response);
49
        }
50
51
        return $response;
52
    }
53
54
    public function getConnection() : Connection
55
    {
56
        return $this->connection;
57
    }
58
59
    public function getPacker() : Packer
60
    {
61
        return $this->packer;
62
    }
63
}
64