Completed
Push — master ( cfda18...16b364 )
by Tomas
05:21 queued 11s
created

BazingaGeocoderExtension   A

Complexity

Total Complexity 35

Size/Duplication

Total Lines 169
Duplicated Lines 10.65 %

Coupling/Cohesion

Components 1
Dependencies 10

Test Coverage

Coverage 70.83%

Importance

Changes 0
Metric Value
wmc 35
lcom 1
cbo 10
dl 18
loc 169
ccs 68
cts 96
cp 0.7083
rs 9.6
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A load() 0 30 5
B loadProviders() 0 37 7
F configureProviderPlugins() 18 61 14
A getConfiguration() 0 4 1
A findReferences() 0 12 6
A implementsProviderFactory() 0 8 2

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
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the BazingaGeocoderBundle package.
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 *
10
 * @license    MIT License
11
 */
12
13
namespace Bazinga\GeocoderBundle\DependencyInjection;
14
15
use Bazinga\GeocoderBundle\DataCollector\GeocoderDataCollector;
16
use Bazinga\GeocoderBundle\DependencyInjection\Compiler\FactoryValidatorPass;
17
use Bazinga\GeocoderBundle\Plugin\FakeIpPlugin;
18
use Bazinga\GeocoderBundle\Plugin\ProfilingPlugin;
19
use Bazinga\GeocoderBundle\ProviderFactory\PluginProviderFactory;
20
use Bazinga\GeocoderBundle\ProviderFactory\ProviderFactoryInterface;
21
use Faker\Generator;
22
use Geocoder\Dumper\Dumper;
23
use Geocoder\Plugin\Plugin\CachePlugin;
24
use Geocoder\Plugin\Plugin\LimitPlugin;
25
use Geocoder\Plugin\Plugin\LocalePlugin;
26
use Geocoder\Plugin\Plugin\LoggerPlugin;
27
use Geocoder\Plugin\PluginProvider;
28
use Geocoder\Provider\Provider;
29
use Symfony\Component\Config\Definition\Processor;
30
use Symfony\Component\Config\FileLocator;
31
use Symfony\Component\DependencyInjection\ContainerBuilder;
32
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
33
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
34
use Symfony\Component\DependencyInjection\Reference;
35
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
36
use Symfony\Component\HttpKernel\Kernel;
37
38
/**
39
 * @author William Durand <[email protected]>.
40
 */
41
class BazingaGeocoderExtension extends Extension
42
{
43 31
    public function load(array $configs, ContainerBuilder $container)
44
    {
45 31
        $processor = new Processor();
46 31
        $configuration = $this->getConfiguration($configs, $container);
47 31
        $config = $processor->processConfiguration($configuration, $configs);
0 ignored issues
show
Bug introduced by
It seems like $configuration defined by $this->getConfiguration($configs, $container) on line 46 can be null; however, Symfony\Component\Config...: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...
48
49 31
        $loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
50 31
        $loader->load('services.yml');
51
52 31
        if (true === $config['profiling']['enabled']) {
53 3
            $loader->load('profiling.yml');
54
        }
55
56 31
        if ($config['fake_ip']['enabled']) {
57
            $definition = $container->getDefinition(FakeIpPlugin::class);
58
            $definition->replaceArgument(1, $config['fake_ip']['ip']);
59
            $definition->replaceArgument(2, $config['fake_ip']['use_faker']);
60
61
            if ($config['fake_ip']['use_faker'] && !class_exists(Generator::class)) {
62
                throw new \LogicException('To enable this option, you must install fzaninotto/faker package.');
63
            }
64
        } else {
65 31
            $container->removeDefinition(FakeIpPlugin::class);
66
        }
67
68 31
        $this->loadProviders($container, $config);
69
70 31
        $container->registerForAutoconfiguration(Dumper::class)
71 31
            ->addTag('bazinga_geocoder.dumper');
72 31
    }
73
74 31
    private function loadProviders(ContainerBuilder $container, array $config)
75
    {
76 31
        foreach ($config['providers'] as $providerName => $providerConfig) {
77
            try {
78 29
                $factoryService = $container->getDefinition($providerConfig['factory']);
79 29
                $factoryClass = $factoryService->getClass() ?: $providerConfig['factory'];
80 29
                if (!$this->implementsProviderFactory($factoryClass)) {
81
                    throw new \LogicException(sprintf('Provider factory "%s" must implement ProviderFactoryInterface', $providerConfig['factory']));
82
                }
83
                // See if any option has a service reference
84 29
                $providerConfig['options'] = $this->findReferences($providerConfig['options']);
85 29
                $factoryClass::validate($providerConfig['options'], $providerName);
86
            } catch (ServiceNotFoundException $e) {
87
                // Assert: We are using a custom factory. If invalid config, it will be caught in FactoryValidatorPass
88
                $providerConfig['options'] = $this->findReferences($providerConfig['options']);
89
                FactoryValidatorPass::addFactoryServiceId($providerConfig['factory']);
90
            }
91
92 29
            $serviceId = 'bazinga_geocoder.provider.'.$providerName;
93 29
            $plugins = $this->configureProviderPlugins($container, $providerConfig, $serviceId);
94
95 29
            $def = $container->register($serviceId, PluginProvider::class)
96 29
                ->setFactory([PluginProviderFactory::class, 'createPluginProvider'])
97 29
                ->addArgument($plugins)
98 29
                ->addArgument(new Reference($providerConfig['factory']))
99 29
                ->addArgument($providerConfig['options']);
100
101 29
            $def->addTag('bazinga_geocoder.provider');
102 29
            foreach ($providerConfig['aliases'] as $alias) {
103
                $container->setAlias($alias, $serviceId);
104
            }
105
106 29
            if (Kernel::VERSION_ID > 40200) {
107 29
                $container->registerAliasForArgument($serviceId, Provider::class, "{$providerName}Geocoder");
108
            }
109
        }
110 31
    }
111
112
    /**
113
     * Configure plugins for a client.
114
     */
115 29
    public function configureProviderPlugins(ContainerBuilder $container, array $config, string $providerServiceId): array
116
    {
117 29
        $plugins = [];
118 29
        foreach ($config['plugins'] as $plugin) {
119 2
            if ($plugin['reference']['enabled']) {
120 2
                $plugins[] = $plugin['reference']['id'];
121
            }
122
        }
123
124 29
        if (isset($config['cache']) || isset($config['cache_lifetime']) || isset($config['cache_precision'])) {
125 2
            $cacheLifetime = isset($config['cache_lifetime']) ? (int) $config['cache_lifetime'] : null;
126
127 2
            if (null === $cacheServiceId = $config['cache']) {
128
                if (!$container->has('app.cache')) {
129
                    throw new \LogicException('You need to specify a service for cache.');
130
                }
131
                $cacheServiceId = 'app.cache';
132
            }
133 2
            $plugins[] = $providerServiceId.'.cache';
134 2
            $container->register($providerServiceId.'.cache', CachePlugin::class)
135 2
                ->setPublic(false)
136 2
                ->setArguments([new Reference($cacheServiceId), $cacheLifetime, $config['cache_precision']]);
137
        }
138
139 29 View Code Duplication
        if (isset($config['limit'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
140
            $plugins[] = $providerServiceId.'.limit';
141
            $container->register($providerServiceId.'.limit', LimitPlugin::class)
142
                ->setPublic(false)
143
                ->setArguments([(int) $config['limit']]);
144
        }
145
146 29 View Code Duplication
        if (isset($config['locale'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
147
            $plugins[] = $providerServiceId.'.locale';
148
            $container->register($providerServiceId.'.locale', LocalePlugin::class)
149
                ->setPublic(false)
150
                ->setArguments([$config['locale']]);
151
        }
152
153 29 View Code Duplication
        if (isset($config['logger'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
154
            $plugins[] = $providerServiceId.'.logger';
155
            $container->register($providerServiceId.'.logger', LoggerPlugin::class)
156
                ->setPublic(false)
157
                ->setArguments([new Reference($config['logger'])]);
158
        }
159
160 29
        if ($container->has(FakeIpPlugin::class)) {
161
            $plugins[] = FakeIpPlugin::class;
162
        }
163
164 29
        if ($container->has(GeocoderDataCollector::class)) {
165 1
            $plugins[] = $providerServiceId.'.profiler';
166 1
            $container->register($providerServiceId.'.profiler', ProfilingPlugin::class)
167 1
                ->setPublic(false)
168 1
                ->setArguments([substr($providerServiceId, strlen('bazinga_geocoder.provider.'))])
169 1
                ->addTag('bazinga_geocoder.profiling_plugin');
170
        }
171
172
        return array_map(function (string $id) {
173 4
            return new Reference($id);
174 29
        }, $plugins);
175
    }
176
177
    /**
178
     * {@inheritdoc}
179
     */
180 31
    public function getConfiguration(array $config, ContainerBuilder $container)
181
    {
182 31
        return new Configuration($container->getParameter('kernel.debug'));
183
    }
184
185 29
    private function findReferences(array $options): array
186
    {
187 29
        foreach ($options as $key => $value) {
188 21
            if (is_array($value)) {
189 1
                $options[$key] = $this->findReferences($value);
190 21
            } elseif ('_service' === substr((string) $key, -8) || 0 === strpos((string) $value, '@') || 'service' === $key) {
191
                $options[$key] = new Reference(ltrim($value, '@'));
192
            }
193
        }
194
195 29
        return $options;
196
    }
197
198
    /**
199
     * @param mixed $factoryClass
200
     */
201 29
    private function implementsProviderFactory($factoryClass): bool
202
    {
203 29
        if (false === $interfaces = class_implements($factoryClass)) {
204
            return false;
205
        }
206
207 29
        return in_array(ProviderFactoryInterface::class, $interfaces, true);
208
    }
209
}
210