Completed
Branch 1707_add_explain_command (cbe7fb)
by Alessandro
02:54
created

MongoDbBundleExtension   A

Complexity

Total Complexity 16

Size/Duplication

Total Lines 174
Duplicated Lines 16.67 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 16
lcom 1
cbo 5
dl 29
loc 174
ccs 93
cts 93
cp 1
rs 10
c 0
b 0
f 0

12 Methods

Rating   Name   Duplication   Size   Complexity  
A load() 0 23 2
A mustCollectData() 0 6 3
A defineLoggers() 0 7 1
A defineDataCollector() 0 16 1
A defineClientRegistry() 0 13 1
A defineConnectionFactory() 7 7 1
A defineConnections() 0 15 2
A defineEventManager() 0 7 1
A defineDataCollectorListeners() 12 12 1
A attachDataCollectionListenerToEventManager() 0 18 1
A attachTwigExtesion() 0 8 1
A defineExplainQueryService() 10 10 1

How to fix   Duplicated Code   

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:

1
<?php declare(strict_types = 1);
2
3
namespace Facile\MongoDbBundle\DependencyInjection;
4
5
use Facile\MongoDbBundle\DataCollector\MongoDbDataCollector;
6
use Facile\MongoDbBundle\Event\ConnectionEvent;
7
use Facile\MongoDbBundle\Event\Listener\DataCollectorListener;
8
use Facile\MongoDbBundle\Event\QueryEvent;
9
use Facile\MongoDbBundle\Services\ClientRegistry;
10
use Facile\MongoDbBundle\Services\ConnectionFactory;
11
use Facile\MongoDbBundle\Services\Explain\ExplainQueryService;
12
use Facile\MongoDbBundle\Services\Loggers\MongoQueryLogger;
13
use Facile\MongoDbBundle\Twig\FacileMongoDbBundleExtension;
14
use MongoDB\Database;
15
use Symfony\Bundle\WebProfilerBundle\WebProfilerBundle;
16
use Symfony\Component\DependencyInjection\ContainerBuilder;
17
use Symfony\Component\DependencyInjection\Definition;
18
use Symfony\Component\DependencyInjection\Reference;
19
use Symfony\Component\EventDispatcher\EventDispatcher;
20
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
21
22
/**
23
 * Class MongoDbBundleExtension.
24
 * @internal
25
 */
26
final class MongoDbBundleExtension extends Extension
27
{
28
    /** @var ContainerBuilder */
29
    private $containerBuilder;
30
31
    /**
32
     * {@inheritdoc}
33
     */
34 6
    public function load(array $configs, ContainerBuilder $container)
35
    {
36 6
        $this->containerBuilder = $container;
37 6
        $configuration = new Configuration();
38 6
        $config = $this->processConfiguration($configuration, $configs);
39
40 6
        $this->defineEventManager();
41 6
        $this->defineClientRegistry($config['clients'], $container->getParameter("kernel.environment"));
42 6
        $this->defineConnectionFactory();
43 6
        $this->defineConnections($config['connections']);
44
45 6
        if ($this->mustCollectData($config)) {
46 3
            $this->defineLoggers();
47 3
            $this->defineDataCollectorListeners();
48 3
            $this->attachDataCollectionListenerToEventManager();
49 3
            $this->defineDataCollector();
50 3
            $this->attachTwigExtesion();
51 3
            $this->defineExplainQueryService();
52
        }
53
54
55 6
        return $config;
56
    }
57
58
    /**
59
     * @param array $config
60
     *
61
     * @return bool
62
     */
63 6
    private function mustCollectData(array $config): bool
64
    {
65 6
        return in_array($this->containerBuilder->getParameter("kernel.environment"), ["dev"])
66 6
            && class_exists(WebProfilerBundle::class)
67 6
            && $config['data_collection'] === true;
68
    }
69
70 3
    private function defineLoggers()
71
    {
72 3
        $loggerDefinition = new Definition(MongoQueryLogger::class);
73 3
        $loggerDefinition->setPublic(false);
74
75 3
        $this->containerBuilder->setDefinition('facile_mongo_db.logger', $loggerDefinition);
76 3
    }
77
78 3
    private function defineDataCollector()
79
    {
80 3
        $dataCollectorDefinition = new Definition(MongoDbDataCollector::class);
81 3
        $dataCollectorDefinition->addMethodCall('setLogger', [new Reference('facile_mongo_db.logger')]);
82 3
        $dataCollectorDefinition->addTag(
83 3
            'data_collector',
84
            [
85 3
                'template' => 'FacileMongoDbBundle:Collector:mongo.html.twig',
86
                'id' => 'mongodb',
87
                'priority' => 250,
88
            ]
89
        );
90 3
        $dataCollectorDefinition->setPublic(false);
91
92 3
        $this->containerBuilder->setDefinition('facile_mongo_db.data_collector', $dataCollectorDefinition);
93 3
    }
94
95
    /**
96
     * @param array  $clientsConfig
97
     * @param string $environment
98
     */
99 6
    private function defineClientRegistry(array $clientsConfig, string $environment)
100
    {
101 6
        $clientRegistryDefinition = new Definition(
102 6
            ClientRegistry::class,
103
            [
104 6
                new Reference('facile_mongo_db.event_dispatcher'),
105 6
                $environment,
106
            ]
107
        );
108 6
        $clientRegistryDefinition->addMethodCall('addClientsConfigurations', [$clientsConfig]);
109
110 6
        $this->containerBuilder->setDefinition('mongo.client_registry', $clientRegistryDefinition);
111 6
    }
112
113 6 View Code Duplication
    private function defineConnectionFactory()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
114
    {
115 6
        $factoryDefinition = new Definition(ConnectionFactory::class, [new Reference('mongo.client_registry')]);
116 6
        $factoryDefinition->setPublic(false);
117
118 6
        $this->containerBuilder->setDefinition('mongo.connection_factory', $factoryDefinition);
119 6
    }
120
121
    /**
122
     * @param array $connections
123
     */
124 6
    private function defineConnections(array $connections)
125
    {
126 6
        foreach ($connections as $name => $conf) {
127 6
            $connectionDefinition = new Definition(
128 6
                Database::class,
129
                [
130 6
                    $conf['client_name'],
131 6
                    $conf['database_name'],
132
                ]
133
            );
134 6
            $connectionDefinition->setFactory([new Reference('mongo.connection_factory'), 'createConnection']);
135 6
            $this->containerBuilder->setDefinition('mongo.connection.'.$name, $connectionDefinition);
136
        }
137 6
        $this->containerBuilder->setAlias('mongo.connection', 'mongo.connection.'.array_keys($connections)[0]);
138 6
    }
139
140 6
    private function defineEventManager()
141
    {
142 6
        $eventManagerDefinition = new Definition(EventDispatcher::class);
143 6
        $eventManagerDefinition->setPublic(false);
144
145 6
        $this->containerBuilder->setDefinition('facile_mongo_db.event_dispatcher', $eventManagerDefinition);
146 6
    }
147
148 3 View Code Duplication
    private function defineDataCollectorListeners()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
149
    {
150 3
        $dataCollectorListenerDefinition = new Definition(
151 3
            DataCollectorListener::class,
152
            [
153 3
                new Reference('facile_mongo_db.logger')
154
            ]
155
        );
156 3
        $dataCollectorListenerDefinition->setPublic(false);
157
158 3
        $this->containerBuilder->setDefinition('facile_mongo_db.data_collector.listener', $dataCollectorListenerDefinition);
159 3
    }
160
161 3
    private function attachDataCollectionListenerToEventManager()
162
    {
163 3
        $eventManagerDefinition = $this->containerBuilder->getDefinition('facile_mongo_db.event_dispatcher');
164 3
        $eventManagerDefinition->addMethodCall(
165 3
            'addListener',
166
            [
167 3
                ConnectionEvent::CLIENT_CREATED,
168 3
                [new Reference('facile_mongo_db.data_collector.listener'), 'onConnectionClientCreated']
169
            ]
170
        );
171 3
        $eventManagerDefinition->addMethodCall(
172 3
            'addListener',
173
            [
174 3
                QueryEvent::QUERY_EXECUTED,
175 3
                [new Reference('facile_mongo_db.data_collector.listener'), 'onQueryExecuted']
176
            ]
177
        );
178 3
    }
179
180 3
    private function attachTwigExtesion()
181
    {
182 3
        $extesion = new Definition(FacileMongoDbBundleExtension::class);
183 3
        $extesion->setPublic(false);
184 3
        $extesion->addTag('twig.extension');
185
186 3
        $this->containerBuilder->setDefinition('facile_mongo_db.twig_extesion', $extesion);
187 3
    }
188
189 3 View Code Duplication
    private function defineExplainQueryService()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
190
    {
191 3
        $explainServiceDefinition = new Definition(
192 3
            ExplainQueryService::class,
193 3
            [new Reference('mongo.client_registry')]
194
        );
195 3
        $explainServiceDefinition->setPublic(true);
196
197 3
        $this->containerBuilder->setDefinition('mongo.explain_query_service', $explainServiceDefinition);
198 3
    }
199
}
200