Completed
Push — master ( bb241f...f9eb32 )
by Simonas
04:41 queued 01:25
created

Manager::getAliases()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
/*
4
 * This file is part of the ONGR package.
5
 *
6
 * (c) NFQ Technologies UAB <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace ONGR\ElasticsearchBundle\Service;
13
14
use Elasticsearch\Client;
15
use Elasticsearch\Common\Exceptions\Missing404Exception;
16
use ONGR\ElasticsearchBundle\Event\Events;
17
use ONGR\ElasticsearchBundle\Event\BulkEvent;
18
use ONGR\ElasticsearchBundle\Event\CommitEvent;
19
use ONGR\ElasticsearchBundle\Exception\BulkWithErrorsException;
20
use ONGR\ElasticsearchBundle\Mapping\MetadataCollector;
21
use ONGR\ElasticsearchBundle\Result\Converter;
22
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
23
use Symfony\Component\Stopwatch\Stopwatch;
24
25
/**
26
 * Manager class.
27
 */
28
class Manager
29
{
30
    /**
31
     * @var string Manager name
32
     */
33
    private $name;
34
35
    /**
36
     * @var array Manager configuration
37
     */
38
    private $config = [];
39
40
    /**
41
     * @var Client
42
     */
43
    private $client;
44
45
    /**
46
     * @var Converter
47
     */
48
    private $converter;
49
50
    /**
51
     * @var array Container for bulk queries
52
     */
53
    private $bulkQueries = [];
54
55
    /**
56
     * @var array Holder for consistency, refresh and replication parameters
57
     */
58
    private $bulkParams = [];
59
60
    /**
61
     * @var array
62
     */
63
    private $indexSettings;
64
65
    /**
66
     * @var MetadataCollector
67
     */
68
    private $metadataCollector;
69
70
    /**
71
     * After commit to make data available the refresh or flush operation is needed
72
     * so one of those methods has to be defined, the default is refresh.
73
     *
74
     * @var string
75
     */
76
    private $commitMode = 'refresh';
77
78
    /**
79
     * The size that defines after how much document inserts call commit function.
80
     *
81
     * @var int
82
     */
83
    private $bulkCommitSize = 100;
84
85
    /**
86
     * Container to count how many documents was passed to the bulk query.
87
     *
88
     * @var int
89
     */
90
    private $bulkCount = 0;
91
92
    /**
93
     * @var Repository[] Repository local cache
94
     */
95
    private $repositories;
96
97
    /**
98
     * @var EventDispatcherInterface
99
     */
100
    private $eventDispatcher;
101
102
    /**
103
     * @var Stopwatch
104
     */
105
    private $stopwatch;
106
107
    /**
108
     * @param string            $name              Manager name
109
     * @param array             $config            Manager configuration
110
     * @param Client            $client
111
     * @param array             $indexSettings
112
     * @param MetadataCollector $metadataCollector
113
     * @param Converter         $converter
114
     */
115
    public function __construct(
116
        $name,
117
        array $config,
118
        $client,
119
        array $indexSettings,
120
        $metadataCollector,
121
        $converter
122
    ) {
123
        $this->name = $name;
124
        $this->config = $config;
125
        $this->client = $client;
126
        $this->indexSettings = $indexSettings;
127
        $this->metadataCollector = $metadataCollector;
128
        $this->converter = $converter;
129
    }
130
131
    /**
132
     * Returns Elasticsearch connection.
133
     *
134
     * @return Client
135
     */
136
    public function getClient()
137
    {
138
        return $this->client;
139
    }
140
141
    /**
142
     * @return string
143
     */
144
    public function getName()
145
    {
146
        return $this->name;
147
    }
148
149
    /**
150
     * @return array
151
     */
152
    public function getConfig()
153
    {
154
        return $this->config;
155
    }
156
157
    /**
158
     * @param EventDispatcherInterface $eventDispatcher
159
     */
160
    public function setEventDispatcher(EventDispatcherInterface $eventDispatcher)
161
    {
162
        $this->eventDispatcher = $eventDispatcher;
163
    }
164
165
    /**
166
     * @param Stopwatch $stopwatch
167
     */
168
    public function setStopwatch(Stopwatch $stopwatch)
169
    {
170
        $this->stopwatch = $stopwatch;
171
    }
172
173
    /**
174
     * Returns repository by document class.
175
     *
176
     * @param string $className FQCN or string in Bundle:Document format
177
     *
178
     * @return Repository
179
     */
180
    public function getRepository($className)
181
    {
182
        if (!is_string($className)) {
183
            throw new \InvalidArgumentException('Document class must be a string.');
184
        }
185
186
        $namespace = $this->getMetadataCollector()->getClassName($className);
187
188
        if (isset($this->repositories[$namespace])) {
189
            return $this->repositories[$namespace];
190
        }
191
192
        $repository = $this->createRepository($namespace);
193
        $this->repositories[$namespace] = $repository;
194
195
        return $repository;
196
    }
197
198
    /**
199
     * @return MetadataCollector
200
     */
201
    public function getMetadataCollector()
202
    {
203
        return $this->metadataCollector;
204
    }
205
206
    /**
207
     * @return Converter
208
     */
209
    public function getConverter()
210
    {
211
        return $this->converter;
212
    }
213
214
    /**
215
     * @return string
216
     */
217
    public function getCommitMode()
218
    {
219
        return $this->commitMode;
220
    }
221
222
    /**
223
     * @param string $commitMode
224
     */
225
    public function setCommitMode($commitMode)
226
    {
227
        if ($commitMode === 'refresh' || $commitMode === 'flush' || $commitMode === 'none') {
228
            $this->commitMode = $commitMode;
229
        } else {
230
            throw new \LogicException('The commit method must be either refresh, flush or none.');
231
        }
232
    }
233
234
    /**
235
     * @return int
236
     */
237
    public function getBulkCommitSize()
238
    {
239
        return $this->bulkCommitSize;
240
    }
241
242
    /**
243
     * @param int $bulkCommitSize
244
     */
245
    public function setBulkCommitSize($bulkCommitSize)
246
    {
247
        $this->bulkCommitSize = $bulkCommitSize;
248
    }
249
250
    /**
251
     * Creates a repository.
252
     *
253
     * @param string $className
254
     *
255
     * @return Repository
256
     */
257
    private function createRepository($className)
258
    {
259
        return new Repository($this, $className);
260
    }
261
262
    /**
263
     * Executes search query in the index.
264
     *
265
     * @param array $types             List of types to search in.
266
     * @param array $query             Query to execute.
267
     * @param array $queryStringParams Query parameters.
268
     *
269
     * @return array
270
     */
271
    public function search(array $types, array $query, array $queryStringParams = [])
272
    {
273
        $params = [];
274
        $params['index'] = $this->getIndexName();
275
        
276
        if (!empty($types)) {
277
            $params['type'] = implode(',', $types);
278
        }
279
        
280
        $params['body'] = $query;
281
282
        if (!empty($queryStringParams)) {
283
            $params = array_merge($queryStringParams, $params);
284
        }
285
286
        $this->stopwatch('start', 'search');
287
        $result = $this->client->search($params);
288
        $this->stopwatch('stop', 'search');
289
290
        return $result;
291
    }
292
293
    /**
294
     * Adds document to next flush.
295
     *
296
     * @param object $document
297
     */
298
    public function persist($document)
299
    {
300
        $documentArray = $this->converter->convertToArray($document);
301
        $type = $this->getMetadataCollector()->getDocumentType(get_class($document));
302
303
        $this->bulk('index', $type, $documentArray);
304
    }
305
306
    /**
307
     * Adds document for removal.
308
     *
309
     * @param object $document
310
     */
311
    public function remove($document)
312
    {
313
        $data = $this->converter->convertToArray($document, [], ['_id', '_routing']);
314
315
        if (!isset($data['_id'])) {
316
            throw new \LogicException(
317
                'In order to use remove() method document class must have property with @Id annotation.'
318
            );
319
        }
320
321
        $type = $this->getMetadataCollector()->getDocumentType(get_class($document));
322
323
        $this->bulk('delete', $type, $data);
324
    }
325
326
    /**
327
     * Flushes elasticsearch index.
328
     *
329
     * @param array $params
330
     *
331
     * @return array
332
     */
333
    public function flush(array $params = [])
334
    {
335
        return $this->client->indices()->flush(array_merge(['index' => $this->getIndexName()], $params));
336
    }
337
338
    /**
339
     * Refreshes elasticsearch index.
340
     *
341
     * @param array $params
342
     *
343
     * @return array
344
     */
345
    public function refresh(array $params = [])
346
    {
347
        return $this->client->indices()->refresh(array_merge(['index' => $this->getIndexName()], $params));
348
    }
349
350
    /**
351
     * Inserts the current query container to the index, used for bulk queries execution.
352
     *
353
     * @param array $params Parameters that will be passed to the flush or refresh queries.
354
     *
355
     * @return null|array
356
     *
357
     * @throws BulkWithErrorsException
358
     */
359
    public function commit(array $params = [])
360
    {
361
        if (!empty($this->bulkQueries)) {
362
            $bulkQueries = array_merge($this->bulkQueries, $this->bulkParams);
363
            $bulkQueries['index']['_index'] = $this->getIndexName();
364
            $this->eventDispatcher->dispatch(
365
                Events::PRE_COMMIT,
366
                new CommitEvent($this->getCommitMode(), $bulkQueries)
367
            );
368
369
            $this->stopwatch('start', 'bulk');
370
            $bulkResponse = $this->client->bulk($bulkQueries);
371
            $this->stopwatch('stop', 'bulk');
372
373
            if ($bulkResponse['errors']) {
374
                throw new BulkWithErrorsException(
375
                    json_encode($bulkResponse),
376
                    0,
377
                    null,
378
                    $bulkResponse
0 ignored issues
show
Documentation introduced by
$bulkResponse is of type callable, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
379
                );
380
            }
381
382
            $this->bulkQueries = [];
383
            $this->bulkCount = 0;
384
385
            $this->stopwatch('start', 'refresh');
386
387
            switch ($this->getCommitMode()) {
388
                case 'flush':
389
                    $this->flush($params);
390
                    break;
391
                case 'refresh':
392
                    $this->refresh($params);
393
                    break;
394
            }
395
396
            $this->eventDispatcher->dispatch(
397
                Events::POST_COMMIT,
398
                new CommitEvent($this->getCommitMode(), $bulkResponse)
0 ignored issues
show
Documentation introduced by
$bulkResponse is of type callable, but the function expects a array|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
399
            );
400
401
            $this->stopwatch('stop', 'refresh');
402
403
            return $bulkResponse;
404
        }
405
406
        return null;
407
    }
408
409
    /**
410
     * Adds query to bulk queries container.
411
     *
412
     * @param string       $operation One of: index, update, delete, create.
413
     * @param string|array $type      Elasticsearch type name.
414
     * @param array        $query     DSL to execute.
415
     *
416
     * @throws \InvalidArgumentException
417
     *
418
     * @return null|array
419
     */
420
    public function bulk($operation, $type, array $query)
421
    {
422
        if (!in_array($operation, ['index', 'create', 'update', 'delete'])) {
423
            throw new \InvalidArgumentException('Wrong bulk operation selected');
424
        }
425
426
        $this->eventDispatcher->dispatch(
427
            Events::BULK,
428
            new BulkEvent($operation, $type, $query)
429
        );
430
431
        $this->bulkQueries['body'][] = [
432
            $operation => array_filter(
433
                [
434
                    '_type' => $type,
435
                    '_id' => isset($query['_id']) ? $query['_id'] : null,
436
                    '_ttl' => isset($query['_ttl']) ? $query['_ttl'] : null,
437
                    '_routing' => isset($query['_routing']) ? $query['_routing'] : null,
438
                    '_parent' => isset($query['_parent']) ? $query['_parent'] : null,
439
                ]
440
            ),
441
        ];
442
        unset($query['_id'], $query['_ttl'], $query['_parent'], $query['_routing']);
443
444
        switch ($operation) {
445
            case 'index':
446
            case 'create':
447
            case 'update':
448
                $this->bulkQueries['body'][] = $query;
449
                break;
450
            case 'delete':
451
                // Body for delete operation is not needed to apply.
452
            default:
453
                // Do nothing.
454
                break;
455
        }
456
457
        // We are using counter because there is to difficult to resolve this from bulkQueries array.
458
        $this->bulkCount++;
459
460
        $response = null;
461
462
        if ($this->bulkCommitSize === $this->bulkCount) {
463
            $response = $this->commit();
464
        }
465
466
        return $response;
467
    }
468
469
    /**
470
     * Optional setter to change bulk query params.
471
     *
472
     * @param array $params Possible keys:
473
     *                      ['consistency'] = (enum) Explicit write consistency setting for the operation.
474
     *                      ['refresh']     = (boolean) Refresh the index after performing the operation.
475
     *                      ['replication'] = (enum) Explicitly set the replication type.
476
     */
477
    public function setBulkParams(array $params)
478
    {
479
        $this->bulkParams = $params;
480
    }
481
482
    /**
483
     * Creates fresh elasticsearch index.
484
     *
485
     * @param bool $noMapping Determines if mapping should be included.
486
     *
487
     * @return array
488
     */
489
    public function createIndex($noMapping = false)
490
    {
491
        if ($noMapping) {
492
            unset($this->indexSettings['body']['mappings']);
493
        }
494
495
        return $this->getClient()->indices()->create($this->indexSettings);
496
    }
497
498
    /**
499
     * Drops elasticsearch index.
500
     */
501
    public function dropIndex()
502
    {
503
        return $this->getClient()->indices()->delete(['index' => $this->getIndexName()]);
504
    }
505
506
    /**
507
     * Tries to drop and create fresh elasticsearch index.
508
     *
509
     * @param bool $noMapping Determines if mapping should be included.
510
     *
511
     * @return array
512
     */
513
    public function dropAndCreateIndex($noMapping = false)
514
    {
515
        try {
516
            $this->dropIndex();
517
        } catch (\Exception $e) {
518
            // Do nothing, our target is to create new index.
519
        }
520
521
        return $this->createIndex($noMapping);
522
    }
523
524
    /**
525
     * Checks if connection index is already created.
526
     *
527
     * @return bool
528
     */
529
    public function indexExists()
530
    {
531
        return $this->getClient()->indices()->exists(['index' => $this->getIndexName()]);
532
    }
533
534
    /**
535
     * Returns index name this connection is attached to.
536
     *
537
     * @return string
538
     */
539
    public function getIndexName()
540
    {
541
        return $this->indexSettings['index'];
542
    }
543
544
    /**
545
     * Sets index name for this connection.
546
     *
547
     * @param string $name
548
     */
549
    public function setIndexName($name)
550
    {
551
        $this->indexSettings['index'] = $name;
552
    }
553
554
    /**
555
     * Returns mappings of the index for this connection.
556
     *
557
     * @return array
558
     */
559
    public function getIndexMappings()
560
    {
561
        return $this->indexSettings['body']['mappings'];
562
    }
563
564
    /**
565
     * Returns Elasticsearch version number.
566
     *
567
     * @return string
568
     */
569
    public function getVersionNumber()
570
    {
571
        return $this->client->info()['version']['number'];
572
    }
573
574
    /**
575
     * Clears elasticsearch client cache.
576
     */
577
    public function clearCache()
578
    {
579
        $this->getClient()->indices()->clearCache(['index' => $this->getIndexName()]);
580
    }
581
582
    /**
583
     * Returns a single document by ID. Returns NULL if document was not found.
584
     *
585
     * @param string $className Document class name or Elasticsearch type name
586
     * @param string $id        Document ID to find
587
     * @param string $routing   Custom routing for the document
588
     *
589
     * @return object
590
     */
591
    public function find($className, $id, $routing = null)
592
    {
593
        $type = $this->resolveTypeName($className);
594
595
        $params = [
596
            'index' => $this->getIndexName(),
597
            'type' => $type,
598
            'id' => $id,
599
        ];
600
601
        if ($routing) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $routing of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
602
            $params['routing'] = $routing;
603
        }
604
605
        try {
606
            $result = $this->getClient()->get($params);
607
        } catch (Missing404Exception $e) {
608
            return null;
609
        }
610
611
        return $this->getConverter()->convertToDocument($result, $this);
0 ignored issues
show
Documentation introduced by
$result is of type callable, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
612
    }
613
614
    /**
615
     * Fetches next set of results.
616
     *
617
     * @param string $scrollId
618
     * @param string $scrollDuration
619
     *
620
     * @return mixed
621
     *
622
     * @throws \Exception
623
     */
624
    public function scroll(
625
        $scrollId,
626
        $scrollDuration = '5m'
627
    ) {
628
        $results = $this->getClient()->scroll(['scroll_id' => $scrollId, 'scroll' => $scrollDuration]);
629
630
        return $results;
631
    }
632
633
    /**
634
     * Clears scroll.
635
     *
636
     * @param string $scrollId
637
     */
638
    public function clearScroll($scrollId)
639
    {
640
        $this->getClient()->clearScroll(['scroll_id' => $scrollId]);
641
    }
642
643
    /**
644
     * Calls "Get Settings API" in Elasticsearch and will return you the currently configured settings.
645
     *
646
     * return array
647
     */
648
    public function getSettings()
649
    {
650
        return $this->getClient()->indices()->getSettings(['index' => $this->getIndexName()]);
651
    }
652
653
    /**
654
     * Gets Elasticsearch aliases information.
655
     * @param $params
656
     *
657
     * @return array
658
     */
659
    public function getAliases($params = [])
660
    {
661
        return $this->getClient()->indices()->getAliases(array_merge(['index' => $this->getIndexName()], $params));
662
    }
663
664
    /**
665
     * Resolves type name by class name.
666
     *
667
     * @param string $className
668
     *
669
     * @return string
670
     */
671
    private function resolveTypeName($className)
672
    {
673
        if (strpos($className, ':') !== false || strpos($className, '\\') !== false) {
674
            return $this->getMetadataCollector()->getDocumentType($className);
675
        }
676
677
        return $className;
678
    }
679
680
    /**
681
     * Starts and stops an event in the stopwatch
682
     *
683
     * @param string $action   only 'start' and 'stop'
684
     * @param string $name     name of the event
685
     */
686
    private function stopwatch($action, $name)
687
    {
688
        if (isset($this->stopwatch)) {
689
            $this->stopwatch->$action('ongr_es: '.$name, 'ongr_es');
690
        }
691
    }
692
}
693