Completed
Push — master ( 6a4a32...e9c85c )
by Nicolas
02:18
created

Client::__construct()   B

Complexity

Conditions 6
Paths 9

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 20
rs 8.9777
c 0
b 0
f 0
cc 6
nc 9
nop 3
1
<?php
2
3
namespace Elastica;
4
5
use Elastica\Bulk\Action;
6
use Elastica\Exception\ConnectionException;
7
use Elastica\Exception\InvalidException;
8
use Elastica\Script\AbstractScript;
9
use Elasticsearch\Endpoints\AbstractEndpoint;
10
use Elasticsearch\Endpoints\Indices\ForceMerge;
11
use Elasticsearch\Endpoints\Indices\Refresh;
12
use Elasticsearch\Endpoints\Update;
13
use Psr\Log\LoggerInterface;
14
use Psr\Log\NullLogger;
15
16
/**
17
 * Client to connect the the elasticsearch server.
18
 *
19
 * @author Nicolas Ruflin <[email protected]>
20
 */
21
class Client
22
{
23
    /**
24
     * @var ClientConfiguration
25
     */
26
    protected $_config;
27
28
    /**
29
     * @var callback
30
     */
31
    protected $_callback;
32
33
    /**
34
     * @var Connection\ConnectionPool
35
     */
36
    protected $_connectionPool;
37
38
    /**
39
     * @var \Elastica\Request|null
40
     */
41
    protected $_lastRequest;
42
43
    /**
44
     * @var \Elastica\Response|null
45
     */
46
    protected $_lastResponse;
47
48
    /**
49
     * @var LoggerInterface
50
     */
51
    protected $_logger;
52
53
    /**
54
     * @var string
55
     */
56
    protected $_version;
57
58
    /**
59
     * Creates a new Elastica client.
60
     *
61
     * @param array|string    $config   OPTIONAL Additional config or DSN of options
62
     * @param callback        $callback OPTIONAL Callback function which can be used to be notified about errors (for example connection down)
63
     * @param LoggerInterface $logger
64
     *
65
     * @throws \Elastica\Exception\InvalidException
66
     */
67
    public function __construct($config = [], $callback = null, LoggerInterface $logger = null)
68
    {
69
        if (\is_string($config)) {
70
            $configuration = ClientConfiguration::fromDsn($config);
71
        } elseif (\is_array($config)) {
72
            $configuration = ClientConfiguration::fromArray($config);
73
        } else {
74
            throw new InvalidException('Config parameter must be an array or a string.');
75
        }
76
77
        $this->_config = $configuration;
0 ignored issues
show
Documentation Bug introduced by
It seems like $configuration of type object<self> is incompatible with the declared type object<Elastica\ClientConfiguration> of property $_config.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
78
        $this->_callback = $callback;
79
80
        if (!$logger && $configuration->get('log')) {
81
            $logger = new Log($configuration->get('log'));
82
        }
83
        $this->_logger = $logger ?: new NullLogger();
84
85
        $this->_initConnections();
86
    }
87
88
    /**
89
     * Get current version.
90
     *
91
     * @return string
92
     */
93
    public function getVersion()
94
    {
95
        if ($this->_version) {
96
            return $this->_version;
97
        }
98
99
        $data = $this->request('/')->getData();
100
101
        return $this->_version = $data['version']['number'];
102
    }
103
104
    /**
105
     * Inits the client connections.
106
     */
107
    protected function _initConnections()
108
    {
109
        $connections = [];
110
111
        foreach ($this->getConfig('connections') as $connection) {
0 ignored issues
show
Bug introduced by
The expression $this->getConfig('connections') of type array|string is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
112
            $connections[] = Connection::create($this->_prepareConnectionParams($connection));
113
        }
114
115
        if ($this->_config->has('servers')) {
116
            $servers = $this->_config->get('servers');
117
            foreach ($servers as $server) {
118
                $connections[] = Connection::create($this->_prepareConnectionParams($server));
119
            }
120
        }
121
122
        // If no connections set, create default connection
123
        if (empty($connections)) {
124
            $connections[] = Connection::create($this->_prepareConnectionParams($this->getConfig()));
0 ignored issues
show
Bug introduced by
It seems like $this->getConfig() targeting Elastica\Client::getConfig() can also be of type string; however, Elastica\Client::_prepareConnectionParams() does only seem to accept array, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
125
        }
126
127
        if (!$this->_config->has('connectionStrategy')) {
128
            if (true === $this->getConfig('roundRobin')) {
129
                $this->setConfigValue('connectionStrategy', 'RoundRobin');
130
            } else {
131
                $this->setConfigValue('connectionStrategy', 'Simple');
132
            }
133
        }
134
135
        $strategy = Connection\Strategy\StrategyFactory::create($this->getConfig('connectionStrategy'));
136
137
        $this->_connectionPool = new Connection\ConnectionPool($connections, $strategy, $this->_callback);
138
    }
139
140
    /**
141
     * Creates a Connection params array from a Client or server config array.
142
     *
143
     * @param array $config
144
     *
145
     * @return array
146
     */
147
    protected function _prepareConnectionParams(array $config)
148
    {
149
        $params = [];
150
        $params['config'] = [];
151
        foreach ($config as $key => $value) {
152
            if (\in_array($key, ['bigintConversion', 'curl', 'headers', 'url'])) {
153
                $params['config'][$key] = $value;
154
            } else {
155
                $params[$key] = $value;
156
            }
157
        }
158
159
        return $params;
160
    }
161
162
    /**
163
     * Sets specific config values (updates and keeps default values).
164
     *
165
     * @param array $config Params
166
     *
167
     * @return $this
168
     */
169
    public function setConfig(array $config)
170
    {
171
        foreach ($config as $key => $value) {
172
            $this->_config->set($key, $value);
173
        }
174
175
        return $this;
176
    }
177
178
    /**
179
     * Returns a specific config key or the whole
180
     * config array if not set.
181
     *
182
     * @param string $key Config key
183
     *
184
     * @throws \Elastica\Exception\InvalidException
185
     *
186
     * @return array|string Config value
187
     */
188
    public function getConfig($key = '')
189
    {
190
        return $this->_config->get($key);
191
    }
192
193
    /**
194
     * Sets / overwrites a specific config value.
195
     *
196
     * @param string $key   Key to set
197
     * @param mixed  $value Value
198
     *
199
     * @return $this
200
     */
201
    public function setConfigValue($key, $value)
202
    {
203
        return $this->setConfig([$key => $value]);
204
    }
205
206
    /**
207
     * @param array|string $keys    config key or path of config keys
208
     * @param mixed        $default default value will be returned if key was not found
209
     *
210
     * @return mixed
211
     */
212
    public function getConfigValue($keys, $default = null)
213
    {
214
        $value = $this->_config->getAll();
215
        foreach ((array) $keys as $key) {
216
            if (isset($value[$key])) {
217
                $value = $value[$key];
218
            } else {
219
                return $default;
220
            }
221
        }
222
223
        return $value;
224
    }
225
226
    /**
227
     * Returns the index for the given connection.
228
     *
229
     * @param string $name Index name to create connection to
230
     *
231
     * @return \Elastica\Index Index for the given name
232
     */
233
    public function getIndex($name)
234
    {
235
        return new Index($this, $name);
236
    }
237
238
    /**
239
     * Adds a HTTP Header.
240
     *
241
     * @param string $header      The HTTP Header
242
     * @param string $headerValue The HTTP Header Value
243
     *
244
     * @throws \Elastica\Exception\InvalidException If $header or $headerValue is not a string
245
     *
246
     * @return $this
247
     */
248
    public function addHeader($header, $headerValue)
249
    {
250
        if (\is_string($header) && \is_string($headerValue)) {
251
            if ($this->_config->has('headers')) {
252
                $headers = $this->_config->get('headers');
253
            } else {
254
                $headers = [];
255
            }
256
            $headers[$header] = $headerValue;
257
            $this->_config->set('headers', $headers);
258
        } else {
259
            throw new InvalidException('Header must be a string');
260
        }
261
262
        return $this;
263
    }
264
265
    /**
266
     * Remove a HTTP Header.
267
     *
268
     * @param string $header The HTTP Header to remove
269
     *
270
     * @throws \Elastica\Exception\InvalidException If $header is not a string
271
     *
272
     * @return $this
273
     */
274
    public function removeHeader($header)
275
    {
276
        if (\is_string($header)) {
277
            if ($this->_config->has('headers')) {
278
                $headers = $this->_config->get('headers');
279
                unset($headers[$header]);
280
                $this->_config->set('headers', $headers);
281
            }
282
        } else {
283
            throw new InvalidException('Header must be a string');
284
        }
285
286
        return $this;
287
    }
288
289
    /**
290
     * Uses _bulk to send documents to the server.
291
     *
292
     * Array of \Elastica\Document as input. Index and type has to be
293
     * set inside the document, because for bulk settings documents,
294
     * documents can belong to any type and index
295
     *
296
     * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html
297
     *
298
     * @param array|\Elastica\Document[] $docs          Array of Elastica\Document
299
     * @param array                      $requestParams
300
     *
301
     * @throws \Elastica\Exception\InvalidException If docs is empty
302
     *
303
     * @return \Elastica\Bulk\ResponseSet Response object
304
     */
305 View Code Duplication
    public function updateDocuments(array $docs, array $requestParams = [])
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
306
    {
307
        if (empty($docs)) {
308
            throw new InvalidException('Array has to consist of at least one element');
309
        }
310
311
        $bulk = new Bulk($this);
312
313
        $bulk->addDocuments($docs, Action::OP_TYPE_UPDATE);
314
        foreach ($requestParams as $key => $value) {
315
            $bulk->setRequestParam($key, $value);
316
        }
317
318
        return $bulk->send();
319
    }
320
321
    /**
322
     * Uses _bulk to send documents to the server.
323
     *
324
     * Array of \Elastica\Document as input. Index and type has to be
325
     * set inside the document, because for bulk settings documents,
326
     * documents can belong to any type and index
327
     *
328
     * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html
329
     *
330
     * @param array|\Elastica\Document[] $docs          Array of Elastica\Document
331
     * @param array                      $requestParams
332
     *
333
     * @throws \Elastica\Exception\InvalidException If docs is empty
334
     *
335
     * @return \Elastica\Bulk\ResponseSet Response object
336
     */
337 View Code Duplication
    public function addDocuments(array $docs, array $requestParams = [])
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
338
    {
339
        if (empty($docs)) {
340
            throw new InvalidException('Array has to consist of at least one element');
341
        }
342
343
        $bulk = new Bulk($this);
344
345
        $bulk->addDocuments($docs);
346
347
        foreach ($requestParams as $key => $value) {
348
            $bulk->setRequestParam($key, $value);
349
        }
350
351
        return $bulk->send();
352
    }
353
354
    /**
355
     * Update document, using update script. Requires elasticsearch >= 0.19.0.
356
     *
357
     * @param int|string                                               $id      document id
358
     * @param array|\Elastica\Script\AbstractScript|\Elastica\Document $data    raw data for request body
359
     * @param string                                                   $index   index to update
360
     * @param string                                                   $type    type of index to update
361
     * @param array                                                    $options array of query params to use for query. For possible options check es api
362
     *
363
     * @return \Elastica\Response
364
     *
365
     * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-update.html
366
     */
367
    public function updateDocument($id, $data, $index, $type, array $options = [])
368
    {
369
        $endpoint = new Update();
370
        $endpoint->setID($id);
371
        $endpoint->setIndex($index);
372
        $endpoint->setType($type);
0 ignored issues
show
Deprecated Code introduced by
The method Elasticsearch\Endpoints\...ractEndpoint::setType() has been deprecated.

This method has been deprecated.

Loading history...
373
374
        if ($data instanceof AbstractScript) {
375
            $requestData = $data->toArray();
376
        } elseif ($data instanceof Document) {
377
            $requestData = ['doc' => $data->getData()];
378
379
            if ($data->getDocAsUpsert()) {
380
                $requestData['doc_as_upsert'] = true;
381
            }
382
383
            $docOptions = $data->getOptions(
384
                [
385
                    'version',
386
                    'version_type',
387
                    'routing',
388
                    'percolate',
389
                    'parent',
390
                    'retry_on_conflict',
391
                    'consistency',
392
                    'replication',
393
                    'refresh',
394
                    'timeout',
395
                ]
396
            );
397
            $options += $docOptions;
398
        } else {
399
            $requestData = $data;
400
        }
401
402
        //If an upsert document exists
403
        if ($data instanceof AbstractScript || $data instanceof Document) {
404
            if ($data->hasUpsert()) {
405
                $requestData['upsert'] = $data->getUpsert()->getData();
406
            }
407
        }
408
409
        $endpoint->setBody($requestData);
410
        $endpoint->setParams($options);
411
412
        $response = $this->requestEndpoint($endpoint);
413
414
        if ($response->isOk()
415
            && $data instanceof Document
416
            && ($data->isAutoPopulate() || $this->getConfigValue(['document', 'autoPopulate'], false))
417
        ) {
418
            $responseData = $response->getData();
419
            if (isset($responseData['_version'])) {
420
                $data->setVersion($responseData['_version']);
421
            }
422
        }
423
424
        return $response;
425
    }
426
427
    /**
428
     * Bulk deletes documents.
429
     *
430
     * @param array|\Elastica\Document[] $docs
431
     * @param array                      $requestParams
432
     *
433
     * @throws \Elastica\Exception\InvalidException
434
     *
435
     * @return \Elastica\Bulk\ResponseSet
436
     */
437 View Code Duplication
    public function deleteDocuments(array $docs, array $requestParams = [])
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
438
    {
439
        if (empty($docs)) {
440
            throw new InvalidException('Array has to consist of at least one element');
441
        }
442
443
        $bulk = new Bulk($this);
444
        $bulk->addDocuments($docs, Action::OP_TYPE_DELETE);
445
446
        foreach ($requestParams as $key => $value) {
447
            $bulk->setRequestParam($key, $value);
448
        }
449
450
        return $bulk->send();
451
    }
452
453
    /**
454
     * Returns the status object for all indices.
455
     *
456
     * @return \Elastica\Status Status object
457
     */
458
    public function getStatus()
459
    {
460
        return new Status($this);
461
    }
462
463
    /**
464
     * Returns the current cluster.
465
     *
466
     * @return \Elastica\Cluster Cluster object
467
     */
468
    public function getCluster()
469
    {
470
        return new Cluster($this);
471
    }
472
473
    /**
474
     * Establishes the client connections.
475
     */
476
    public function connect()
477
    {
478
        return $this->_initConnections();
479
    }
480
481
    /**
482
     * @param \Elastica\Connection $connection
483
     *
484
     * @return $this
485
     */
486
    public function addConnection(Connection $connection)
487
    {
488
        $this->_connectionPool->addConnection($connection);
489
490
        return $this;
491
    }
492
493
    /**
494
     * Determines whether a valid connection is available for use.
495
     *
496
     * @return bool
497
     */
498
    public function hasConnection()
499
    {
500
        return $this->_connectionPool->hasConnection();
501
    }
502
503
    /**
504
     * @throws \Elastica\Exception\ClientException
505
     *
506
     * @return \Elastica\Connection
507
     */
508
    public function getConnection()
509
    {
510
        return $this->_connectionPool->getConnection();
511
    }
512
513
    /**
514
     * @return \Elastica\Connection[]
515
     */
516
    public function getConnections()
517
    {
518
        return $this->_connectionPool->getConnections();
519
    }
520
521
    /**
522
     * @return \Elastica\Connection\Strategy\StrategyInterface
523
     */
524
    public function getConnectionStrategy()
525
    {
526
        return $this->_connectionPool->getStrategy();
527
    }
528
529
    /**
530
     * @param array|\Elastica\Connection[] $connections
531
     *
532
     * @return $this
533
     */
534
    public function setConnections(array $connections)
535
    {
536
        $this->_connectionPool->setConnections($connections);
537
538
        return $this;
539
    }
540
541
    /**
542
     * Deletes documents with the given ids, index, type from the index.
543
     *
544
     * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html
545
     *
546
     * @param array                  $ids     Document ids
547
     * @param string|\Elastica\Index $index   Index name
548
     * @param string|\Elastica\Type  $type    Type of documents
549
     * @param string|bool            $routing Optional routing key for all ids
550
     *
551
     * @throws \Elastica\Exception\InvalidException
552
     *
553
     * @return \Elastica\Bulk\ResponseSet Response  object
554
     */
555
    public function deleteIds(array $ids, $index, $type, $routing = false)
556
    {
557
        if (empty($ids)) {
558
            throw new InvalidException('Array has to consist of at least one id');
559
        }
560
561
        $bulk = new Bulk($this);
562
        $bulk->setIndex($index);
563
        $bulk->setType($type);
564
565
        foreach ($ids as $id) {
566
            $action = new Action(Action::OP_TYPE_DELETE);
567
            $action->setId($id);
568
569
            if (!empty($routing)) {
570
                $action->setRouting($routing);
0 ignored issues
show
Bug introduced by
It seems like $routing defined by parameter $routing on line 555 can also be of type boolean; however, Elastica\Bulk\Action::setRouting() does only seem to accept string|integer, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
571
            }
572
573
            $bulk->addAction($action);
574
        }
575
576
        return $bulk->send();
577
    }
578
579
    /**
580
     * Bulk operation.
581
     *
582
     * Every entry in the params array has to exactly on array
583
     * of the bulk operation. An example param array would be:
584
     *
585
     * array(
586
     *         array('index' => array('_index' => 'test', '_type' => 'user', '_id' => '1')),
587
     *         array('user' => array('name' => 'hans')),
588
     *         array('delete' => array('_index' => 'test', '_type' => 'user', '_id' => '2'))
589
     * );
590
     *
591
     * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html
592
     *
593
     * @param array $params Parameter array
594
     *
595
     * @throws \Elastica\Exception\ResponseException
596
     * @throws \Elastica\Exception\InvalidException
597
     *
598
     * @return \Elastica\Bulk\ResponseSet Response object
599
     */
600
    public function bulk(array $params)
601
    {
602
        if (empty($params)) {
603
            throw new InvalidException('Array has to consist of at least one param');
604
        }
605
606
        $bulk = new Bulk($this);
607
608
        $bulk->addRawData($params);
609
610
        return $bulk->send();
611
    }
612
613
    /**
614
     * Makes calls to the elasticsearch server based on this index.
615
     *
616
     * It's possible to make any REST query directly over this method
617
     *
618
     * @param string       $path        Path to call
619
     * @param string       $method      Rest method to use (GET, POST, DELETE, PUT)
620
     * @param array|string $data        OPTIONAL Arguments as array or pre-encoded string
621
     * @param array        $query       OPTIONAL Query params
622
     * @param string       $contentType Content-Type sent with this request
623
     *
624
     * @throws Exception\ConnectionException|Exception\ClientException
625
     *
626
     * @return Response Response object
627
     */
628
    public function request($path, $method = Request::GET, $data = [], array $query = [], $contentType = Request::DEFAULT_CONTENT_TYPE)
629
    {
630
        $connection = $this->getConnection();
631
        $request = $this->_lastRequest = new Request($path, $method, $data, $query, $connection, $contentType);
0 ignored issues
show
Bug introduced by
It seems like $data defined by parameter $data on line 628 can also be of type string; however, Elastica\Request::__construct() does only seem to accept array, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
632
        $this->_lastResponse = null;
633
634
        try {
635
            $response = $this->_lastResponse = $request->send();
636
        } catch (ConnectionException $e) {
637
            $this->_connectionPool->onFail($connection, $e, $this);
638
            $this->_log($e);
0 ignored issues
show
Deprecated Code introduced by
The method Elastica\Client::_log() has been deprecated with message: Overwriting Client->_log is deprecated. Handle logging functionality by using a custom LoggerInterface.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
639
640
            // In case there is no valid connection left, throw exception which caused the disabling of the connection.
641
            if (!$this->hasConnection()) {
642
                throw $e;
643
            }
644
645
            return $this->request($path, $method, $data, $query);
646
        }
647
648
        $this->_log($request);
0 ignored issues
show
Deprecated Code introduced by
The method Elastica\Client::_log() has been deprecated with message: Overwriting Client->_log is deprecated. Handle logging functionality by using a custom LoggerInterface.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
649
650
        return $response;
651
    }
652
653
    /**
654
     * Makes calls to the elasticsearch server with usage official client Endpoint.
655
     *
656
     * @param AbstractEndpoint $endpoint
657
     *
658
     * @return Response
659
     */
660
    public function requestEndpoint(AbstractEndpoint $endpoint)
661
    {
662
        return $this->request(
663
            \ltrim($endpoint->getURI(), '/'),
664
            $endpoint->getMethod(),
665
            null === $endpoint->getBody() ? [] : $endpoint->getBody(),
666
            $endpoint->getParams()
667
        );
668
    }
669
670
    /**
671
     * logging.
672
     *
673
     * @deprecated Overwriting Client->_log is deprecated. Handle logging functionality by using a custom LoggerInterface.
674
     *
675
     * @param mixed $context
676
     */
677
    protected function _log($context)
678
    {
679
        if ($context instanceof ConnectionException) {
680
            $this->_logger->error('Elastica Request Failure', [
681
                'exception' => $context,
682
                'request' => $context->getRequest()->toArray(),
683
                'retry' => $this->hasConnection(),
684
            ]);
685
686
            return;
687
        }
688
689
        if ($context instanceof Request) {
690
            $this->_logger->debug('Elastica Request', [
691
                'request' => $context->toArray(),
692
                'response' => $this->_lastResponse ? $this->_lastResponse->getData() : null,
693
                'responseStatus' => $this->_lastResponse ? $this->_lastResponse->getStatus() : null,
694
            ]);
695
696
            return;
697
        }
698
699
        $this->_logger->debug('Elastica Request', [
700
            'message' => $context,
701
        ]);
702
    }
703
704
    /**
705
     * Force merges all search indices.
706
     *
707
     * @param array $args OPTIONAL Optional arguments
708
     *
709
     * @return \Elastica\Response Response object
710
     *
711
     * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-forcemerge.html
712
     */
713
    public function forcemergeAll($args = [])
714
    {
715
        $endpoint = new ForceMerge();
716
        $endpoint->setParams($args);
717
718
        return $this->requestEndpoint($endpoint);
719
    }
720
721
    /**
722
     * Refreshes all search indices.
723
     *
724
     * @return \Elastica\Response Response object
725
     *
726
     * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-refresh.html
727
     */
728
    public function refreshAll()
729
    {
730
        return $this->requestEndpoint(new Refresh());
731
    }
732
733
    /**
734
     * @return Request|null
735
     */
736
    public function getLastRequest()
737
    {
738
        return $this->_lastRequest;
739
    }
740
741
    /**
742
     * @return Response|null
743
     */
744
    public function getLastResponse()
745
    {
746
        return $this->_lastResponse;
747
    }
748
749
    /**
750
     * Replace the existing logger.
751
     *
752
     * @param LoggerInterface $logger
753
     *
754
     * @return $this
755
     */
756
    public function setLogger(LoggerInterface $logger)
757
    {
758
        $this->_logger = $logger;
759
760
        return $this;
761
    }
762
}
763