Passed
Branch php71 (acb31d)
by Eugene
02:53
created

Client::executeUpdate()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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