Passed
Pull Request — master (#37)
by Eugene
09:14
created

Client::fromDefaults()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 5
ccs 0
cts 4
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
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
use Tarantool\Client\Schema\Criteria;
30
use Tarantool\Client\Schema\Index;
31
use Tarantool\Client\Schema\Space;
32
33
final class Client
34
{
35
    private $handler;
36
    private $spaces = [];
37
38 232
    public function __construct(Handler $handler)
39
    {
40 232
        $this->handler = $handler;
41 232
    }
42
43
    public static function fromDefaults() : self
44
    {
45
        return new self(new DefaultHandler(
46
            StreamConnection::createTcp(),
47
            new PurePacker()
48
        ));
49
    }
50
51
    public static function fromOptions(array $options) : self
52
    {
53
        $connectionOptions = [];
54
        if (isset($options['connect_timeout'])) {
55
            $connectionOptions['connect_timeout'] = $options['connect_timeout'];
56
        }
57
        if (isset($options['socket_timeout'])) {
58
            $connectionOptions['socket_timeout'] = $options['socket_timeout'];
59
        }
60
        if (isset($options['tcp_nodelay'])) {
61
            $connectionOptions['tcp_nodelay'] = $options['tcp_nodelay'];
62
        }
63
64
        $connection = StreamConnection::create($options['uri'] ?? StreamConnection::DEFAULT_URI, $connectionOptions);
65
        $handler = new DefaultHandler($connection, new PurePacker());
66
67
        if (isset($options['username'])) {
68
            $handler = new MiddlewareHandler(
69
                new AuthMiddleware($options['username'], $options['password'] ?? ''),
70
                $handler
71
            );
72
        }
73
        if (isset($options['max_retries']) && 0 !== $options['max_retries']) {
74
            $handler = new MiddlewareHandler(
75
                RetryMiddleware::linear($options['max_retries']),
76
                $handler
77
            );
78
        }
79
80
        return new self($handler);
81
    }
82
83
    public static function fromDsn(string $dsn) : self
84
    {
85
        $dsn = Dsn::parse($dsn);
86
87
        $connectionOptions = [];
88
        if (null !== $timeout = $dsn->getInt('connect_timeout')) {
89
            $connectionOptions['connect_timeout'] = $timeout;
90
        }
91
        if (null !== $timeout = $dsn->getInt('socket_timeout')) {
92
            $connectionOptions['socket_timeout'] = $timeout;
93
        }
94
        if (null !== $tcpNoDelay = $dsn->getBool('socket_timeout')) {
95
            $connectionOptions['tcp_nodelay'] = $tcpNoDelay;
96
        }
97
98
        $connection = $dsn->isTcp()
99
            ? StreamConnection::createTcp($dsn->getConnectionUri(), $connectionOptions)
100
            : StreamConnection::createUds($dsn->getConnectionUri(), $connectionOptions);
101
102
        $handler = new DefaultHandler($connection, new PurePacker());
103
104
        if ($username = $dsn->getUsername()) {
105
            $handler = new MiddlewareHandler(
106
                new AuthMiddleware($username, $dsn->getPassword() ?? ''),
107
                $handler
108
            );
109
        }
110
        if ($maxRetries = $dsn->getInt('max_retries')) {
111
            $handler = new MiddlewareHandler(
112
                RetryMiddleware::linear($maxRetries),
113
                $handler
114
            );
115
        }
116
117
        return new self($handler);
118
    }
119
120
    public function withMiddleware(Middleware $middleware, Middleware ...$middlewares) : self
121
    {
122
        $new = clone $this;
123
        $new->handler = new MiddlewareHandler($middleware, $this->handler);
124
125
        if ($middlewares) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $middlewares of type array<integer,Tarantool\...\Middleware\Middleware> 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...
126
            $new->handler = MiddlewareHandler::create($new->handler, $middlewares);
127
        }
128
129
        return $new;
130
    }
131
132 12
    public function getHandler() : Handler
133
    {
134 12
        return $this->handler;
135
    }
136
137 54
    public function ping() : void
138
    {
139 54
        $this->handler->handle(new Ping());
140 4
    }
141
142 106
    public function getSpace(string $spaceName) : Space
143
    {
144 106
        if (isset($this->spaces[$spaceName])) {
145 2
            return $this->spaces[$spaceName];
146
        }
147
148 106
        $spaceId = $this->getSpaceIdByName($spaceName);
149
150 102
        return $this->spaces[$spaceName] = $this->spaces[$spaceId] = new Space($this->handler, $spaceId);
151
    }
152
153 112
    public function getSpaceById(int $spaceId) : Space
154
    {
155 112
        if (isset($this->spaces[$spaceId])) {
156
            return $this->spaces[$spaceId];
157
        }
158
159 112
        return $this->spaces[$spaceId] = new Space($this->handler, $spaceId);
160
    }
161
162 4
    public function call(string $funcName, ...$args) : array
163
    {
164 4
        $request = new Call($funcName, $args);
165
166 4
        return $this->handler->handle($request)->getBodyField(IProto::DATA);
167
    }
168
169 8
    public function executeQuery(string $sql, ...$params) : SqlQueryResult
170
    {
171 8
        $request = new Execute($sql, $params);
172 8
        $response = $this->handler->handle($request);
173
174 8
        return new SqlQueryResult(
175 8
            $response->getBodyField(IProto::DATA),
176 8
            $response->getBodyField(IProto::METADATA)
177
        );
178
    }
179
180 10
    public function executeUpdate(string $sql, ...$params) : SqlUpdateResult
181
    {
182 10
        $request = new Execute($sql, $params);
183
184 10
        return new SqlUpdateResult(
185 10
            $this->handler->handle($request)->getBodyField(IProto::SQL_INFO)
186
        );
187
    }
188
189 46
    public function evaluate(string $expr, ...$args) : array
190
    {
191 46
        $request = new Evaluate($expr, $args);
192
193 46
        return $this->handler->handle($request)->getBodyField(IProto::DATA);
194
    }
195
196 4
    public function flushSpaces() : void
197
    {
198 4
        $this->spaces = [];
199 4
    }
200
201 106
    private function getSpaceIdByName(string $spaceName) : int
202
    {
203 106
        $schema = $this->getSpaceById(Space::VSPACE_ID);
204 106
        $data = $schema->select(Criteria::key([$spaceName])->andIndex(Index::SPACE_NAME));
205
206 106
        if ([] === $data) {
207 4
            throw RequestFailed::unknownSpace($spaceName);
208
        }
209
210 102
        return $data[0][0];
211
    }
212
}
213