Completed
Branch 1707_add_explain_command (902dba)
by Alessandro
06:37
created

defineExplainQueryService()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 6

Duplication

Lines 10
Ratio 100 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 10
loc 10
ccs 0
cts 0
cp 0
rs 9.4285
cc 1
eloc 6
nc 1
nop 0
crap 2
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 5
     */
34
    public function load(array $configs, ContainerBuilder $container)
35 5
    {
36 5
        $this->containerBuilder = $container;
37 5
        $configuration = new Configuration();
38
        $config = $this->processConfiguration($configuration, $configs);
39 5
40 5
        $this->defineEventManager();
41 5
        $this->defineClientRegistry($config['clients'], $container->getParameter("kernel.environment"));
42 5
        $this->defineConnectionFactory();
43
        $this->defineConnections($config['connections']);
44 5
45 2
        if ($this->mustCollectData($config)) {
46 2
            $this->defineLoggers();
47 2
            $this->defineDataCollectorListeners();
48 2
            $this->attachDataCollectionListenerToEventManager();
49 2
            $this->defineDataCollector();
50
            $this->attachTwigExtesion();
51
            $this->defineExplainQueryService();
52 5
        }
53
54
55
        return $config;
56
    }
57
58
    /**
59
     * @param array $config
60 5
     *
61
     * @return bool
62 5
     */
63 5
    private function mustCollectData(array $config): bool
64 5
    {
65
        return in_array($this->containerBuilder->getParameter("kernel.environment"), ["dev"])
66
            && class_exists(WebProfilerBundle::class)
67 2
            && $config['data_collection'] === true;
68
    }
69 2
70 2
    private function defineLoggers()
71
    {
72 2
        $loggerDefinition = new Definition(MongoQueryLogger::class);
73 2
        $loggerDefinition->setPublic(false);
74
75 2
        $this->containerBuilder->setDefinition('facile_mongo_db.logger', $loggerDefinition);
76
    }
77 2
78 2
    private function defineDataCollector()
79 2
    {
80 2
        $dataCollectorDefinition = new Definition(MongoDbDataCollector::class);
81
        $dataCollectorDefinition->addMethodCall('setLogger', [new Reference('facile_mongo_db.logger')]);
82 2
        $dataCollectorDefinition->addTag(
83
            'data_collector',
84
            [
85
                'template' => 'FacileMongoDbBundle:Collector:mongo.html.twig',
86
                'id' => 'mongodb',
87 2
                'priority' => 250,
88
            ]
89 2
        );
90 2
        $dataCollectorDefinition->setPublic(false);
91
92
        $this->containerBuilder->setDefinition('facile_mongo_db.data_collector', $dataCollectorDefinition);
93
    }
94
95
    /**
96 5
     * @param array  $clientsConfig
97
     * @param string $environment
98 5
     */
99 5
    private function defineClientRegistry(array $clientsConfig, string $environment)
100
    {
101 5
        $clientRegistryDefinition = new Definition(
102 5
            ClientRegistry::class,
103
            [
104
                new Reference('facile_mongo_db.event_dispatcher'),
105 5
                $environment,
106
            ]
107 5
        );
108 5
        $clientRegistryDefinition->addMethodCall('addClientsConfigurations', [$clientsConfig]);
109
110 5
        $this->containerBuilder->setDefinition('mongo.client_registry', $clientRegistryDefinition);
111
    }
112 5
113 5 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 5
        $factoryDefinition = new Definition(ConnectionFactory::class, [new Reference('mongo.client_registry')]);
116 5
        $factoryDefinition->setPublic(false);
117
118
        $this->containerBuilder->setDefinition('mongo.connection_factory', $factoryDefinition);
119
    }
120
121 5
    /**
122
     * @param array $connections
123 5
     */
124 5
    private function defineConnections(array $connections)
125 5
    {
126
        foreach ($connections as $name => $conf) {
127 5
            $connectionDefinition = new Definition(
128 5
                Database::class,
129
                [
130
                    $conf['client_name'],
131 5
                    $conf['database_name'],
132 5
                ]
133
            );
134 5
            $connectionDefinition->setFactory([new Reference('mongo.connection_factory'), 'createConnection']);
135 5
            $this->containerBuilder->setDefinition('mongo.connection.'.$name, $connectionDefinition);
136
        }
137 5
        $this->containerBuilder->setAlias('mongo.connection', 'mongo.connection.'.array_keys($connections)[0]);
138
    }
139 5
140 5
    private function defineEventManager()
141
    {
142 5
        $eventManagerDefinition = new Definition(EventDispatcher::class);
143 5
        $eventManagerDefinition->setPublic(false);
144
145 2
        $this->containerBuilder->setDefinition('facile_mongo_db.event_dispatcher', $eventManagerDefinition);
146
    }
147 2
148 2 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 2
        $dataCollectorListenerDefinition = new Definition(
151
            DataCollectorListener::class,
152
            [
153 2
                new Reference('facile_mongo_db.logger')
154
            ]
155 2
        );
156 2
        $dataCollectorListenerDefinition->setPublic(false);
157
158 2
        $this->containerBuilder->setDefinition('facile_mongo_db.data_collector.listener', $dataCollectorListenerDefinition);
159
    }
160 2
161 2
    private function attachDataCollectionListenerToEventManager()
162 2
    {
163
        $eventManagerDefinition = $this->containerBuilder->getDefinition('facile_mongo_db.event_dispatcher');
164 2
        $eventManagerDefinition->addMethodCall(
165 2
            'addListener',
166
            [
167
                ConnectionEvent::CLIENT_CREATED,
168 2
                [new Reference('facile_mongo_db.data_collector.listener'), 'onConnectionClientCreated']
169 2
            ]
170
        );
171 2
        $eventManagerDefinition->addMethodCall(
172 2
            'addListener',
173
            [
174
                QueryEvent::QUERY_EXECUTED,
175 2
                [new Reference('facile_mongo_db.data_collector.listener'), 'onQueryExecuted']
176
            ]
177 2
        );
178
    }
179 2
180 2
    private function attachTwigExtesion()
181 2
    {
182
        $extesion = new Definition(FacileMongoDbBundleExtension::class);
183 2
        $extesion->setPublic(false);
184 2
        $extesion->addTag('twig.extension');
185
186
        $this->containerBuilder->setDefinition('facile_mongo_db.twig_extesion', $extesion);
187
    }
188
189 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
        $explainServiceDefinition = new Definition(
192
            ExplainQueryService::class,
193
            [new Reference('mongo.client_registry')]
194
        );
195
        $explainServiceDefinition->setPublic(true);
196
197
        $this->containerBuilder->setDefinition('mongo.explain_query_service', $explainServiceDefinition);
198
    }
199
}
200