Completed
Pull Request — master (#37)
by Eugene
11:44 queued 01:46
created

Client::sendRequest()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 11
ccs 6
cts 6
cp 1
rs 9.9
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Tarantool Client package.
7
 *
8
 * (c) Eugene Leonovich <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Tarantool\Client;
15
16
use Tarantool\Client\Connection\StreamConnection;
17
use Tarantool\Client\Exception\RequestFailed;
18
use Tarantool\Client\Handler\DefaultHandler;
19
use Tarantool\Client\Handler\Handler;
20
use Tarantool\Client\Handler\MiddlewareHandler;
21
use Tarantool\Client\Middleware\AuthMiddleware;
22
use Tarantool\Client\Middleware\Middleware;
23
use Tarantool\Client\Middleware\RetryMiddleware;
24
use Tarantool\Client\Packer\PurePacker;
25
use Tarantool\Client\Request\Call;
26
use Tarantool\Client\Request\Evaluate;
27
use Tarantool\Client\Request\Execute;
28
use Tarantool\Client\Request\Ping;
29 55
use Tarantool\Client\Schema\Criteria;
30
use Tarantool\Client\Schema\Index;
31 55
use Tarantool\Client\Schema\Space;
32 55
33 55
final class Client
34
{
35 3
    private $handler;
36
    private $spaces = [];
37 3
38
    public function __construct(Handler $handler)
39
    {
40 2
        $this->handler = $handler;
41
    }
42 2
43
    public static function fromDefaults() : self
44
    {
45 54
        return new self(new DefaultHandler(
46
            StreamConnection::createTcp(),
47 54
            new PurePacker()
48
        ));
49 33
    }
50 2
51
    public static function fromOptions(array $options) : self
52 33
    {
53
        $connectionOptions = [];
54 51
        if (isset($options['connect_timeout'])) {
55
            $connectionOptions['connect_timeout'] = $options['connect_timeout'];
56 51
        }
57 51
        if (isset($options['socket_timeout'])) {
58 51
            $connectionOptions['socket_timeout'] = $options['socket_timeout'];
59
        }
60 14
        if (isset($options['tcp_nodelay'])) {
61
            $connectionOptions['tcp_nodelay'] = $options['tcp_nodelay'];
62 14
        }
63
64
        $connection = StreamConnection::create($options['uri'] ?? StreamConnection::DEFAULT_URI, $connectionOptions);
65 14
        $handler = new DefaultHandler($connection, new PurePacker());
66
67 14
        if (isset($options['username'])) {
68 12
            $handler = MiddlewareHandler::create($handler, new AuthMiddleware($options['username'], $options['password'] ?? ''));
69
        }
70
        if (isset($options['max_retries']) && 0 !== $options['max_retries']) {
71 14
            $handler = MiddlewareHandler::create($handler, RetryMiddleware::linear($options['max_retries']));
72 14
        }
73
74 10
        return new self($handler);
75 10
    }
76
77 10
    public static function fromDsn(string $dsn) : self
78
    {
79 10
        $dsn = Dsn::parse($dsn);
80
81
        $connectionOptions = [];
82 10
        if (null !== $timeout = $dsn->getInt('connect_timeout')) {
83
            $connectionOptions['connect_timeout'] = $timeout;
84 10
        }
85
        if (null !== $timeout = $dsn->getInt('socket_timeout')) {
86 10
            $connectionOptions['socket_timeout'] = $timeout;
87
        }
88
        if (null !== $tcpNoDelay = $dsn->getBool('socket_timeout')) {
89
            $connectionOptions['tcp_nodelay'] = $tcpNoDelay;
90
        }
91
92
        $connection = $dsn->isTcp()
93
            ? StreamConnection::createTcp($dsn->getConnectionUri(), $connectionOptions)
94 64
            : StreamConnection::createUds($dsn->getConnectionUri(), $connectionOptions);
95
96 64
        $handler = new DefaultHandler($connection, new PurePacker());
97 58
98
        if ($username = $dsn->getUsername()) {
99
            $handler = MiddlewareHandler::create($handler, new AuthMiddleware($username, $dsn->getPassword() ?? ''));
100 16
        }
101 10
        if ($maxRetries = $dsn->getInt('max_retries')) {
102
            $handler = MiddlewareHandler::create($handler, RetryMiddleware::linear($maxRetries));
103
        }
104 14
105
        return new self($handler);
106 12
    }
107
108
    public function withMiddleware(Middleware $middleware, Middleware ...$middlewares) : self
109 8
    {
110
        $new = clone $this;
111 8
        $new->handler = MiddlewareHandler::create($new->handler, $middleware, ...$middlewares);
112
113 8
        return $new;
114
    }
115
116 26
    public function getHandler() : Handler
117
    {
118 26
        return $this->handler;
119
    }
120 26
121
    public function ping() : void
122
    {
123 12
        $this->handler->handle(new Ping());
124
    }
125 12
126 12
    public function getSpace(string $spaceName) : Space
127
    {
128 115
        if (isset($this->spaces[$spaceName])) {
129
            return $this->spaces[$spaceName];
130 115
        }
131 30
132
        $spaceId = $this->getSpaceIdByName($spaceName);
133
134 113
        return $this->spaces[$spaceName] = $this->spaces[$spaceId] = new Space($this->handler, $spaceId);
135 113
    }
136
137 109
    public function getSpaceById(int $spaceId) : Space
138
    {
139
        if (isset($this->spaces[$spaceId])) {
140 14
            return $this->spaces[$spaceId];
141
        }
142 14
143 14
        return $this->spaces[$spaceId] = new Space($this->handler, $spaceId);
144 14
    }
145
146 14
    public function call(string $funcName, ...$args) : array
147 3
    {
148
        $request = new Call($funcName, $args);
149
150 12
        return $this->handler->handle($request)->getBodyField(IProto::DATA);
151
    }
152
153
    public function executeQuery(string $sql, ...$params) : SqlQueryResult
154
    {
155
        $request = new Execute($sql, $params);
156
        $response = $this->handler->handle($request);
157
158
        return new SqlQueryResult(
159
            $response->getBodyField(IProto::DATA),
160
            $response->getBodyField(IProto::METADATA)
161
        );
162
    }
163
164
    public function executeUpdate(string $sql, ...$params) : SqlUpdateResult
165
    {
166
        $request = new Execute($sql, $params);
167
168
        return new SqlUpdateResult(
169
            $this->handler->handle($request)->getBodyField(IProto::SQL_INFO)
170
        );
171
    }
172
173
    public function evaluate(string $expr, ...$args) : array
174
    {
175
        $request = new Evaluate($expr, $args);
176
177
        return $this->handler->handle($request)->getBodyField(IProto::DATA);
178
    }
179
180
    public function flushSpaces() : void
181
    {
182
        $this->spaces = [];
183
    }
184
185
    private function getSpaceIdByName(string $spaceName) : int
186
    {
187
        $schema = $this->getSpaceById(Space::VSPACE_ID);
188
        $data = $schema->select(Criteria::key([$spaceName])->andIndex(Index::SPACE_NAME));
189
190
        if ([] === $data) {
191
            throw RequestFailed::unknownSpace($spaceName);
192
        }
193
194
        return $data[0][0];
195
    }
196
}
197