Completed
Pull Request — master (#25)
by Alexander
07:52 queued 42s
created

ElasticaExtension::loadClients()   D

Complexity

Conditions 10
Paths 20

Size

Total Lines 28
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 10

Importance

Changes 0
Metric Value
dl 0
loc 28
ccs 16
cts 16
cp 1
rs 4.8196
c 0
b 0
f 0
cc 10
eloc 16
nc 20
nop 2
crap 10

How to fix   Complexity   

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
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 6
     * {@inheritdoc}
27
     */
28 6
    public function load(array $configs, ContainerBuilder $container)
29 6
    {
30
        $configuration = new Configuration();
31 6
        $config = $this->processConfiguration($configuration, $configs);
32 6
33 6
        $loader = new Loader\YamlFileLoader(
34 6
            $container,
35
            new FileLocator(__DIR__ . '/../Resources/config')
36 6
        );
37
38 6
        $loader->load('services.yml');
39 6
40 6
        $this->loadLogger($config, $container);
41
        $this->loadClients($config, $container);
42 6
    }
43
44
    private function loadLogger(array $config, ContainerBuilder $container)
45 6
    {
46 6
        $definition = $container
47 6
            ->register('elastica.logger', ElasticaLogger::class)
48 6
            ->addArgument($this->createLoggerReference($config))
49 6
            ->addArgument('%kernel.debug%')
50
            ->setPublic(true);
51 6
52 4
        if ('logger' === $config['logger']) {
53 4
            $definition->addTag('monolog.logger', ['channel' => 'elastica']);
54 6
        }
55
    }
56 6
57
    private function createLoggerReference(array $config)
58 6
    {
59 5
        if (null !== $config['logger']) {
60 5
            return new Reference(
61
                $config['logger'],
62 5
                ContainerInterface::IGNORE_ON_INVALID_REFERENCE
63
            );
64
        }
65 1
66
        return null;
67
    }
68 6
69
    /**
70 6
     * @param array $config
71 2
     * @param ContainerBuilder $container
72 6
     * @throws \Symfony\Component\DependencyInjection\Exception\LogicException
73 6
     * @throws InvalidArgumentException
74
     */
75 2
    private function loadClients(array $config, ContainerBuilder $container)
76
    {
77
        foreach ($config['clients'] as $clientName => $clientConfig) {
78 2
            $this->loadClient($clientName, $clientConfig, $container);
79 2
        }
80 2
        // If container have support for services auto-wiring
81 2
        // and we have client to define as default - create service alias for auto-wiring
82 2
        if (!method_exists($container, 'autowire')) {
83 2
            return;
84 2
        }
85 2
        $defaultClient = $config['default_client'];
86 2
        if ($defaultClient === false) {
87 2
            // Default client definition is not allowed
88
            return;
89 2
        }
90
        if ($defaultClient === null && !empty($config['clients'])) {
91 2
            $defaultClient = key($config['clients']);
92
        }
93 2
        if ($defaultClient !== null && !array_key_exists($defaultClient, $config['clients'])) {
94 2
            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 2
        if ($container->hasDefinition(Client::class)) {
97
            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
        if ($defaultClient !== null) {
100
            $container->setAlias(Client::class, $this->createClientId($defaultClient));
101
        }
102
    }
103
104
    private function loadClient($clientName, array $clientConfig, ContainerBuilder $container)
105
    {
106
        $container
107
            ->register($this->createClientId($clientName), Client::class)
108
            ->addArgument($clientConfig)
109
            ->addMethodCall('setLogger', [
110
                new Reference('elastica.logger')
111
            ])
112
            ->addMethodCall('setConfigValue', [
113
                'log',
114
                $container->getParameter('kernel.debug')
115
            ])
116
            ->setPublic(true);
117
    }
118
119
    private function createClientId($clientName)
120
    {
121
        return sprintf(
122
            self::CLIENT_ID_TEMPLATE,
123
            $clientName
124
        );
125
    }
126
}
127