Completed
Push — master ( 021254...ec539d )
by Adrian
02:28
created

Client::delete()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 7
rs 10
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
 * Class Client
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
65
    protected function _initConnections()
66
    {
67
        $connections = [];
68
        if (isset($this->_config['connections'])) {
69
            foreach ($this->_config['connections'] as $connection) {
70
                if (is_array($connection)) {
71
                    $connections[] = Connection::create($connection);
72
                } else {
73
                    $connections[] = $connection;
74
                }
75
76
            }
77
78
        }
79
80
        if (empty($connections)) {
81
            $connections[] = Connection::create($this->_config);
82
        }
83
        if (isset($this->_config['connectionStrategy'])) {
84
            if (is_string($this->_config['connectionStrategy'])) {
85
                $strategyName = '\\Manticoresearch\\Connection\\Strategy\\' . $this->_config['connectionStrategy'];
86
                if (class_exists($strategyName)) {
87
                    $strategy = new $strategyName();
88
                } elseif (class_exists($this->_config['connectionStrategy'])) {
89
                    $strategyName = $this->_config['connectionStrategy'];
90
                    $strategy = new $strategyName();
91
                }
92
            } elseif ($this->_config['connectionStrategy'] instanceof SelectorInterface) {
93
                $strategy = $this->_config['connectionStrategy'];
94
            } else {
95
                throw new RuntimeException('Cannot create a strategy based on provided settings!');
96
            }
97
        } else {
98
            $strategy = new $this->_connectionStrategy;
99
        }
100
        if (!isset($this->_config['retries'])) {
101
            $this->_config['retries'] = count($connections);
102
        }
103
        $this->_connectionPool = new Connection\ConnectionPool($connections, $strategy, $this->_config['retries']);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $strategy does not seem to be defined for all execution paths leading up to this point.
Loading history...
104
    }
105
106
    /**
107
     * @param $hosts
108
     */
109
    public function setHosts($hosts)
110
    {
111
        $this->_config['connections'] = $hosts;
112
        $this->_initConnections();
113
    }
114
115
    /**
116
     * @param array $config
117
     * @return $this
118
     */
119
    public function setConfig(array $config): self
120
    {
121
        $this->_config = array_merge($this->_config, $config);
122
        return $this;
123
    }
124
125
    /**
126
     * @param $config
127
     * @return Client
128
     */
129
    public static function create($config): Client
130
    {
131
        return self::createFromArray($config);
132
    }
133
134
    /**
135
     * @param $config
136
     * @return Client
137
     */
138
    public static function createFromArray($config): Client
139
    {
140
141
        return new self($config);
142
    }
143
144
    /**
145
     * @return mixed
146
     */
147
    public function getConnections()
148
    {
149
        return $this->_connectionPool->getConnections();
150
    }
151
152
    /**
153
     * @return mixed
154
     */
155
    public function getConnectionPool(): ConnectionPool
156
    {
157
        return $this->_connectionPool;
158
    }
159
160
    /**
161
     * Endpoint: search
162
     * @param array $params
163
     */
164
    public function search(array $params = [])
165
    {
166
167
168
        $endpoint = new Endpoints\Search($params);
169
        $response = $this->request($endpoint);
170
        return $response->getResponse();
171
    }
172
173
    /**
174
     * Endpoint: insert
175
     * @param array $params
176
     */
177
    public function insert(array $params = [])
178
    {
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
194
        $endpoint = new Endpoints\Replace($params);
195
        $response = $this->request($endpoint);
196
197
        return $response->getResponse();
198
    }
199
200
    /**
201
     * Endpoint: update
202
     * @param array $params
203
     */
204
    public function update(array $params = [])
205
    {
206
207
        $endpoint = new Endpoints\Update($params);
208
        $response = $this->request($endpoint);
209
210
        return $response->getResponse();
211
    }
212
213
    /**
214
     * Endpoint: sql
215
     * @param array $params
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
237
        $endpoint = new Endpoints\Delete($params);
238
        $response = $this->request($endpoint);
239
240
        return $response->getResponse();
0 ignored issues
show
Bug Best Practice introduced by
The expression return $response->getResponse() also could return the type string which is incompatible with the documented return type array.
Loading history...
241
    }
242
243
    /**
244
     * Endpoint: pq
245
     */
246
    public function pq(): Pq
247
    {
248
249
        return new Pq($this);
250
    }
251
252
    /**
253
     * Endpoint: indices
254
     */
255
    public function indices(): Indices
256
    {
257
258
        return new Indices($this);
259
    }
260
261
    /**
262
     * Endpoint: nodes
263
     */
264
    public function nodes(): Nodes
265
    {
266
267
        return new Nodes($this);
268
    }
269
270
    public function cluster(): Cluster
271
    {
272
        return new Cluster($this);
273
    }
274
275
    /**
276
     * Endpoint: bulk
277
     * @param array $params
278
     * @return array
279
     */
280
    public function bulk(array $params = [])
281
    {
282
        $endpoint = new Endpoints\Bulk($params);
283
        $response = $this->request($endpoint);
284
285
        return $response->getResponse();
0 ignored issues
show
Bug Best Practice introduced by
The expression return $response->getResponse() also could return the type string which is incompatible with the documented return type array.
Loading history...
286
    }
287
288
    /**
289
     * Endpoint: suggest
290
     * @param array $params
291
     * @return array
292
     */
293
    public function suggest(array $params = [])
294
    {
295
        $endpoint = new Endpoints\Suggest($params);
296
        $endpoint->setIndex($params['index']);
297
        $endpoint->setBody($params['body']);
298
        $response = $this->request($endpoint, ['responseClass' => 'Manticoresearch\\Response\\SqlToArray']);
299
        return $response->getResponse();
300
    }
301
302
    public function keywords(array $params = [])
303
    {
304
        $endpoint = new Endpoints\Keywords($params);
305
        $endpoint->setIndex($params['index']);
306
        $endpoint->setBody($params['body']);
307
        $response = $this->request($endpoint, ['responseClass' => 'Manticoresearch\\Response\\SqlToArray']);
308
        return $response->getResponse();
309
    }
310
311
312
    /*
313
     * @return Response
314
     */
315
316
    public function request(Request $request, array $params = []): Response
317
    {
318
319
320
        try {
321
            $connection = $this->_connectionPool->getConnection();
322
            $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

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