Completed
Pull Request — master (#660)
by
unknown
02:31
created

Manager   D

Complexity

Total Complexity 71

Size/Duplication

Total Lines 661
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 12

Importance

Changes 14
Bugs 0 Features 3
Metric Value
wmc 71
c 14
b 0
f 3
lcom 1
cbo 12
dl 0
loc 661
rs 4.993

36 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 15 1
A getClient() 0 4 1
A getName() 0 4 1
A getConfig() 0 4 1
A setEventDispatcher() 0 4 1
A getRepository() 0 17 3
A getMetadataCollector() 0 4 1
A getConverter() 0 4 1
A getCommitMode() 0 4 1
A setCommitMode() 0 8 4
A getBulkCommitSize() 0 4 1
A setBulkCommitSize() 0 4 1
A createRepository() 0 4 1
A search() 0 13 2
A persist() 0 9 1
A remove() 0 14 2
A flush() 0 4 1
A refresh() 0 4 1
B commit() 0 33 4
C bulk() 0 47 10
A setBulkParams() 0 4 1
A createIndex() 0 8 2
A dropIndex() 0 4 1
A dropAndCreateIndex() 0 10 2
A indexExists() 0 4 1
A getIndexName() 0 4 1
A setIndexName() 0 4 1
A getVersionNumber() 0 4 1
A clearCache() 0 4 1
A find() 0 18 2
A execute() 0 10 2
B parseResult() 0 21 6
B convertToNormalizedArray() 0 20 6
A scroll() 0 9 1
A clearScroll() 0 4 1
A resolveTypeName() 0 8 3

How to fix   Complexity   

Complex Class

Complex classes like Manager often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Manager, and based on these observations, apply Extract Interface, too.

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\PersistEvent;
19
use ONGR\ElasticsearchBundle\Event\CommitEvent;
20
use ONGR\ElasticsearchBundle\Mapping\MetadataCollector;
21
use ONGR\ElasticsearchBundle\Result\AbstractResultsIterator;
22
use ONGR\ElasticsearchBundle\Result\Converter;
23
use ONGR\ElasticsearchBundle\Result\DocumentIterator;
24
use ONGR\ElasticsearchBundle\Result\RawIterator;
25
use ONGR\ElasticsearchBundle\Result\Result;
26
use ONGR\ElasticsearchDSL\Search;
27
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
28
29
/**
30
 * Manager class.
31
 */
32
class Manager
33
{
34
    /**
35
     * @var string Manager name
36
     */
37
    private $name;
38
39
    /**
40
     * @var array Manager configuration
41
     */
42
    private $config = [];
43
44
    /**
45
     * @var Client
46
     */
47
    private $client;
48
49
    /**
50
     * @var Converter
51
     */
52
    private $converter;
53
54
    /**
55
     * @var array Container for bulk queries
56
     */
57
    private $bulkQueries = [];
58
59
    /**
60
     * @var array Holder for consistency, refresh and replication parameters
61
     */
62
    private $bulkParams = [];
63
64
    /**
65
     * @var array
66
     */
67
    private $indexSettings;
68
69
    /**
70
     * @var MetadataCollector
71
     */
72
    private $metadataCollector;
73
74
    /**
75
     * After commit to make data available the refresh or flush operation is needed
76
     * so one of those methods has to be defined, the default is refresh.
77
     *
78
     * @var string
79
     */
80
    private $commitMode = 'refresh';
81
82
    /**
83
     * The size that defines after how much document inserts call commit function.
84
     *
85
     * @var int
86
     */
87
    private $bulkCommitSize = 100;
88
89
    /**
90
     * Container to count how many documents was passed to the bulk query.
91
     *
92
     * @var int
93
     */
94
    private $bulkCount = 0;
95
96
    /**
97
     * @var Repository[] Repository local cache
98
     */
99
    private $repositories;
100
101
    /**
102
     * @var EventDispatcherInterface
103
     */
104
    private $eventDispatcher;
105
106
    /**
107
     * @param string            $name              Manager name
108
     * @param array             $config            Manager configuration
109
     * @param Client            $client
110
     * @param array             $indexSettings
111
     * @param MetadataCollector $metadataCollector
112
     * @param Converter         $converter
113
     */
114
    public function __construct(
115
        $name,
116
        array $config,
117
        $client,
118
        array $indexSettings,
119
        $metadataCollector,
120
        $converter
121
    ) {
122
        $this->name = $name;
123
        $this->config = $config;
124
        $this->client = $client;
125
        $this->indexSettings = $indexSettings;
126
        $this->metadataCollector = $metadataCollector;
127
        $this->converter = $converter;
128
    }
129
130
    /**
131
     * Returns Elasticsearch connection.
132
     *
133
     * @return Client
134
     */
135
    public function getClient()
136
    {
137
        return $this->client;
138
    }
139
140
    /**
141
     * @return string
142
     */
143
    public function getName()
144
    {
145
        return $this->name;
146
    }
147
148
    /**
149
     * @return array
150
     */
151
    public function getConfig()
152
    {
153
        return $this->config;
154
    }
155
156
    /**
157
     * @param EventDispatcherInterface $eventDispatcher
158
     */
159
    public function setEventDispatcher(EventDispatcherInterface $eventDispatcher)
160
    {
161
        $this->eventDispatcher = $eventDispatcher;
162
    }
163
164
    /**
165
     * Returns repository by document class.
166
     *
167
     * @param string $className FQCN or string in Bundle:Document format
168
     *
169
     * @return Repository
170
     */
171
    public function getRepository($className)
172
    {
173
        if (!is_string($className)) {
174
            throw new \InvalidArgumentException('Document class must be a string.');
175
        }
176
177
        $namespace = $this->getMetadataCollector()->getClassName($className);
178
179
        if (isset($this->repositories[$namespace])) {
180
            return $this->repositories[$namespace];
181
        }
182
183
        $repository = $this->createRepository($namespace);
184
        $this->repositories[$namespace] = $repository;
185
186
        return $repository;
187
    }
188
189
    /**
190
     * @return MetadataCollector
191
     */
192
    public function getMetadataCollector()
193
    {
194
        return $this->metadataCollector;
195
    }
196
197
    /**
198
     * @return Converter
199
     */
200
    public function getConverter()
201
    {
202
        return $this->converter;
203
    }
204
205
    /**
206
     * @return string
207
     */
208
    public function getCommitMode()
209
    {
210
        return $this->commitMode;
211
    }
212
213
    /**
214
     * @param string $commitMode
215
     */
216
    public function setCommitMode($commitMode)
217
    {
218
        if ($commitMode === 'refresh' || $commitMode === 'flush' || $commitMode === 'none') {
219
            $this->commitMode = $commitMode;
220
        } else {
221
            throw new \LogicException('The commit method must be either refresh, flush or none.');
222
        }
223
    }
224
225
    /**
226
     * @return int
227
     */
228
    public function getBulkCommitSize()
229
    {
230
        return $this->bulkCommitSize;
231
    }
232
233
    /**
234
     * @param int $bulkCommitSize
235
     */
236
    public function setBulkCommitSize($bulkCommitSize)
237
    {
238
        $this->bulkCommitSize = $bulkCommitSize;
239
    }
240
241
    /**
242
     * Creates a repository.
243
     *
244
     * @param string $className
245
     *
246
     * @return Repository
247
     */
248
    private function createRepository($className)
249
    {
250
        return new Repository($this, $className);
251
    }
252
253
    /**
254
     * Executes search query in the index.
255
     *
256
     * @param array $types             List of types to search in.
257
     * @param array $query             Query to execute.
258
     * @param array $queryStringParams Query parameters.
259
     *
260
     * @return array
261
     */
262
    public function search(array $types, array $query, array $queryStringParams = [])
263
    {
264
        $params = [];
265
        $params['index'] = $this->getIndexName();
266
        $params['type'] = implode(',', $types);
267
        $params['body'] = $query;
268
269
        if (!empty($queryStringParams)) {
270
            $params = array_merge($queryStringParams, $params);
271
        }
272
273
        return $this->client->search($params);
274
    }
275
276
    /**
277
     * Adds document to next flush.
278
     *
279
     * @param object $document
280
     */
281
    public function persist($document)
282
    {
283
        $documentArray = $this->converter->convertToArray($document);
284
        $type = $this->getMetadataCollector()->getDocumentType(get_class($document));
285
286
        $this->eventDispatcher->dispatch(Events::PERSIST, new PersistEvent($document));
287
288
        $this->bulk('index', $type, $documentArray);
289
    }
290
291
    /**
292
     * Adds document for removal.
293
     *
294
     * @param object $document
295
     */
296
    public function remove($document)
297
    {
298
        $data = $this->converter->convertToArray($document, [], ['_id']);
299
300
        if (!isset($data['_id'])) {
301
            throw new \LogicException(
302
                'In order to use remove() method document class must have property with @Id annotation.'
303
            );
304
        }
305
306
        $type = $this->getMetadataCollector()->getDocumentType(get_class($document));
307
308
        $this->bulk('delete', $type, ['_id' => $data['_id']]);
309
    }
310
311
    /**
312
     * Flushes elasticsearch index.
313
     *
314
     * @param array $params
315
     *
316
     * @return array
317
     */
318
    public function flush(array $params = [])
319
    {
320
        return $this->client->indices()->flush(array_merge(['index' => $this->getIndexName()], $params));
321
    }
322
323
    /**
324
     * Refreshes elasticsearch index.
325
     *
326
     * @param array $params
327
     *
328
     * @return array
329
     */
330
    public function refresh(array $params = [])
331
    {
332
        return $this->client->indices()->refresh(array_merge(['index' => $this->getIndexName()], $params));
333
    }
334
335
    /**
336
     * Inserts the current query container to the index, used for bulk queries execution.
337
     *
338
     * @param array $params Parameters that will be passed to the flush or refresh queries.
339
     *
340
     * @return null|array
341
     */
342
    public function commit(array $params = [])
343
    {
344
        if (!empty($this->bulkQueries)) {
345
            $bulkQueries = array_merge($this->bulkQueries, $this->bulkParams);
346
347
            $this->eventDispatcher->dispatch(
348
                Events::PRE_COMMIT,
349
                new CommitEvent($this->getCommitMode(), $bulkQueries)
350
            );
351
352
            $bulkResponse = $this->client->bulk($bulkQueries);
353
            $this->bulkQueries = [];
354
            $this->bulkCount = 0;
355
356
            switch ($this->getCommitMode()) {
357
                case 'flush':
358
                    $this->flush($params);
359
                    break;
360
                case 'refresh':
361
                    $this->refresh($params);
362
                    break;
363
            }
364
365
            $this->eventDispatcher->dispatch(
366
                Events::POST_COMMIT,
367
                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...
368
            );
369
370
            return $bulkResponse;
371
        }
372
373
        return null;
374
    }
375
376
    /**
377
     * Adds query to bulk queries container.
378
     *
379
     * @param string       $operation One of: index, update, delete, create.
380
     * @param string|array $type      Elasticsearch type name.
381
     * @param array        $query     DSL to execute.
382
     *
383
     * @throws \InvalidArgumentException
384
     *
385
     * @return null|array
386
     */
387
    public function bulk($operation, $type, array $query)
388
    {
389
        if (!in_array($operation, ['index', 'create', 'update', 'delete'])) {
390
            throw new \InvalidArgumentException('Wrong bulk operation selected');
391
        }
392
393
        $this->eventDispatcher->dispatch(
394
            Events::BULK,
395
            new BulkEvent($operation, $type, $query)
396
        );
397
398
        $this->bulkQueries['body'][] = [
399
            $operation => array_filter(
400
                [
401
                    '_index' => $this->getIndexName(),
402
                    '_type' => $type,
403
                    '_id' => isset($query['_id']) ? $query['_id'] : null,
404
                    '_ttl' => isset($query['_ttl']) ? $query['_ttl'] : null,
405
                    '_parent' => isset($query['_parent']) ? $query['_parent'] : null,
406
                ]
407
            ),
408
        ];
409
        unset($query['_id'], $query['_ttl'], $query['_parent']);
410
411
        switch ($operation) {
412
            case 'index':
413
            case 'create':
414
            case 'update':
415
                $this->bulkQueries['body'][] = $query;
416
                break;
417
            case 'delete':
418
                // Body for delete operation is not needed to apply.
419
            default:
420
                // Do nothing.
421
                break;
422
        }
423
424
        // We are using counter because there is to difficult to resolve this from bulkQueries array.
425
        $this->bulkCount++;
426
427
        $response = null;
428
        if ($this->bulkCommitSize === $this->bulkCount) {
429
            $response = $this->commit();
430
        }
431
432
        return $response;
433
    }
434
435
    /**
436
     * Optional setter to change bulk query params.
437
     *
438
     * @param array $params Possible keys:
439
     *                      ['consistency'] = (enum) Explicit write consistency setting for the operation.
440
     *                      ['refresh']     = (boolean) Refresh the index after performing the operation.
441
     *                      ['replication'] = (enum) Explicitly set the replication type.
442
     */
443
    public function setBulkParams(array $params)
444
    {
445
        $this->bulkParams = $params;
446
    }
447
448
    /**
449
     * Creates fresh elasticsearch index.
450
     *
451
     * @param bool $noMapping Determines if mapping should be included.
452
     *
453
     * @return array
454
     */
455
    public function createIndex($noMapping = false)
456
    {
457
        if ($noMapping) {
458
            unset($this->indexSettings['body']['mappings']);
459
        }
460
461
        return $this->getClient()->indices()->create($this->indexSettings);
462
    }
463
464
    /**
465
     * Drops elasticsearch index.
466
     */
467
    public function dropIndex()
468
    {
469
        return $this->getClient()->indices()->delete(['index' => $this->getIndexName()]);
470
    }
471
472
    /**
473
     * Tries to drop and create fresh elasticsearch index.
474
     *
475
     * @param bool $noMapping Determines if mapping should be included.
476
     *
477
     * @return array
478
     */
479
    public function dropAndCreateIndex($noMapping = false)
480
    {
481
        try {
482
            $this->dropIndex();
483
        } catch (\Exception $e) {
484
            // Do nothing, our target is to create new index.
485
        }
486
487
        return $this->createIndex($noMapping);
488
    }
489
490
    /**
491
     * Checks if connection index is already created.
492
     *
493
     * @return bool
494
     */
495
    public function indexExists()
496
    {
497
        return $this->getClient()->indices()->exists(['index' => $this->getIndexName()]);
498
    }
499
500
    /**
501
     * Returns index name this connection is attached to.
502
     *
503
     * @return string
504
     */
505
    public function getIndexName()
506
    {
507
        return $this->indexSettings['index'];
508
    }
509
510
    /**
511
     * Sets index name for this connection.
512
     *
513
     * @param string $name
514
     */
515
    public function setIndexName($name)
516
    {
517
        $this->indexSettings['index'] = $name;
518
    }
519
520
    /**
521
     * Returns Elasticsearch version number.
522
     *
523
     * @return string
524
     */
525
    public function getVersionNumber()
526
    {
527
        return $this->client->info()['version']['number'];
528
    }
529
530
    /**
531
     * Clears elasticsearch client cache.
532
     */
533
    public function clearCache()
534
    {
535
        $this->getClient()->indices()->clearCache(['index' => $this->getIndexName()]);
536
    }
537
538
    /**
539
     * Returns a single document by ID. Returns NULL if document was not found.
540
     *
541
     * @param string $className Document class name or Elasticsearch type name
542
     * @param string $id        Document ID to find
543
     *
544
     * @return object
545
     */
546
    public function find($className, $id)
547
    {
548
        $type = $this->resolveTypeName($className);
549
550
        $params = [
551
            'index' => $this->getIndexName(),
552
            'type' => $type,
553
            'id' => $id,
554
        ];
555
556
        try {
557
            $result = $this->getClient()->get($params);
558
        } catch (Missing404Exception $e) {
559
            return null;
560
        }
561
562
        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...
563
    }
564
565
    /**
566
     * Executes given search.
567
     *
568
     * @param array  $types
569
     * @param Search $search
570
     * @param string $resultsType
571
     *
572
     * @return DocumentIterator|RawIterator|array
573
     */
574
    public function execute($types, Search $search, $resultsType = Result::RESULTS_OBJECT)
575
    {
576
        foreach ($types as &$type) {
577
            $type = $this->resolveTypeName($type);
578
        }
579
580
        $results = $this->search($types, $search->toArray(), $search->getQueryParams());
581
582
        return $this->parseResult($results, $resultsType, $search->getScroll());
0 ignored issues
show
Documentation introduced by
$results 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...
583
    }
584
585
    /**
586
     * Parses raw result.
587
     *
588
     * @param array  $raw
589
     * @param string $resultsType
590
     * @param string $scrollDuration
591
     *
592
     * @return DocumentIterator|RawIterator|array
593
     *
594
     * @throws \Exception
595
     */
596
    private function parseResult($raw, $resultsType, $scrollDuration = null)
597
    {
598
        $scrollConfig = [];
599
        if (isset($raw['_scroll_id'])) {
600
            $scrollConfig['_scroll_id'] = $raw['_scroll_id'];
601
            $scrollConfig['duration'] = $scrollDuration;
602
        }
603
604
        switch ($resultsType) {
605
            case Result::RESULTS_OBJECT:
606
                return new DocumentIterator($raw, $this, $scrollConfig);
607
            case Result::RESULTS_ARRAY:
608
                return $this->convertToNormalizedArray($raw);
609
            case Result::RESULTS_RAW:
610
                return $raw;
611
            case Result::RESULTS_RAW_ITERATOR:
612
                return new RawIterator($raw, $this, $scrollConfig);
613
            default:
614
                throw new \Exception('Wrong results type selected');
615
        }
616
    }
617
618
    /**
619
     * Normalizes response array.
620
     *
621
     * @param array $data
622
     *
623
     * @return array
624
     */
625
    private function convertToNormalizedArray($data)
626
    {
627
        if (array_key_exists('_source', $data)) {
628
            return $data['_source'];
629
        }
630
631
        $output = [];
632
633
        if (isset($data['hits']['hits'][0]['_source'])) {
634
            foreach ($data['hits']['hits'] as $item) {
635
                $output[] = $item['_source'];
636
            }
637
        } elseif (isset($data['hits']['hits'][0]['fields'])) {
638
            foreach ($data['hits']['hits'] as $item) {
639
                $output[] = array_map('reset', $item['fields']);
640
            }
641
        }
642
643
        return $output;
644
    }
645
646
    /**
647
     * Fetches next set of results.
648
     *
649
     * @param string $scrollId
650
     * @param string $scrollDuration
651
     * @param string $resultsType
652
     *
653
     * @return AbstractResultsIterator
654
     *
655
     * @throws \Exception
656
     */
657
    public function scroll(
658
        $scrollId,
659
        $scrollDuration = '5m',
660
        $resultsType = Result::RESULTS_OBJECT
661
    ) {
662
        $results = $this->getClient()->scroll(['scroll_id' => $scrollId, 'scroll' => $scrollDuration]);
663
664
        return $this->parseResult($results, $resultsType, $scrollDuration);
0 ignored issues
show
Documentation introduced by
$results 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...
665
    }
666
667
    /**
668
     * Clears scroll.
669
     *
670
     * @param string $scrollId
671
     */
672
    public function clearScroll($scrollId)
673
    {
674
        $this->getClient()->clearScroll(['scroll_id' => $scrollId]);
675
    }
676
677
    /**
678
     * Resolves type name by class name.
679
     *
680
     * @param string $className
681
     *
682
     * @return string
683
     */
684
    private function resolveTypeName($className)
685
    {
686
        if (strpos($className, ':') !== false || strpos($className, '\\') !== false) {
687
            return $this->getMetadataCollector()->getDocumentType($className);
688
        }
689
690
        return $className;
691
    }
692
}
693