Completed
Pull Request — master (#25)
by Alexander
08:45
created

ElasticaExtension   A

Complexity

Total Complexity 17

Size/Duplication

Total Lines 106
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 9

Test Coverage

Coverage 98.39%

Importance

Changes 0
Metric Value
wmc 17
lcom 1
cbo 9
dl 0
loc 106
ccs 61
cts 62
cp 0.9839
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A load() 0 15 1
A loadLogger() 0 12 2
A createLoggerReference() 0 11 2
D loadClients() 0 28 10
A loadClient() 0 14 1
A createClientId() 0 7 1
1
<?php
2
3
namespace GBProd\ElasticaBundle\DependencyInjection;
4
5
use Elastica\Client;
6
use GBProd\ElasticaBundle\Logger\ElasticaLogger;
7
use Symfony\Component\Config\FileLocator;
8
use Symfony\Component\DependencyInjection\ContainerBuilder;
9
use Symfony\Component\DependencyInjection\ContainerInterface;
10
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
11
use Symfony\Component\DependencyInjection\Exception\LogicException;
12
use Symfony\Component\DependencyInjection\Loader;
13
use Symfony\Component\DependencyInjection\Reference;
14
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
15
16
/**
17
 * Extension class for ElasticaExtension
18
 *
19
 * @author gbprod <[email protected]>
20
 */
21
class ElasticaExtension extends Extension
22
{
23
    const CLIENT_ID_TEMPLATE = 'elastica.%s_client';
24
25
    /**
26
     * {@inheritdoc}
27
     */
28 12
    public function load(array $configs, ContainerBuilder $container)
29
    {
30 12
        $configuration = new Configuration();
31 12
        $config = $this->processConfiguration($configuration, $configs);
32
33 12
        $loader = new Loader\YamlFileLoader(
34 12
            $container,
35 12
            new FileLocator(__DIR__ . '/../Resources/config')
36 12
        );
37
38 12
        $loader->load('services.yml');
39
40 12
        $this->loadLogger($config, $container);
41 12
        $this->loadClients($config, $container);
42 10
    }
43
44 12
    private function loadLogger(array $config, ContainerBuilder $container)
45
    {
46
        $definition = $container
47 12
            ->register('elastica.logger', ElasticaLogger::class)
48 12
            ->addArgument($this->createLoggerReference($config))
49 12
            ->addArgument('%kernel.debug%')
50 12
            ->setPublic(true);
51
52 12
        if ('logger' === $config['logger']) {
53 10
            $definition->addTag('monolog.logger', ['channel' => 'elastica']);
54 10
        }
55 12
    }
56
57 12
    private function createLoggerReference(array $config)
58
    {
59 12
        if (null !== $config['logger']) {
60 11
            return new Reference(
61 11
                $config['logger'],
62
                ContainerInterface::IGNORE_ON_INVALID_REFERENCE
63 11
            );
64
        }
65
66 1
        return null;
67
    }
68
69
    /**
70
     * @param array $config
71
     * @param ContainerBuilder $container
72
     * @throws \Symfony\Component\DependencyInjection\Exception\LogicException
73
     * @throws InvalidArgumentException
74
     */
75 12
    private function loadClients(array $config, ContainerBuilder $container)
76
    {
77 12
        foreach ($config['clients'] as $clientName => $clientConfig) {
78 8
            $this->loadClient($clientName, $clientConfig, $container);
79 12
        }
80
        // If container have support for services auto-wiring
81
        // and we have client to define as default - create service alias for auto-wiring
82 12
        if (!method_exists($container, 'autowire')) {
83
            return;
84
        }
85 12
        $defaultClient = $config['default_client'];
86 12
        if ($defaultClient === false) {
87
            // Default client definition is not allowed
88 1
            return;
89
        }
90 11
        if ($defaultClient === null && !empty($config['clients'])) {
91 4
            $defaultClient = key($config['clients']);
92 4
        }
93 11
        if ($defaultClient !== null && !array_key_exists($defaultClient, $config['clients'])) {
94 1
            throw new InvalidArgumentException(sprintf('Invalid default Elasticsearch client is defined: %s', $defaultClient));
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 127 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
95
        }
96 10
        if ($container->hasDefinition(Client::class)) {
97 1
            throw new LogicException('Default Elasticsearch client registration is requested, but client service is already defined in container');
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 147 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
98
        }
99 9
        if ($defaultClient !== null) {
100 5
            $container->setAlias(Client::class, $this->createClientId($defaultClient));
101 5
        }
102 9
    }
103
104 8
    private function loadClient($clientName, array $clientConfig, ContainerBuilder $container)
105
    {
106
        $container
107 8
            ->register($this->createClientId($clientName), Client::class)
108 8
            ->addArgument($clientConfig)
109 8
            ->addMethodCall('setLogger', [
110 8
                new Reference('elastica.logger')
111 8
            ])
112 8
            ->addMethodCall('setConfigValue', [
113 8
                'log',
114 8
                $container->getParameter('kernel.debug')
115 8
            ])
116 8
            ->setPublic(true);
117 8
    }
118
119 8
    private function createClientId($clientName)
120
    {
121 8
        return sprintf(
122 8
            self::CLIENT_ID_TEMPLATE,
123
            $clientName
124 8
        );
125
    }
126
}
127