Completed
Branch query_logging_to_events (025608)
by Alessandro
02:17
created

MongoDbBundleExtension::defineListeners()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 11
ccs 6
cts 6
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 5
nc 1
nop 0
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Facile\MongoDbBundle\DependencyInjection;
6
7
use Facile\MongoDbBundle\DataCollector\MongoDbDataCollector;
8
use Facile\MongoDbBundle\Event\ConnectionEvent;
9
use Facile\MongoDbBundle\Event\Listener\DataCollectorListener;
10
use Facile\MongoDbBundle\Event\Listener\QueryEvent;
11
use Facile\MongoDbBundle\Services\ClientRegistry;
12
use Facile\MongoDbBundle\Services\ConnectionFactory;
13
use Facile\MongoDbBundle\Services\Loggers\MongoLogger;
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
class MongoDbBundleExtension extends Extension
27
{
28
    /** @var ContainerBuilder */
29
    private $containerBuilder;
30
31
    /**
32
     * {@inheritdoc}
33
     */
34 4
    public function load(array $configs, ContainerBuilder $container)
35
    {
36 4
        $this->containerBuilder = $container;
37 4
        $configuration = new Configuration();
38 4
        $config = $this->processConfiguration($configuration, $configs);
39
40 4
        $this->defineEventManager();
41 4
        $this->defineLoggers();
42
43 4
        if ($container->getParameter("kernel.environment") === 'dev' && class_exists(WebProfilerBundle::class)) {
44 2
            $this->defineListeners();
45 2
            $this->attachEventsToEventManager();
46 2
            $this->defineDataCollector();
47
        }
48
49 4
        $this->defineClientRegistry($config['clients'], $container->getParameter("kernel.environment"));
50 4
        $this->defineConnectionFactory();
51 4
        $this->defineConnections($config['connections']);
52
53 4
        return $config;
54
    }
55
56 4
    private function defineLoggers()
57
    {
58 4
        $loggerDefinition = new Definition(MongoLogger::class);
59 4
        $loggerDefinition->setPublic(false);
60
61 4
        $this->containerBuilder->setDefinition('facile_mongo_db.logger', $loggerDefinition);
62 4
    }
63
64 2
    private function defineDataCollector()
65
    {
66 2
        $dataCollectorDefinition = new Definition(MongoDbDataCollector::class);
67 2
        $dataCollectorDefinition->addMethodCall('setLogger', [new Reference('facile_mongo_db.logger')]);
68 2
        $dataCollectorDefinition->addTag(
69 2
            'data_collector',
70
            [
71 2
                'template' => 'FacileMongoDbBundle:Collector:mongo.html.twig',
72
                'id' => 'mongodb',
73
                'priority' => 250,
74
            ]
75
        );
76 2
        $dataCollectorDefinition->setPublic(false);
77
78 2
        $this->containerBuilder->setDefinition('facile_mongo_db.data_collector', $dataCollectorDefinition);
79 2
    }
80
81
    /**
82
     * @param array  $clientsConfig
83
     * @param string $environment
84
     */
85 4
    private function defineClientRegistry(array $clientsConfig, string $environment)
86
    {
87 4
        $clientRegistryDefinition = new Definition(
88 4
            ClientRegistry::class,
89
            [
90 4
                new Reference('facile_mongo_db.event_dispatcher'),
91 4
                $environment,
92
            ]
93
        );
94 4
        $clientRegistryDefinition->addMethodCall('addClientsConfigurations', [$clientsConfig]);
95 4
        $clientRegistryDefinition->setPublic(false);
96
97 4
        $this->containerBuilder->setDefinition('mongo.client_registry', $clientRegistryDefinition);
98 4
    }
99
100 4
    private function defineConnectionFactory()
101
    {
102 4
        $factoryDefinition = new Definition(ConnectionFactory::class, [new Reference('mongo.client_registry')]);
103 4
        $factoryDefinition->setPublic(false);
104
105 4
        $this->containerBuilder->setDefinition('mongo.connection_factory', $factoryDefinition);
106 4
    }
107
108
    /**
109
     * @param array $connections
110
     */
111 4
    private function defineConnections(array $connections)
112
    {
113 4
        foreach ($connections as $name => $conf) {
114 4
            $connectionDefinition = new Definition(
115 4
                Database::class,
116
                [
117 4
                    $conf['client_name'],
118 4
                    $conf['database_name'],
119
                ]
120
            );
121 4
            $connectionDefinition->setFactory([new Reference('mongo.connection_factory'), 'createConnection']);
122 4
            $this->containerBuilder->setDefinition('mongo.connection.'.$name, $connectionDefinition);
123
        }
124 4
        $this->containerBuilder->setAlias('mongo.connection', 'mongo.connection.'.array_keys($connections)[0]);
125 4
    }
126
127 4
    private function defineEventManager()
128
    {
129 4
        $eventManagerDefinition = new Definition(EventDispatcher::class);
130
131 4
        $this->containerBuilder->setDefinition('facile_mongo_db.event_dispatcher', $eventManagerDefinition);
132 4
    }
133
134 2
    private function defineListeners()
135
    {
136 2
        $dataCollectorListenerDefinition = new Definition(
137 2
            DataCollectorListener::class,
138
            [
139 2
                new Reference('facile_mongo_db.logger')
140
            ]
141
        );
142
143 2
        $this->containerBuilder->setDefinition('facile_mongo_db.data_collector.listener', $dataCollectorListenerDefinition);
144 2
    }
145
146 2
    private function attachEventsToEventManager()
147
    {
148 2
        $eventManagerDefinition = $this->containerBuilder->getDefinition('facile_mongo_db.event_dispatcher');
149 2
        $eventManagerDefinition->addMethodCall(
150 2
            'addListener',
151
            [
152 2
                ConnectionEvent::CLIENT_CREATED,
153 2
                [new Reference('facile_mongo_db.data_collector.listener'), 'onConnectionClientCreated']
154
            ]
155
        );
156 2
        $eventManagerDefinition->addMethodCall(
157 2
            'addListener',
158
            [
159 2
                QueryEvent::QUERY_EXECUTED,
160 2
                [new Reference('facile_mongo_db.data_collector.listener'), 'onQueryExecution']
161
            ]
162
        );
163 2
    }
164
}
165