Passed
Push — master ( e545e6...b1604d )
by
unknown
02:35 queued 12s
created

Client::initConnections()   C

Complexity

Conditions 12
Paths 52

Size

Total Lines 44
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 12
eloc 32
c 1
b 0
f 0
nc 52
nop 0
dl 0
loc 44
rs 6.9666

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Manticoresearch;
6
7
use Manticoresearch\Connection\ConnectionPool;
8
use Manticoresearch\Connection\Strategy\SelectorInterface;
9
use Manticoresearch\Connection\Strategy\StaticRoundRobin;
10
11
use Manticoresearch\Endpoints\Pq;
12
use Manticoresearch\Exceptions\ConnectionException;
13
use Manticoresearch\Exceptions\NoMoreNodesException;
14
use Manticoresearch\Exceptions\RuntimeException;
15
use Psr\Log\LoggerInterface;
16
use Psr\Log\NullLogger;
17
18
/**
19
 * Manticore  client object
20
 * @package Manticoresearch
21
 * @category Manticoresearch
22
 * @author Adrian Nuta <[email protected]>
23
 * @link https://manticoresearch.com
24
 */
25
class Client
26
{
27
    /**
28
     *
29
     */
30
    const VERSION = '1.0.0';
31
32
    /**
33
     * @var array
34
     */
35
    protected $config = [];
36
    /**
37
     * @var string
38
     */
39
    private $connectionStrategy = StaticRoundRobin::class;
40
    /**
41
     * @var ConnectionPool
42
     */
43
    protected $connectionPool;
44
45
    /**
46
     * @var LoggerInterface|NullLogger
47
     */
48
    protected $logger;
49
50
    protected $lastResponse;
51
52
    /*
53
     * $config can be a connection array or
54
     * $config['connections] = array of connections
55
     * $config['connectionStrategy'] = class name of pool strategy
56
     */
57
    public function __construct($config = [], LoggerInterface $logger = null)
58
    {
59
        $this->setConfig($config);
60
        $this->logger = $logger ?? new NullLogger();
61
        $this->initConnections();
62
    }
63
64
    protected function initConnections()
65
    {
66
        $connections = [];
67
        if (isset($this->config['connections'])) {
68
            foreach ($this->config['connections'] as $connection) {
69
                if (is_array($connection)) {
70
                    $connections[] = Connection::create($connection);
71
                } else {
72
                    $connections[] = $connection;
73
                }
74
            }
75
        }
76
77
        if (empty($connections)) {
78
            $connections[] = Connection::create($this->config);
79
        }
80
        if (isset($this->config['connectionStrategy'])) {
81
            if (is_string($this->config['connectionStrategy'])) {
82
                $strategyName = $this->config['connectionStrategy'];
83
                if (strncmp($strategyName, 'Manticoresearch\\', 16) === 0) {
84
                    $strategy = new $strategyName();
85
                } else {
86
                    $strategyFullName = '\\Manticoresearch\\Connection\\Strategy\\' . $strategyName;
87
                    if (class_exists($strategyFullName)) {
88
                        $strategy = new $strategyFullName();
89
                    } elseif (class_exists($strategyName)) {
90
                        $strategy = new $strategyName();
91
                    }
92
                }
93
            } elseif ($this->config['connectionStrategy'] instanceof SelectorInterface) {
94
                $strategy = $this->config['connectionStrategy'];
95
            } else {
96
                throw new RuntimeException('Cannot create a strategy based on provided settings!');
97
            }
98
        } else {
99
            $strategy = new $this->connectionStrategy;
100
        }
101
        if (!isset($this->config['retries'])) {
102
            $this->config['retries'] = count($connections);
103
        }
104
        $this->connectionPool = new Connection\ConnectionPool(
105
            $connections,
106
            $strategy ?? new $this->connectionStrategy,
107
            $this->config['retries']
108
        );
109
    }
110
111
    /**
112
     * @param string|array $hosts
113
     */
114
    public function setHosts($hosts)
115
    {
116
        $this->config['connections'] = $hosts;
117
        $this->initConnections();
118
    }
119
120
    /**
121
     * @param array $config
122
     * @return $this
123
     */
124
    public function setConfig(array $config): self
125
    {
126
        $this->config = array_merge($this->config, $config);
127
        return $this;
128
    }
129
130
    /**
131
     * @param array $config
132
     * @return Client
133
     */
134
    public static function create($config): Client
135
    {
136
        return self::createFromArray($config);
137
    }
138
139
    /**
140
     * @param array $config
141
     * @return Client
142
     */
143
    public static function createFromArray($config): Client
144
    {
145
        return new self($config);
146
    }
147
148
    /**
149
     * @return mixed
150
     */
151
    public function getConnections()
152
    {
153
        return $this->connectionPool->getConnections();
154
    }
155
156
    /**
157
     * @return ConnectionPool
158
     */
159
    public function getConnectionPool(): ConnectionPool
160
    {
161
        return $this->connectionPool;
162
    }
163
164
    /**
165
     * Endpoint: search
166
     * @param array $params
167
     * @param bool $obj
168
     * @return array|Response
169
     */
170
    public function search(array $params = [], $obj = false)
171
    {
172
        $endpoint = new Endpoints\Search($params);
173
        $response = $this->request($endpoint);
174
        if ($obj === true) {
175
            return $response;
176
        } else {
177
            return $response->getResponse();
178
        }
179
    }
180
181
    /**
182
     * Endpoint: insert
183
     * @param array $params
184
     * @return array
185
     */
186
    public function insert(array $params = [])
187
    {
188
        $endpoint = new Endpoints\Insert($params);
189
        $response = $this->request($endpoint);
190
191
        return $response->getResponse();
192
    }
193
194
    /**
195
     * Endpoint: replace
196
     * @param array $params
197
     * @return mixed
198
     */
199
    public function replace(array $params = [])
200
    {
201
        $endpoint = new Endpoints\Replace($params);
202
        $response = $this->request($endpoint);
203
204
        return $response->getResponse();
205
    }
206
207
    /**
208
     * Endpoint: update
209
     * @param array $params
210
     * @return array
211
     */
212
    public function update(array $params = [])
213
    {
214
        $endpoint = new Endpoints\Update($params);
215
        $response = $this->request($endpoint);
216
217
        return $response->getResponse();
218
    }
219
220
    /**
221
     * Endpoint: sql
222
     * @param array $params
223
     * @return array
224
     */
225
    public function sql(array $params = [])
226
    {
227
        $endpoint = new Endpoints\Sql($params);
228
        if (isset($params['mode'])) {
229
            $endpoint->setMode($params['mode']);
230
            $response = $this->request($endpoint, ['responseClass' => 'Manticoresearch\\Response\\SqlToArray']);
231
        } else {
232
            $response = $this->request($endpoint);
233
        }
234
        return $response->getResponse();
235
    }
236
237
    /**
238
     * Endpoint: delete
239
     * @param array $params
240
     * @return array
241
     */
242
    public function delete(array $params = [])
243
    {
244
        $endpoint = new Endpoints\Delete($params);
245
        $response = $this->request($endpoint);
246
247
        return $response->getResponse();
248
    }
249
250
    /**
251
     * Endpoint: pq
252
     */
253
    public function pq(): Pq
254
    {
255
        return new Pq($this);
256
    }
257
258
    /**
259
     * Endpoint: indices
260
     */
261
    public function indices(): Indices
262
    {
263
        return new Indices($this);
264
    }
265
266
    /**
267
     * Endpoint: nodes
268
     */
269
    public function nodes(): Nodes
270
    {
271
        return new Nodes($this);
272
    }
273
274
    public function cluster(): Cluster
275
    {
276
        return new Cluster($this);
277
    }
278
279
    /**
280
     * Return Index object
281
     *
282
     * @param string|null $name Name of index
283
     *
284
     * @return \Manticoresearch\Index
285
     */
286
    public function index(string $name = null): Index
287
    {
288
        return new Index($this, $name);
289
    }
290
291
    /**
292
     * Endpoint: bulk
293
     * @param array $params
294
     * @return array
295
     */
296
    public function bulk(array $params = [])
297
    {
298
        $endpoint = new Endpoints\Bulk($params);
299
        $response = $this->request($endpoint);
300
301
        return $response->getResponse();
302
    }
303
304
    /**
305
     * Endpoint: suggest
306
     * @param array $params
307
     * @return array
308
     */
309
    public function suggest(array $params = [])
310
    {
311
        $endpoint = new Endpoints\Suggest();
312
        $endpoint->setIndex($params['index']);
313
        $endpoint->setBody($params['body']);
314
        $response = $this->request(
315
            $endpoint,
316
            [
317
                'responseClass' => 'Manticoresearch\\Response\\SqlToArray',
318
                'responseClassParams' => ['customMapping' => true]
319
            ]
320
        );
321
        return $response->getResponse();
322
    }
323
324
    public function keywords(array $params = [])
325
    {
326
        $endpoint = new Endpoints\Keywords();
327
        $endpoint->setIndex($params['index']);
328
        $endpoint->setBody($params['body']);
329
        $response = $this->request($endpoint, ['responseClass' => 'Manticoresearch\\Response\\SqlToArray']);
330
        return $response->getResponse();
331
    }
332
333
    public function explainQuery(array $params = [])
334
    {
335
        $endpoint = new Endpoints\ExplainQuery();
336
        $endpoint->setIndex($params['index']);
337
        $endpoint->setBody($params['body']);
338
        $response = $this->request(
339
            $endpoint,
340
            [
341
                'responseClass' => 'Manticoresearch\\Response\\SqlToArray',
342
                'responseClassParams' => ['customMapping' => true]
343
            ]
344
        );
345
        return $response->getResponse();
346
    }
347
348
349
    /*
350
     * @return Response
351
     */
352
353
    public function request(Request $request, array $params = []): Response
354
    {
355
        try {
356
            $connection = $this->connectionPool->getConnection();
357
            $this->lastResponse = $connection->getTransportHandler($this->logger)->execute($request, $params);
0 ignored issues
show
introduced by
The method execute() does not exist on Manticoresearch\Transport. Maybe you want to declare this class abstract? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

357
            $this->lastResponse = $connection->getTransportHandler($this->logger)->/** @scrutinizer ignore-call */ execute($request, $params);
Loading history...
358
        } catch (NoMoreNodesException $e) {
359
            $this->logger->error('Manticore Search Request out of retries:', [
360
                'exception' => $e->getMessage(),
361
                'request' => $request->toArray()
362
            ]);
363
            $this->initConnections();
364
            throw $e;
365
        } catch (ConnectionException $e) {
366
            $this->logger->warning('Manticore Search Request failed ' . $this->connectionPool->retries_attempts . ':', [
367
                'exception' => $e->getMessage(),
368
                'request' => $e->getRequest()->toArray()
369
            ]);
370
371
            if ($connection) {
0 ignored issues
show
introduced by
$connection is of type Manticoresearch\Connection, thus it always evaluated to true.
Loading history...
372
                $connection->mark(false);
373
            }
374
375
            return $this->request($request, $params);
376
        }
377
        return $this->lastResponse;
378
    }
379
380
    /*
381
 *
382
 * @return Response
383
 */
384
385
    public function getLastResponse(): Response
386
    {
387
        return $this->lastResponse;
388
    }
389
}
390