Completed
Push — master ( dbffe0...b20597 )
by Simonas
03:22
created

Manager   F

Complexity

Total Complexity 80

Size/Duplication

Total Lines 743
Duplicated Lines 0.54 %

Coupling/Cohesion

Components 1
Dependencies 12

Importance

Changes 0
Metric Value
wmc 80
lcom 1
cbo 12
dl 4
loc 743
rs 3.4285
c 0
b 0
f 0

39 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 getRepository() 0 17 3
A getMetadataCollector() 0 4 1
A getConverter() 0 4 1
A getCommitMode() 0 4 1
A getBulkCommitSize() 0 4 1
A setBulkCommitSize() 0 4 1
A createRepository() 0 4 1
A setEventDispatcher() 0 4 1
A setStopwatch() 0 4 1
A setCommitMode() 0 8 4
A search() 0 21 3
A persist() 0 7 1
A remove() 0 14 2
A flush() 0 4 1
A refresh() 0 4 1
B commit() 0 49 5
C bulk() 0 49 11
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 getIndexMappings() 0 4 1
A getVersionNumber() 0 4 1
A clearCache() 0 4 1
A find() 0 22 3
A execute() 0 10 2
B parseResult() 4 21 6
B convertToNormalizedArray() 0 20 6
A scroll() 0 18 2
A clearScroll() 0 4 1
A resolveTypeName() 0 8 3
A stopwatch() 0 6 2

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

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

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...
640
    }
641
642
    /**
643
     * Parses raw result.
644
     *
645
     * @deprecated use strict return type functions from Repository class instead.
646
     *
647
     * @param array  $raw
648
     * @param string $resultsType
649
     * @param string $scrollDuration
650
     *
651
     * @return DocumentIterator|RawIterator|array
652
     *
653
     * @throws \Exception
654
     */
655
    private function parseResult($raw, $resultsType, $scrollDuration = null)
656
    {
657
        $scrollConfig = [];
658 View Code Duplication
        if (isset($raw['_scroll_id'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
659
            $scrollConfig['_scroll_id'] = $raw['_scroll_id'];
660
            $scrollConfig['duration'] = $scrollDuration;
661
        }
662
663
        switch ($resultsType) {
664
            case Result::RESULTS_OBJECT:
665
                return new DocumentIterator($raw, $this, $scrollConfig);
666
            case Result::RESULTS_ARRAY:
667
                return $this->convertToNormalizedArray($raw);
0 ignored issues
show
Deprecated Code introduced by
The method ONGR\ElasticsearchBundle...vertToNormalizedArray() has been deprecated with message: Use ArrayIterator from Result namespace instead.

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...
668
            case Result::RESULTS_RAW:
669
                return $raw;
670
            case Result::RESULTS_RAW_ITERATOR:
671
                return new RawIterator($raw, $this, $scrollConfig);
672
            default:
673
                throw new \Exception('Wrong results type selected');
674
        }
675
    }
676
677
    /**
678
     * Normalizes response array.
679
     *
680
     * @deprecated Use ArrayIterator from Result namespace instead.
681
     *
682
     * @param array $data
683
     *
684
     * @return array
685
     */
686
    private function convertToNormalizedArray($data)
687
    {
688
        if (array_key_exists('_source', $data)) {
689
            return $data['_source'];
690
        }
691
692
        $output = [];
693
694
        if (isset($data['hits']['hits'][0]['_source'])) {
695
            foreach ($data['hits']['hits'] as $item) {
696
                $output[] = $item['_source'];
697
            }
698
        } elseif (isset($data['hits']['hits'][0]['fields'])) {
699
            foreach ($data['hits']['hits'] as $item) {
700
                $output[] = array_map('reset', $item['fields']);
701
            }
702
        }
703
704
        return $output;
705
    }
706
707
    /**
708
     * Fetches next set of results.
709
     *
710
     * @param string $scrollId
711
     * @param string $scrollDuration
712
     * @param string $resultsType
713
     *
714
     * @return mixed
715
     *
716
     * @throws \Exception
717
     */
718
    public function scroll(
719
        $scrollId,
720
        $scrollDuration = '5m',
721
        $resultsType = Result::RESULTS_OBJECT
722
    ) {
723
        $results = $this->getClient()->scroll(['scroll_id' => $scrollId, 'scroll' => $scrollDuration]);
724
725
        if ($resultsType == Result::RESULTS_RAW) {
726
            return $results;
727
        } else {
728
            trigger_error(
729
                '$resultsType parameter was deprecated in scroll() fucntion. ' .
730
                'Use strict type findXXX functions from repository instead. Will be removed in 3.0',
731
                E_USER_DEPRECATED
732
            );
733
            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...
Deprecated Code introduced by
The method ONGR\ElasticsearchBundle...\Manager::parseResult() has been deprecated with message: use strict return type functions from Repository class instead.

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...
734
        }
735
    }
736
737
    /**
738
     * Clears scroll.
739
     *
740
     * @param string $scrollId
741
     */
742
    public function clearScroll($scrollId)
743
    {
744
        $this->getClient()->clearScroll(['scroll_id' => $scrollId]);
745
    }
746
747
    /**
748
     * Resolves type name by class name.
749
     *
750
     * @param string $className
751
     *
752
     * @return string
753
     */
754
    private function resolveTypeName($className)
755
    {
756
        if (strpos($className, ':') !== false || strpos($className, '\\') !== false) {
757
            return $this->getMetadataCollector()->getDocumentType($className);
758
        }
759
760
        return $className;
761
    }
762
763
    /**
764
     * Starts and stops an event in the stopwatch
765
     *
766
     * @param string $action   only 'start' and 'stop'
767
     * @param string $name     name of the event
768
     */
769
    private function stopwatch($action, $name)
770
    {
771
        if (isset($this->stopwatch)) {
772
            $this->stopwatch->$action('ongr_es: '.$name, 'ongr_es');
773
        }
774
    }
775
}
776