Passed
Pull Request — master (#73)
by Eugene
11:48 queued 01:44
created

Client::fromDefaults()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 0
dl 0
loc 5
rs 10
c 0
b 0
f 0
ccs 4
cts 4
cp 1
crap 1
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;
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\AuthenticationMiddleware;
22
use Tarantool\Client\Middleware\Middleware;
23
use Tarantool\Client\Middleware\RetryMiddleware;
24
use Tarantool\Client\Packer\Packer;
25
use Tarantool\Client\Packer\PackerFactory;
26
use Tarantool\Client\Request\CallRequest;
27
use Tarantool\Client\Request\EvaluateRequest;
28
use Tarantool\Client\Request\ExecuteRequest;
29
use Tarantool\Client\Request\PingRequest;
30
use Tarantool\Client\Request\PrepareRequest;
31
use Tarantool\Client\Schema\Criteria;
32
use Tarantool\Client\Schema\Space;
33
34
final class Client
35
{
36
    /** @var Handler */
37
    private $handler;
38
39
    /** @var array<array-key, Space> */
0 ignored issues
show
Documentation Bug introduced by
The doc comment array<array-key, Space> at position 2 could not be parsed: Unknown type name 'array-key' at position 2 in array<array-key, Space>.
Loading history...
40
    private $spaces = [];
41
42 577
    public function __construct(Handler $handler)
43
    {
44 577
        $this->handler = $handler;
45 577
    }
46
47 3
    public static function fromDefaults() : self
48
    {
49 3
        return new self(new DefaultHandler(
50 3
            StreamConnection::createTcp(),
51 3
            PackerFactory::create()
52
        ));
53
    }
54
55 9
    public static function fromOptions(array $options, ?Packer $packer = null) : self
56
    {
57 9
        $connectionOptions = [];
58 9
        if (isset($options['connect_timeout'])) {
59
            $connectionOptions['connect_timeout'] = $options['connect_timeout'];
60
        }
61 9
        if (isset($options['socket_timeout'])) {
62
            $connectionOptions['socket_timeout'] = $options['socket_timeout'];
63
        }
64 9
        if (isset($options['tcp_nodelay'])) {
65
            $connectionOptions['tcp_nodelay'] = $options['tcp_nodelay'];
66
        }
67 9
        if (isset($options['persistent'])) {
68
            $connectionOptions['persistent'] = $options['persistent'];
69
        }
70
71 9
        $middleware = [];
72 9
        if (isset($options['max_retries']) && 0 !== $options['max_retries']) {
73 3
            $middleware[] = RetryMiddleware::linear($options['max_retries']);
74
        }
75 9
        if (isset($options['username'])) {
76 3
            $middleware[] = new AuthenticationMiddleware($options['username'], $options['password'] ?? '');
77
        }
78
79 9
        $connection = isset($options['uri'])
80 9
            ? StreamConnection::create($options['uri'], $connectionOptions)
81
            : StreamConnection::createTcp(StreamConnection::DEFAULT_TCP_URI, $connectionOptions);
82 9
83 3
        $handler = new DefaultHandler($connection, $packer ?? PackerFactory::create());
84 9
85
        return $middleware
86
            ? new self(MiddlewareHandler::create($handler, $middleware))
87 6
            : new self($handler);
88
    }
89 6
90
    public static function fromDsn(string $dsn, ?Packer $packer = null) : self
91 6
    {
92 6
        $dsn = Dsn::parse($dsn);
93
94
        $connectionOptions = [];
95 6
        if (null !== $timeout = $dsn->getFloat('connect_timeout')) {
96
            $connectionOptions['connect_timeout'] = $timeout;
97
        }
98 6
        if (null !== $timeout = $dsn->getFloat('socket_timeout')) {
99
            $connectionOptions['socket_timeout'] = $timeout;
100
        }
101 6
        if (null !== $tcpNoDelay = $dsn->getBool('tcp_nodelay')) {
102
            $connectionOptions['tcp_nodelay'] = $tcpNoDelay;
103
        }
104
        if (null !== $persistent = $dsn->getBool('persistent')) {
105 6
            $connectionOptions['persistent'] = $persistent;
106 6
        }
107
108
        $middleware = [];
109 6
        if ($maxRetries = $dsn->getInt('max_retries')) {
110
            $middleware[] = RetryMiddleware::linear($maxRetries);
111
        }
112
        if ($username = $dsn->getUsername()) {
113 6
            $middleware[] = new AuthenticationMiddleware($username, $dsn->getPassword() ?? '');
114 6
        }
115 6
116
        $connection = $dsn->isTcp()
117 6
            ? StreamConnection::createTcp($dsn->getConnectionUri(), $connectionOptions)
118
            : StreamConnection::createUds($dsn->getConnectionUri(), $connectionOptions);
119 6
120
        $handler = new DefaultHandler($connection, $packer ?? PackerFactory::create());
121 6
122
        return $middleware
123
            ? new self(MiddlewareHandler::create($handler, $middleware))
124 27
            : new self($handler);
125
    }
126 27
127 27
    public function withMiddleware(Middleware ...$middleware) : self
128
    {
129 27
        $new = clone $this;
130
        $new->handler = MiddlewareHandler::create($new->handler, $middleware);
131
132 3
        return $new;
133
    }
134 3
135 3
    public function withPrependedMiddleware(Middleware ...$middleware) : self
136
    {
137 3
        $new = clone $this;
138
        $new->handler = MiddlewareHandler::create($new->handler, $middleware, true);
139
140 96
        return $new;
141
    }
142 96
143
    public function getHandler() : Handler
144
    {
145 176
        return $this->handler;
146
    }
147 176
148 3
    public function getSpace(string $spaceName) : Space
149
    {
150
        if (isset($this->spaces[$spaceName])) {
151 176
            return $this->spaces[$spaceName];
152
        }
153 170
154
        $spaceId = $this->getSpaceIdByName($spaceName);
155
156 188
        return $this->spaces[$spaceName] = $this->spaces[$spaceId] = new Space($this->handler, $spaceId);
157
    }
158 188
159
    public function getSpaceById(int $spaceId) : Space
160
    {
161
        if (isset($this->spaces[$spaceId])) {
162 188
            return $this->spaces[$spaceId];
163
        }
164
165 102
        return $this->spaces[$spaceId] = new Space($this->handler, $spaceId);
166
    }
167 102
168 22
    public function ping() : void
169
    {
170
        $this->handler->handle(new PingRequest());
171
    }
172
173 30
    /**
174
     * @param mixed ...$args
175 30
     */
176 30
    public function call(string $funcName, ...$args) : array
177
    {
178
        return $this->handler->handle(new CallRequest($funcName, $args))
179
            ->getBodyField(Keys::DATA);
180
    }
181
182 262
    /**
183
     * @param mixed ...$args
184 262
     */
185 247
    public function evaluate(string $expr, ...$args) : array
186
    {
187
        return $this->handler->handle(new EvaluateRequest($expr, $args))
188
            ->getBodyField(Keys::DATA);
189
    }
190
191 9
    /**
192
     * @param mixed ...$params
193 9
     */
194
    public function execute(string $sql, ...$params) : Response
195
    {
196
        return $this->handler->handle(ExecuteRequest::fromSql($sql, $params));
197
    }
198
199 30
    /**
200
     * @param mixed ...$params
201 30
     */
202
    public function executeQuery(string $sql, ...$params) : SqlQueryResult
203 30
    {
204 30
        $response = $this->handler->handle(ExecuteRequest::fromSql($sql, $params));
205 30
206
        return new SqlQueryResult(
207
            $response->getBodyField(Keys::DATA),
208
            $response->getBodyField(Keys::METADATA)
209
        );
210
    }
211
212 18
    /**
213
     * @param mixed ...$params
214 18
     */
215
    public function executeUpdate(string $sql, ...$params) : SqlUpdateResult
216 18
    {
217
        $response = $this->handler->handle(ExecuteRequest::fromSql($sql, $params));
218
219 15
        return new SqlUpdateResult($response->getBodyField(Keys::SQL_INFO));
220
    }
221 15
222
    public function prepare(string $sql) : PreparedStatement
223 15
    {
224 15
        $response = $this->handler->handle(PrepareRequest::fromSql($sql));
225 15
226 15
        return new PreparedStatement(
227 15
            $this->handler,
228 15
            $response->getBodyField(Keys::STMT_ID),
229
            $response->getBodyField(Keys::BIND_COUNT),
230
            $response->getBodyField(Keys::BIND_METADATA),
231
            $response->tryGetBodyField(Keys::METADATA, [])
232 6
        );
233
    }
234 6
235 6
    public function flushSpaces() : void
236
    {
237 30
        $this->spaces = [];
238
    }
239 30
240 30
    public function __clone()
241
    {
242 176
        $this->spaces = [];
243
    }
244 176
245 176
    private function getSpaceIdByName(string $spaceName) : int
246
    {
247 176
        $schema = $this->getSpaceById(Space::VSPACE_ID);
248 170
        $data = $schema->select(Criteria::key([$spaceName])->andIndex(Space::VSPACE_NAME_INDEX));
249
250
        if ($data) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $data of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
251 6
            return $data[0][0];
252
        }
253
254
        throw RequestFailed::unknownSpace($spaceName);
255
    }
256
}
257