Completed
Push — master ( dfcc9a...242cad )
by Simonas
7s
created

Manager::getConverter()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

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