Completed
Push — master ( b25384...a9cbe2 )
by Adrian
01:51
created

Client::explainQuery()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 5
nc 1
nop 1
dl 0
loc 7
rs 10
c 0
b 0
f 0
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 = '\\Manticoresearch\\Connection\\Strategy\\' . $this->_config['connectionStrategy'];
83
                if (class_exists($strategyName)) {
84
                    $strategy = new $strategyName();
85
                } elseif (class_exists($this->_config['connectionStrategy'])) {
86
                    $strategyName = $this->_config['connectionStrategy'];
87
                    $strategy = new $strategyName();
88
                }
89
            } elseif ($this->_config['connectionStrategy'] instanceof SelectorInterface) {
90
                $strategy = $this->_config['connectionStrategy'];
91
            } else {
92
                throw new RuntimeException('Cannot create a strategy based on provided settings!');
93
            }
94
        } else {
95
            $strategy = new $this->_connectionStrategy;
96
        }
97
        if (!isset($this->_config['retries'])) {
98
            $this->_config['retries'] = count($connections);
99
        }
100
        $this->_connectionPool = new Connection\ConnectionPool($connections, $strategy ?? new $this->_connectionStrategy, $this->_config['retries']);
101
    }
102
103
    /**
104
     * @param string|array $hosts
105
     */
106
    public function setHosts($hosts)
107
    {
108
        $this->_config['connections'] = $hosts;
109
        $this->_initConnections();
110
    }
111
112
    /**
113
     * @param array $config
114
     * @return $this
115
     */
116
    public function setConfig(array $config): self
117
    {
118
        $this->_config = array_merge($this->_config, $config);
119
        return $this;
120
    }
121
122
    /**
123
     * @param array $config
124
     * @return Client
125
     */
126
    public static function create($config): Client
127
    {
128
        return self::createFromArray($config);
129
    }
130
131
    /**
132
     * @param array $config
133
     * @return Client
134
     */
135
    public static function createFromArray($config): Client
136
    {
137
        return new self($config);
138
    }
139
140
    /**
141
     * @return mixed
142
     */
143
    public function getConnections()
144
    {
145
        return $this->_connectionPool->getConnections();
146
    }
147
148
    /**
149
     * @return ConnectionPool
150
     */
151
    public function getConnectionPool(): ConnectionPool
152
    {
153
        return $this->_connectionPool;
154
    }
155
156
    /**
157
     * Endpoint: search
158
     * @param array $params
159
     * @param bool $obj
160
     * @return array|Response
161
     */
162
    public function search(array $params = [],$obj=false)
163
    {
164
        $endpoint = new Endpoints\Search($params);
165
        $response = $this->request($endpoint);
166
        if($obj ===true) {
167
            return $response;
168
        }else{
169
            return $response->getResponse();
170
        }
171
    }
172
173
    /**
174
     * Endpoint: insert
175
     * @param array $params
176
     * @return array
177
     */
178
    public function insert(array $params = [])
179
    {
180
        $endpoint = new Endpoints\Insert($params);
181
        $response = $this->request($endpoint);
182
183
        return $response->getResponse();
184
    }
185
186
    /**
187
     * Endpoint: replace
188
     * @param array $params
189
     * @return mixed
190
     */
191
    public function replace(array $params = [])
192
    {
193
        $endpoint = new Endpoints\Replace($params);
194
        $response = $this->request($endpoint);
195
196
        return $response->getResponse();
197
    }
198
199
    /**
200
     * Endpoint: update
201
     * @param array $params
202
     * @return array
203
     */
204
    public function update(array $params = [])
205
    {
206
        $endpoint = new Endpoints\Update($params);
207
        $response = $this->request($endpoint);
208
209
        return $response->getResponse();
210
    }
211
212
    /**
213
     * Endpoint: sql
214
     * @param array $params
215
     * @return array
216
     */
217
    public function sql(array $params = [])
218
    {
219
        $endpoint = new Endpoints\Sql($params);
220
        if (isset($params['mode'])) {
221
            $endpoint->setMode($params['mode']);
222
            $response = $this->request($endpoint, ['responseClass' => 'Manticoresearch\\Response\\SqlToArray']);
223
        } else {
224
            $response = $this->request($endpoint);
225
        }
226
        return $response->getResponse();
227
    }
228
229
    /**
230
     * Endpoint: delete
231
     * @param array $params
232
     * @return array
233
     */
234
    public function delete(array $params = [])
235
    {
236
        $endpoint = new Endpoints\Delete($params);
237
        $response = $this->request($endpoint);
238
239
        return $response->getResponse();
240
    }
241
242
    /**
243
     * Endpoint: pq
244
     */
245
    public function pq(): Pq
246
    {
247
        return new Pq($this);
248
    }
249
250
    /**
251
     * Endpoint: indices
252
     */
253
    public function indices(): Indices
254
    {
255
        return new Indices($this);
256
    }
257
258
    /**
259
     * Endpoint: nodes
260
     */
261
    public function nodes(): Nodes
262
    {
263
        return new Nodes($this);
264
    }
265
266
    public function cluster(): Cluster
267
    {
268
        return new Cluster($this);
269
    }
270
271
    /**
272
     * Endpoint: bulk
273
     * @param array $params
274
     * @return array
275
     */
276
    public function bulk(array $params = [])
277
    {
278
        $endpoint = new Endpoints\Bulk($params);
279
        $response = $this->request($endpoint);
280
281
        return $response->getResponse();
282
    }
283
284
    /**
285
     * Endpoint: suggest
286
     * @param array $params
287
     * @return array
288
     */
289
    public function suggest(array $params = [])
290
    {
291
        $endpoint = new Endpoints\Suggest();
292
        $endpoint->setIndex($params['index']);
293
        $endpoint->setBody($params['body']);
294
        $response = $this->request($endpoint, ['responseClass' => 'Manticoresearch\\Response\\SqlToArray']);
295
        return $response->getResponse();
296
    }
297
298
    public function keywords(array $params = [])
299
    {
300
        $endpoint = new Endpoints\Keywords();
301
        $endpoint->setIndex($params['index']);
302
        $endpoint->setBody($params['body']);
303
        $response = $this->request($endpoint, ['responseClass' => 'Manticoresearch\\Response\\SqlToArray']);
304
        return $response->getResponse();
305
    }
306
    public function explainQuery(array $params = [])
307
    {
308
        $endpoint = new Endpoints\ExplainQuery();
309
        $endpoint->setIndex($params['index']);
310
        $endpoint->setBody($params['body']);
311
        $response = $this->request($endpoint, ['responseClass' => 'Manticoresearch\\Response\\SqlToArray']);
312
        return $response->getResponse();
313
    }
314
315
316
    /*
317
     * @return Response
318
     */
319
320
    public function request(Request $request, array $params = []): Response
321
    {
322
        try {
323
            $connection = $this->_connectionPool->getConnection();
324
            $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

324
            $this->_lastResponse = $connection->getTransportHandler($this->_logger)->/** @scrutinizer ignore-call */ execute($request, $params);
Loading history...
325
        } catch (NoMoreNodesException $e) {
326
            $this->_logger->error('Manticore Search Request out of retries:', [
327
                'exception' => $e->getMessage(),
328
                'request' => $request->toArray()
329
            ]);
330
            throw $e;
331
        } catch (ConnectionException $e) {
332
            $this->_logger->warning('Manticore Search Request failed ' . $this->_connectionPool->retries_attempts . ':', [
333
                'exception' => $e->getMessage(),
334
                'request' => $e->getRequest()->toArray()
335
            ]);
336
337
            if (isset($connection)) {
338
                $connection->mark(false);
339
            }
340
341
            return $this->request($request, $params);
342
        }
343
        return $this->_lastResponse;
344
    }
345
    /*
346
 *
347
 * @return Response
348
 */
349
350
    public function getLastResponse(): Response
351
    {
352
        return $this->_lastResponse;
353
    }
354
355
}
356