Completed
Pull Request — master (#8)
by Tobias
10:23 queued 06:37
created

Neo4jExtension::handleEntityMangers()   B

Complexity

Conditions 4
Paths 3

Size

Total Lines 23
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 4.0582

Importance

Changes 0
Metric Value
dl 0
loc 23
ccs 11
cts 13
cp 0.8462
rs 8.7972
c 0
b 0
f 0
cc 4
eloc 16
nc 3
nop 3
crap 4.0582
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Neo4j\Neo4jBundle\DependencyInjection;
6
7
use GraphAware\Neo4j\Client\Connection\Connection;
8
use GraphAware\Neo4j\OGM\EntityManager;
9
use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
10
use Symfony\Component\Config\FileLocator;
11
use Symfony\Component\DependencyInjection\ContainerBuilder;
12
use Symfony\Component\DependencyInjection\Definition;
13
use Symfony\Component\DependencyInjection\DefinitionDecorator;
14
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
15
use Symfony\Component\DependencyInjection\Reference;
16
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
17
18
/**
19
 * @author Tobias Nyholm <[email protected]>
20
 */
21
class Neo4jExtension extends Extension
22
{
23
    /**
24
     * {@inheritdoc}
25
     */
26 4
    public function load(array $configs, ContainerBuilder $container)
27
    {
28 4
        $configuration = $this->getConfiguration($configs, $container);
29 4
        $config = $this->processConfiguration($configuration, $configs);
1 ignored issue
show
Bug introduced by
It seems like $configuration defined by $this->getConfiguration($configs, $container) on line 28 can be null; however, Symfony\Component\Depend...:processConfiguration() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
30
31 4
        $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
32 4
        $loader->load('services.xml');
33
34 4
        $this->handleConnections($config, $container);
35 4
        $clientServiceIds = $this->handleClients($config, $container);
36 4
        if ($this->validateEntityManagers($config)) {
37 4
            $loader->load('entity_manager.xml');
38 4
            $this->handleEntityMangers($config, $container, $clientServiceIds);
39
        }
40
41
        // add aliases for the default services
42 4
        $container->setAlias('neo4j.connection', 'neo4j.connection.default');
43 4
        $container->setAlias('neo4j.client', 'neo4j.client.default');
44 4
        $container->setAlias('neo4j.entity_manager', 'neo4j.entity_manager.default');
45
46
        // Configure toolbar
47 4
        if ($this->isConfigEnabled($container, $config['profiling'])) {
48 2
            $loader->load('data-collector.xml');
49
50 2
            $container->getDefinition('neo4j.factory.client')
51 2
                ->replaceArgument(0, new Reference('neo4j.client_logger'));
52
        }
53 4
    }
54
55
    /**
56
     * @param array            $config
57
     * @param ContainerBuilder $container
58
     *
59
     * @return array with service ids
60
     */
61 4
    private function handleClients(array &$config, ContainerBuilder $container): array
62
    {
63 4
        if (empty($config['clients'])) {
64
            // Add default entity manager if none set.
65 4
            $config['clients']['default'] = ['connections' => ['default']];
66
        }
67
68 4
        $serviceIds = [];
69 4
        foreach ($config['clients'] as $name => $data) {
70 4
            $serviceIds[$name] = $serviceId = sprintf('neo4j.client.%s', $name);
71 4
            $urls = [];
72 4
            foreach ($data['connections'] as $connectionName) {
73 4
                if (empty($config['connections'][$connectionName])) {
74
                    throw new InvalidConfigurationException(sprintf(
75
                        'Client "%s" is configured to use connection named "%s" but there is no such connection',
76
                        $name,
77
                        $connectionName
78
                    ));
79
                }
80 4
                $urls[] = $this->getUrl($config['connections'][$connectionName]);
81
            }
82 4
            if (empty($urls)) {
83
                $urls[] = $this->getUrl($config['connections']['default']);
84
            }
85
86
            $container
87 4
                ->setDefinition($serviceId, new DefinitionDecorator('neo4j.client.abstract'))
88 4
                ->setArguments([$urls]);
89
        }
90
91 4
        return $serviceIds;
92
    }
93
94
    /**
95
     * @param array            $config
96
     * @param ContainerBuilder $container
97
     * @param array            $clientServiceIds
98
     *
99
     * @return array
100
     */
101 4
    private function handleEntityMangers(array &$config, ContainerBuilder $container, array $clientServiceIds): array
102
    {
103 4
        $serviceIds = [];
104 4
        foreach ($config['entity_managers'] as $name => $data) {
105 4
            $serviceIds[] = $serviceId = sprintf('neo4j.entity_manager.%s', $name);
106 4
            $clientName = $data['client'];
107 4
            if (empty($clientServiceIds[$clientName])) {
108
                throw new InvalidConfigurationException(sprintf(
109
                    'EntityManager "%s" is configured to use client named "%s" but there is no such client',
110
                    $name,
111
                    $clientName
112
                ));
113
            }
114
            $container
115 4
                ->setDefinition($serviceId, new DefinitionDecorator('neo4j.entity_manager.abstract'))
116 4
                ->setArguments([
117 4
                    $container->getDefinition($clientServiceIds[$clientName]),
118 4
                    empty($data['cache_dir']) ? $container->getParameter('kernel.cache_dir').'/neo4j' : $data['cache_dir'],
119
                ]);
120
        }
121
122 4
        return $serviceIds;
123
    }
124
125
    /**
126
     * @param array            $config
127
     * @param ContainerBuilder $container
128
     *
129
     * @return array with service ids
130
     */
131 4
    private function handleConnections(array &$config, ContainerBuilder $container): array
132
    {
133 4
        $serviceIds = [];
134 4
        $firstName = null;
135 4
        foreach ($config['connections'] as $name => $data) {
136 4
            if ($firstName === null || $name === 'default') {
137 4
                $firstName = $name;
138
            }
139 4
            $def = new Definition(Connection::class);
140 4
            $def->addArgument($name);
141 4
            $def->addArgument($this->getUrl($data));
142 4
            $serviceIds[] = $serviceId = 'neo4j.connection.'.$name;
143 4
            $container->setDefinition($serviceId, $def);
144
        }
145
146
        // Make sure we got a 'default'
147 4
        if ($firstName !== 'default') {
148
            $config['connections']['default'] = $config['connections'][$firstName];
149
        }
150
151 4
        return $serviceIds;
152
    }
153
154
    /**
155
     * Get URL form config.
156
     *
157
     * @param array $config
158
     *
159
     * @return string
160
     */
161 4
    private function getUrl(array $config): string
162
    {
163 4
        return sprintf(
164 4
            '%s://%s:%s@%s:%d',
165 4
            $config['schema'],
166 4
            $config['username'],
167 4
            $config['password'],
168 4
            $config['host'],
169 4
            $config['port']
170
        );
171
    }
172
173
    /**
174
     * {@inheritdoc}
175
     */
176 4
    public function getConfiguration(array $config, ContainerBuilder $container): Configuration
177
    {
178 4
        return new Configuration($container->getParameter('kernel.debug'));
179
    }
180
181 4
    public function getAlias(): string
182
    {
183 4
        return 'neo4j';
184
    }
185
186
    /**
187
     * Make sure the EntityManager is installed if we have configured it.
188
     *
189
     * @param array &$config
190
     *
191
     * @return bool true if "graphaware/neo4j-php-ogm" is installed
192
     *
193
     * @thorws \LogicException if EntityManagers os not installed but they are configured.
194
     */
195 4
    private function validateEntityManagers(array &$config): bool
196
    {
197 4
        $dependenciesInstalled = class_exists(EntityManager::class);
198 4
        $entityManagersConfigured = !empty($config['entity_managers']);
199
200 4
        if ($dependenciesInstalled && !$entityManagersConfigured) {
201
            // Add default entity manager if none set.
202 4
            $config['entity_managers']['default'] = ['client' => 'default'];
203
        } elseif (!$dependenciesInstalled && $entityManagersConfigured) {
204
            throw new \LogicException(
205
                'You need to install "graphaware/neo4j-php-ogm" to be able to use the EntityManager'
206
            );
207
        }
208
209 4
        return $dependenciesInstalled;
210
    }
211
}
212