Completed
Pull Request — master (#1646)
by Karel
04:11
created

FOSElasticaExtension::load()   B

Complexity

Conditions 8
Paths 33

Size

Total Lines 59

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 35
CRAP Score 8.0101

Importance

Changes 0
Metric Value
dl 0
loc 59
ccs 35
cts 37
cp 0.9459
rs 7.6501
c 0
b 0
f 0
cc 8
nc 33
nop 2
crap 8.0101

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/*
4
 * This file is part of the FOSElasticaBundle package.
5
 *
6
 * (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
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 FOS\ElasticaBundle\DependencyInjection;
13
14
use Elastica\Client as ElasticaClient;
15
use FOS\ElasticaBundle\Elastica\Client;
16
use FOS\ElasticaBundle\Manager\RepositoryManagerInterface;
17
use Symfony\Component\Config\FileLocator;
18
use Symfony\Component\DependencyInjection\Alias;
19
use Symfony\Component\DependencyInjection\ChildDefinition;
20
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
21
use Symfony\Component\DependencyInjection\ContainerBuilder;
22
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
23
use Symfony\Component\DependencyInjection\Reference;
24
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
25
26
class FOSElasticaExtension extends Extension
27
{
28
    /**
29
     * Definition of elastica clients as configured by this extension.
30
     *
31
     * @var array
32
     */
33
    private $clients = [];
34
35
    /**
36
     * An array of indexes as configured by the extension.
37
     *
38
     * @var array
39
     */
40
    private $indexConfigs = [];
41
42
    /**
43
     * An array of index templates as configured by the extension.
44
     *
45
     * @var array
46
     */
47
    private $indexTemplateConfigs = [];
48
49
    /**
50
     * If we've encountered a type mapped to a specific persistence driver, it will be loaded
51
     * here.
52
     *
53
     * @var array
54
     */
55
    private $loadedDrivers = [];
56
57 21
    public function load(array $configs, ContainerBuilder $container)
58
    {
59 21
        $configuration = $this->getConfiguration($configs, $container);
60 21
        $config = $this->processConfiguration($configuration, $configs);
61
62 21
        $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
63
64 21
        if (empty($config['clients']) || empty($config['indexes'])) {
65
            // No Clients or indexes are defined
66
            return;
67
        }
68
69 21
        foreach (['config', 'index', 'persister', 'provider', 'source', 'transformer', 'event_listener', 'commands'] as $basename) {
70 21
            $loader->load(sprintf('%s.xml', $basename));
71
        }
72
73 21
        if (empty($config['default_client'])) {
74 21
            $keys = array_keys($config['clients']);
75 21
            $config['default_client'] = reset($keys);
76
        }
77
78 21
        if (empty($config['default_index'])) {
79 21
            $keys = array_keys($config['indexes']);
80 21
            $config['default_index'] = reset($keys);
81
        }
82
83 21
        if (isset($config['serializer'])) {
84 1
            $loader->load('serializer.xml');
85
86 1
            $this->loadSerializer($config['serializer'], $container);
87
        }
88
89 21
        $this->loadClients($config['clients'], $container);
90 21
        $container->setAlias('fos_elastica.client', sprintf('fos_elastica.client.%s', $config['default_client']));
91 21
        $container->getAlias('fos_elastica.client')->setPublic(true);
92 21
        $container->setAlias(ElasticaClient::class, new Alias('fos_elastica.client', false));
93 21
        $container->setAlias(Client::class, 'fos_elastica.client');
94 21
        $container->getAlias(Client::class)->setPublic(false);
95
96 21
        $this->loadIndexes($config['indexes'], $container);
97 21
        $container->setAlias('fos_elastica.index', sprintf('fos_elastica.index.%s', $config['default_index']));
98 21
        $container->getAlias('fos_elastica.index')->setPublic(true);
99 21
        $container->setParameter('fos_elastica.default_index', $config['default_index']);
100
101 21
        if ($usedIndexNames = \array_intersect_key($config['indexes'], $config['index_templates'])) {
102
            throw new \DomainException(\sprintf('Index names "%s" are already in use and can not be used for index templates names', \implode('","', \array_keys($usedIndexNames))));
103
        }
104 21
        $this->loadIndexTemplates($config['index_templates'], $container);
105
106 21
        $container->getDefinition('fos_elastica.config_source.container')->replaceArgument(0, $this->indexConfigs);
107
        $container
108 21
            ->getDefinition('fos_elastica.config_source.template_container')
109 21
            ->replaceArgument(0, $this->indexTemplateConfigs);
110
111 21
        $this->loadIndexManager($container);
112 21
        $this->loadIndexTemplateManager($container);
113
114 21
        $this->createDefaultManagerAlias($config['default_manager'], $container);
115 21
    }
116
117
    /**
118
     * @return Configuration
119
     */
120 21
    public function getConfiguration(array $config, ContainerBuilder $container)
121
    {
122 21
        return new Configuration($container->getParameter('kernel.debug'));
123
    }
124
125
    /**
126
     * Loads the configured clients.
127
     *
128
     * @param array            $clients   An array of clients configurations
129
     * @param ContainerBuilder $container A ContainerBuilder instance
130
     *
131
     * @return array
132
     */
133 21
    private function loadClients(array $clients, ContainerBuilder $container)
134
    {
135 21
        foreach ($clients as $name => $clientConfig) {
136 21
            $clientId = sprintf('fos_elastica.client.%s', $name);
137
138 21
            $clientDef = new ChildDefinition('fos_elastica.client_prototype');
139 21
            $clientDef->replaceArgument(0, $clientConfig);
140 21
            $clientDef->replaceArgument(1, null);
141
142 21
            $logger = $clientConfig['connections'][0]['logger'];
143 21
            if (false !== $logger) {
144 21
                $clientDef->addMethodCall('setLogger', [new Reference($logger)]);
145
            }
146
147 21
            $clientDef->addTag('fos_elastica.client');
148
149 21
            $container->setDefinition($clientId, $clientDef);
150
151 21
            $this->clients[$name] = [
152 21
                'id' => $clientId,
153 21
                'reference' => new Reference($clientId),
154
            ];
155
        }
156 21
    }
157
158
    /**
159
     * Loads the configured indexes.
160
     *
161
     * @param array            $indexes   An array of indexes configurations
162
     * @param ContainerBuilder $container A ContainerBuilder instance
163
     *
164
     * @throws \InvalidArgumentException
165
     *
166
     * @return array
167
     */
168 21
    private function loadIndexes(array $indexes, ContainerBuilder $container)
169
    {
170 21
        $indexableCallbacks = [];
171
172 21
        foreach ($indexes as $name => $index) {
173 21
            $indexId = sprintf('fos_elastica.index.%s', $name);
174 21
            $indexName = $index['index_name'] ?? $name;
175
176 21
            $indexDef = new ChildDefinition('fos_elastica.index_prototype');
177 21
            $indexDef->setFactory([new Reference('fos_elastica.client'), 'getIndex']);
178 21
            $indexDef->replaceArgument(0, $indexName);
179 21
            $indexDef->addTag('fos_elastica.index', [
180 21
                'name' => $name,
181
            ]);
182
183 21 View Code Duplication
            if (isset($index['client'])) {
184 1
                $client = $this->getClient($index['client']);
185
186 1
                $indexDef->setFactory([$client, 'getIndex']);
187
            }
188
189 21
            $container->setDefinition($indexId, $indexDef);
190 21
            $reference = new Reference($indexId);
191
192 21
            $this->indexConfigs[$name] = [
193 21
                'elasticsearch_name' => $indexName,
194 21
                'reference' => $reference,
195 21
                'model' => $index['persistence']['model'] ?? null,
196 21
                'name' => $name,
197 21
                'settings' => $index['settings'],
198 21
                'index_prototype' => $index['index_prototype'] ?? [],
199 21
                'use_alias' => $index['use_alias'],
200
            ];
201
202 21
            if ($index['finder']) {
203
                $this->loadIndexFinder($container, $name, $reference);
204
            }
205
206 21
            $this->loadIndexConfig((array) $index, $this->indexConfigs[$name]);
207
208 21
            if (isset($index['indexable_callback'])) {
209 4
                $indexableCallbacks[$name] = $this->buildCallback($index['indexable_callback'], $name);
210
            }
211
212 21
            $this->loadIndexSerializerIntegration($index['serializer'] ?? [], $container, $reference);
213
214 21
            if (isset($index['persistence'])) {
215 15
                $this->loadIndexPersistenceIntegration($index['persistence'], $container, $reference, $name);
216
            }
217
        }
218
219 21
        $indexable = $container->getDefinition('fos_elastica.indexable');
220 21
        $indexable->replaceArgument(0, $indexableCallbacks);
221 21
    }
222
223
    /**
224
     * Loads the configured indexes.
225
     *
226
     * @param array            $indexTemplates An array of indexes configurations
227
     * @param ContainerBuilder $container      A ContainerBuilder instance
228
     *
229
     * @throws \InvalidArgumentException
230
     *
231
     * @return void
232
     */
233 21
    private function loadIndexTemplates(array $indexTemplates, ContainerBuilder $container)
234
    {
235 21
        foreach ($indexTemplates as $name => $indexTemplate) {
236 6
            $indexId = sprintf('fos_elastica.index_template.%s', $name);
237 6
            $indexTemplateName = $indexTemplate['template_name'] ?? $name;
238
239 6
            $indexDef = new ChildDefinition('fos_elastica.index_template_prototype');
240 6
            $indexDef->setFactory([new Reference('fos_elastica.client'), 'getIndexTemplate']);
241 6
            $indexDef->replaceArgument(0, $indexTemplateName);
242 6
            $indexDef->addTag('fos_elastica.index_template', [
243 6
                'name' => $name,
244
            ]);
245
246 6 View Code Duplication
            if (isset($indexTemplate['client'])) {
247 6
                $client = $this->getClient($indexTemplate['client']);
248 6
                $indexDef->setFactory([$client, 'getIndexTemplate']);
249
            }
250
251 6
            $container->setDefinition($indexId, $indexDef);
252 6
            $reference = new Reference($indexId);
253
254 6
            $this->indexTemplateConfigs[$name] = [
255 6
                'elasticsearch_name' => $indexTemplateName,
256 6
                'reference' => $reference,
257 6
                'name' => $name,
258 6
                'settings' => $indexTemplate['settings'],
259 6
                'template' => $indexTemplate['template'],
260
            ];
261
262 6
            $this->loadIndexConfig((array) $indexTemplate, $this->indexTemplateConfigs[$name]);
263
        }
264 21
    }
265
266
    /**
267
     * Loads the configured index finders.
268
     *
269
     * @param string    $name  The index name
270
     * @param Reference $index Reference to the related index
271
     *
272
     * @return string
273
     */
274
    private function loadIndexFinder(ContainerBuilder $container, string $name, Reference $index): void
275
    {
276
        $finderId = sprintf('fos_elastica.finder.%s', $name);
277
        $finderDef = new ChildDefinition('fos_elastica.finder');
278
        $finderDef->replaceArgument(0, $index);
279
        $finderDef->replaceArgument(1, new Reference(sprintf('fos_elastica.elastica_to_model_transformer.%s', $name)));
280
281
        $container->setDefinition($finderId, $finderDef);
282
    }
283
284
    /**
285
     * Loads the configured $index.
286
     */
287 21
    private function loadIndexConfig(array $index, array &$indexConfig): void
288
    {
289 21
        $indexConfig = array_merge($indexConfig, [
290 21
            'mapping' => [], // An array containing anything that gets sent directly to ElasticSearch
291
            'config' => [],
292
        ]);
293
294
        foreach ([
295 21
            'dynamic_templates',
296
            'properties',
297
            '_id',
298
            '_routing',
299
            '_source',
300
        ] as $field) {
301 21
            if (isset($index[$field])) {
302 21
                $indexConfig['mapping'][$field] = $index[$field];
303
            }
304
        }
305
306
        foreach ([
307 21
            'analyzer',
308
            'search_analyzer',
309
            'dynamic',
310
            'date_detection',
311
            'dynamic_date_formats',
312
            'numeric_detection',
313
        ] as $field) {
314 21
            $indexConfig['config'][$field] = array_key_exists($field, $index) ? $index[$field] : null;
315
        }
316 21
    }
317
318 4
    private function buildCallback($indexCallback, $indexName)
319
    {
320 4
        if (is_array($indexCallback)) {
321 4
            if (!isset($indexCallback[0])) {
322
                throw new \InvalidArgumentException(sprintf('Invalid indexable_callback for index %s', $indexName));
323
            }
324
325 4
            $classOrServiceRef = $this->transformServiceReference($indexCallback[0]);
326 4
            if ($classOrServiceRef instanceof Reference && !isset($indexCallback[1])) {
327
                return $classOrServiceRef; // __invoke
328
            }
329
330 4
            if (!isset($indexCallback[1])) {
331
                throw new \InvalidArgumentException(sprintf('Invalid indexable_callback for index %s', $indexName));
332
            }
333
334 4
            return [$classOrServiceRef, $indexCallback[1]];
335
        }
336
337 4
        if (is_string($indexCallback)) {
338 4
            return $this->transformServiceReference($indexCallback);
339
        }
340
341
        throw new \InvalidArgumentException(sprintf('Invalid indexable_callback for index %s', $indexName));
342
    }
343
344 4
    private function transformServiceReference($classOrService)
345
    {
346 4
        return 0 === strpos($classOrService, '@') ? new Reference(substr($classOrService, 1)) : $classOrService;
347
    }
348
349 21
    private function loadIndexSerializerIntegration(array $config, ContainerBuilder $container, Reference $indexRef): void
350
    {
351 21
        if ($container->hasDefinition('fos_elastica.serializer_callback_prototype')) {
352 1
            $indexSerializerId = sprintf('%s.serializer.callback', $indexRef);
353 1
            $indexSerializerDef = new ChildDefinition('fos_elastica.serializer_callback_prototype');
354
355 1
            if (isset($config['groups'])) {
356 1
                $indexSerializerDef->addMethodCall('setGroups', [$config['groups']]);
357
            }
358
359 1
            if (isset($config['serialize_null'])) {
360 1
                $indexSerializerDef->addMethodCall('setSerializeNull', [$config['serialize_null']]);
361
            }
362
363 1
            if (isset($config['version'])) {
364 1
                $indexSerializerDef->addMethodCall('setVersion', [$config['version']]);
365
            }
366
367 1
            $container->setDefinition($indexSerializerId, $indexSerializerDef);
368
        }
369 21
    }
370
371
    /**
372
     * Loads the optional provider and finder for a type.
373
     */
374 15
    private function loadIndexPersistenceIntegration(array $config, ContainerBuilder $container, Reference $indexRef, string $indexName): void
375
    {
376 15
        if (isset($config['driver'])) {
377 15
            $this->loadDriver($container, $config['driver']);
378
        }
379
380 15
        $elasticaToModelTransformerId = $this->loadElasticaToModelTransformer($config, $container, $indexName);
381 15
        $modelToElasticaTransformerId = $this->loadModelToElasticaTransformer($config, $container, $indexName);
382 15
        $objectPersisterId = $this->loadObjectPersister($config, $indexRef, $container, $indexName, $modelToElasticaTransformerId);
383
384 15
        if (isset($config['provider'])) {
385 15
            $this->loadIndexPagerProvider($config, $container, $indexName);
386
        }
387 15
        if (isset($config['finder'])) {
388 15
            $this->loadTypeFinder($config, $container, $elasticaToModelTransformerId, $indexRef, $indexName);
389
        }
390 15
        if (isset($config['listener']) && $config['listener']['enabled']) {
391 14
            $this->loadIndexListener($config, $container, $objectPersisterId, $indexName);
392
        }
393 15
    }
394
395
    /**
396
     * Creates and loads an ElasticaToModelTransformer.
397
     */
398 15
    private function loadElasticaToModelTransformer(array $persistenceConfig, ContainerBuilder $container, string $indexName): string
399
    {
400 15
        if (isset($persistenceConfig['elastica_to_model_transformer']['service'])) {
401 1
            return $persistenceConfig['elastica_to_model_transformer']['service'];
402
        }
403
404
        /* Note: transformer services may conflict with "prototype.driver", if
405
         * the index and type names were "prototype" and a driver, respectively.
406
         */
407 14
        $abstractId = sprintf('fos_elastica.elastica_to_model_transformer.prototype.%s', $persistenceConfig['driver']);
408 14
        $serviceId = sprintf('fos_elastica.elastica_to_model_transformer.%s', $indexName);
409 14
        $serviceDef = new ChildDefinition($abstractId);
410 14
        $serviceDef->addTag('fos_elastica.elastica_to_model_transformer', ['index' => $indexName]);
411
412 14
        $serviceDef->replaceArgument(1, $persistenceConfig['model']);
413 14
        $serviceDef->replaceArgument(2, array_merge($persistenceConfig['elastica_to_model_transformer'], [
414 14
            'identifier' => $persistenceConfig['identifier'],
415
        ]));
416 14
        $container->setDefinition($serviceId, $serviceDef);
417
418 14
        return $serviceId;
419
    }
420
421
    /**
422
     * Creates and loads a ModelToElasticaTransformer for an index.
423
     */
424 15
    private function loadModelToElasticaTransformer(array $config, ContainerBuilder $container, string $indexName): string
425
    {
426 15
        if (isset($config['model_to_elastica_transformer']['service'])) {
427
            return $config['model_to_elastica_transformer']['service'];
428
        }
429
430 15
        $abstractId = $container->hasDefinition('fos_elastica.serializer_callback_prototype') ?
431 1
            'fos_elastica.model_to_elastica_identifier_transformer' :
432 15
            'fos_elastica.model_to_elastica_transformer';
433
434 15
        $serviceId = sprintf('fos_elastica.model_to_elastica_transformer.%s', $indexName);
435 15
        $serviceDef = new ChildDefinition($abstractId);
436 15
        $serviceDef->replaceArgument(0, [
437 15
            'identifier' => $config['identifier'],
438 15
            'index' => $indexName,
439
        ]);
440 15
        $container->setDefinition($serviceId, $serviceDef);
441
442 15
        return $serviceId;
443
    }
444
445
    /**
446
     * Creates and loads an object persister for a index.
447
     */
448 15
    private function loadObjectPersister(array $config, Reference $indexRef, ContainerBuilder $container, string $indexName, string $transformerId): string
449
    {
450 15
        if (isset($config['persister']['service'])) {
451 1
            return $config['persister']['service'];
452
        }
453
454
        $arguments = [
455 14
            $indexRef,
456 14
            new Reference($transformerId),
457 14
            $config['model'],
458
        ];
459
460 14
        if ($container->hasDefinition('fos_elastica.serializer_callback_prototype')) {
461 1
            $abstractId = 'fos_elastica.object_serializer_persister';
462 1
            $callbackId = sprintf('%s.serializer.callback', $indexRef);
463 1
            $arguments[] = [new Reference($callbackId), 'serialize'];
464
        } else {
465 13
            $abstractId = 'fos_elastica.object_persister';
466 13
            $mapping = $this->indexConfigs[$indexName]['mapping'];
467 13
            $argument = $mapping['properties'];
468 13
            $arguments[] = $argument;
469
        }
470
471 14
        $arguments[] = array_intersect_key($config['persister'], array_flip(['refresh']));
472
473 14
        $serviceId = sprintf('fos_elastica.object_persister.%s', $indexName);
474 14
        $serviceDef = new ChildDefinition($abstractId);
475 14
        foreach ($arguments as $i => $argument) {
476 14
            $serviceDef->replaceArgument($i, $argument);
477
        }
478
479 14
        $serviceDef->addTag('fos_elastica.persister', ['index' => $indexName]);
480
481 14
        $container->setDefinition($serviceId, $serviceDef);
482
483 14
        return $serviceId;
484
    }
485
486
    /**
487
     * Loads a pager provider for a index.
488
     */
489 15
    private function loadIndexPagerProvider(array $indexConfig, ContainerBuilder $container, string $indexName): string
490
    {
491 15
        if (isset($indexConfig['provider']['service'])) {
492
            return $indexConfig['provider']['service'];
493
        }
494
495 15
        $baseConfig = $indexConfig['provider'];
496 15
        unset($baseConfig['service']);
497
498 15
        $driver = $indexConfig['driver'];
499
500 15
        switch ($driver) {
501 15
            case 'orm':
502 2
            case 'mongodb':
503 1
            case 'phpcr':
504 15
                $providerDef = new ChildDefinition('fos_elastica.pager_provider.prototype.'.$driver);
505 15
                $providerDef->replaceArgument(2, $indexConfig['model']);
506 15
                $providerDef->replaceArgument(3, $baseConfig);
507 15
                break;
508
            default:
509
                throw new \LogicException(sprintf('The pager provider for driver "%s" does not exist.', $driver));
510
        }
511
512
        /* Note: provider services may conflict with "prototype.driver", if the
513
         * index and type names were "prototype" and a driver, respectively.
514
         */
515 15
        $providerId = sprintf('fos_elastica.pager_provider.%s', $indexName);
516 15
        $providerDef->addTag('fos_elastica.pager_provider', ['index' => $indexName]);
517
518 15
        $container->setDefinition($providerId, $providerDef);
519
520 15
        return $providerId;
521
    }
522
523
    /**
524
     * Loads doctrine listeners to handle indexing of new or updated objects.
525
     */
526 14
    private function loadIndexListener(array $indexConfig, ContainerBuilder $container, string $objectPersisterId, string $indexName): string
527
    {
528 14
        if (isset($indexConfig['listener']['service'])) {
529
            return $indexConfig['listener']['service'];
530
        }
531
532
        /* Note: listener services may conflict with "prototype.driver", if the
533
         * index names were "prototype" and a driver, respectively.
534
         */
535 14
        $abstractListenerId = sprintf('fos_elastica.listener.prototype.%s', $indexConfig['driver']);
536 14
        $listenerId = sprintf('fos_elastica.listener.%s', $indexName);
537 14
        $listenerDef = new ChildDefinition($abstractListenerId);
538 14
        $listenerDef->replaceArgument(0, new Reference($objectPersisterId));
539 14
        $listenerDef->replaceArgument(3, $indexConfig['listener']['logger'] ?
540
            new Reference($indexConfig['listener']['logger']) :
541 14
            null
542
        );
543
        $listenerConfig = [
544 14
            'identifier' => $indexConfig['identifier'],
545 14
            'indexName' => $indexName,
546
        ];
547
548 14
        $tagName = null;
549 14
        switch ($indexConfig['driver']) {
550 14
            case 'orm':
551 12
                $tagName = 'doctrine.event_listener';
552 12
                break;
553 2
            case 'phpcr':
554 1
                $tagName = 'doctrine_phpcr.event_listener';
555 1
                break;
556 1
            case 'mongodb':
557 1
                $tagName = 'doctrine_mongodb.odm.event_listener';
558 1
                break;
559
        }
560
561 14
        if ($indexConfig['listener']['defer']) {
562
            $listenerDef->setPublic(true);
563
            $listenerDef->addTag(
564
                'kernel.event_listener',
565
                ['event' => 'kernel.terminate', 'method' => 'onTerminate']
566
            );
567
            $listenerDef->addTag(
568
                'kernel.event_listener',
569
                ['event' => 'console.terminate', 'method' => 'onTerminate']
570
            );
571
            $listenerConfig['defer'] = true;
572
        }
573
574 14
        $listenerDef->replaceArgument(2, $listenerConfig);
575
576 14
        if (null !== $tagName) {
577 14
            foreach ($this->getDoctrineEvents($indexConfig) as $event) {
578 14
                $listenerDef->addTag($tagName, ['event' => $event]);
579
            }
580
        }
581
582 14
        $container->setDefinition($listenerId, $listenerDef);
583
584 14
        return $listenerId;
585
    }
586
587
    /**
588
     * Map Elastica to Doctrine events for the current driver.
589
     */
590 14
    private function getDoctrineEvents(array $indexConfig)
591
    {
592 14
        switch ($indexConfig['driver']) {
593 14
            case 'orm':
594 12
                $eventsClass = '\Doctrine\ORM\Events';
595 12
                break;
596 2
            case 'phpcr':
597 1
                $eventsClass = '\Doctrine\ODM\PHPCR\Event';
598 1
                break;
599 1
            case 'mongodb':
600 1
                $eventsClass = '\Doctrine\ODM\MongoDB\Events';
601 1
                break;
602
            default:
603
                throw new \InvalidArgumentException(sprintf('Cannot determine events for driver "%s"', $indexConfig['driver']));
604
        }
605
606 14
        $events = [];
607
        $eventMapping = [
608 14
            'insert' => [constant($eventsClass.'::postPersist')],
609 14
            'update' => [constant($eventsClass.'::postUpdate')],
610 14
            'delete' => [constant($eventsClass.'::preRemove')],
611 14
            'flush' => [constant($eventsClass.'::postFlush')],
612
        ];
613
614 14
        foreach ($eventMapping as $event => $doctrineEvents) {
615 14
            if (isset($indexConfig['listener'][$event]) && $indexConfig['listener'][$event]) {
616 14
                $events = array_merge($events, $doctrineEvents);
617
            }
618
        }
619
620 14
        return $events;
621
    }
622
623
    /**
624
     * Loads a Type specific Finder.
625
     */
626 15
    private function loadTypeFinder(array $typeConfig, ContainerBuilder $container, string $elasticaToModelId, Reference $indexRef, string $indexName): string
627
    {
628 15
        if (isset($typeConfig['finder']['service'])) {
629
            $finderId = $typeConfig['finder']['service'];
630
        } else {
631 15
            $finderId = sprintf('fos_elastica.finder.%s', $indexName);
632 15
            $finderDef = new ChildDefinition('fos_elastica.finder');
633 15
            $finderDef->replaceArgument(0, $indexRef);
634 15
            $finderDef->replaceArgument(1, new Reference($elasticaToModelId));
635 15
            $container->setDefinition($finderId, $finderDef);
636
        }
637
638 15
        $arguments = [$indexName, new Reference($finderId)];
639 15
        if (isset($typeConfig['repository'])) {
640 4
            $arguments[] = $typeConfig['repository'];
641
        }
642
643 15
        $container->getDefinition('fos_elastica.repository_manager')
644 15
            ->addMethodCall('addIndex', $arguments);
645
646 15
        $managerId = sprintf('fos_elastica.manager.%s', $typeConfig['driver']);
647 15
        $container->getDefinition($managerId)
648 15
            ->addMethodCall('addEntity', [$typeConfig['model'], $indexName]);
649
650 15
        return $finderId;
651
    }
652
653
    /**
654
     * Loads the index manager.
655
     **/
656 21 View Code Duplication
    private function loadIndexManager(ContainerBuilder $container): void
657
    {
658
        $indexRefs = array_map(function ($index) {
659 21
            return $index['reference'];
660 21
        }, $this->indexConfigs);
661
662 21
        $managerDef = $container->getDefinition('fos_elastica.index_manager');
663 21
        $managerDef->replaceArgument(0, $indexRefs);
664 21
    }
665
666
    /**
667
     * Load index template manager.
668
     */
669 21 View Code Duplication
    private function loadIndexTemplateManager(ContainerBuilder $container): void
670
    {
671
        $indexTemplateRefs = array_map(function ($index) {
672 6
            return $index['reference'];
673 21
        }, $this->indexTemplateConfigs);
674
675 21
        $managerDef = $container->getDefinition('fos_elastica.index_template_manager');
676 21
        $managerDef->replaceArgument(0, $indexTemplateRefs);
677 21
    }
678
679
    /**
680
     * Makes sure a specific driver has been loaded.
681
     */
682 15
    private function loadDriver(ContainerBuilder $container, string $driver): void
683
    {
684 15
        if (in_array($driver, $this->loadedDrivers, true)) {
685 5
            return;
686
        }
687
688 15
        $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
689 15
        $loader->load($driver.'.xml');
690 15
        $this->loadedDrivers[] = $driver;
691 15
    }
692
693
    /**
694
     * Loads and configures the serializer prototype.
695
     */
696 1
    private function loadSerializer(array $config, ContainerBuilder $container): void
697
    {
698 1
        $container->setAlias('fos_elastica.serializer', $config['serializer']);
699
700 1
        $serializer = $container->getDefinition('fos_elastica.serializer_callback_prototype');
701 1
        $serializer->setClass($config['callback_class']);
702
703 1
        if (is_subclass_of($config['callback_class'], ContainerAwareInterface::class)) {
0 ignored issues
show
Bug introduced by
Due to PHP Bug #53727, is_subclass_of might return inconsistent results on some PHP versions if \Symfony\Component\Depen...erAwareInterface::class can be an interface. If so, you could instead use ReflectionClass::implementsInterface.
Loading history...
704
            $serializer->addMethodCall('setContainer', [new Reference('service_container')]);
705
        }
706 1
    }
707
708
    /**
709
     * Creates a default manager alias for defined default manager or the first loaded driver.
710
     */
711 21
    private function createDefaultManagerAlias(string $defaultManager, ContainerBuilder $container): void
712
    {
713 21
        if (0 == count($this->loadedDrivers)) {
714 6
            return;
715
        }
716
717 15
        if (count($this->loadedDrivers) > 1
718 15
            && in_array($defaultManager, $this->loadedDrivers, true)
719
        ) {
720
            $defaultManagerService = $defaultManager;
721
        } else {
722 15
            $defaultManagerService = $this->loadedDrivers[0];
723
        }
724
725 15
        $container->setAlias('fos_elastica.manager', sprintf('fos_elastica.manager.%s', $defaultManagerService));
726 15
        $container->getAlias('fos_elastica.manager')->setPublic(true);
727 15
        $container->setAlias(RepositoryManagerInterface::class, 'fos_elastica.manager');
728 15
        $container->getAlias(RepositoryManagerInterface::class)->setPublic(false);
729 15
    }
730
731
    /**
732
     * Returns a reference to a client given its configured name.
733
     *
734
     * @throws \InvalidArgumentException
735
     */
736 7
    private function getClient(string $clientName): Reference
737
    {
738 7
        if (!array_key_exists($clientName, $this->clients)) {
739
            throw new \InvalidArgumentException(sprintf('The elastica client with name "%s" is not defined', $clientName));
740
        }
741
742 7
        return $this->clients[$clientName]['reference'];
743
    }
744
}
745