Completed
Push — master ( f4ed63...849f7f )
by Nikola
06:32
created

Extension::configureSourceType()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 6

Duplication

Lines 12
Ratio 100 %

Code Coverage

Tests 6
CRAP Score 1

Importance

Changes 0
Metric Value
dl 12
loc 12
ccs 6
cts 6
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 6
nc 1
nop 2
crap 1
1
<?php
2
/*
3
 * This file is part of the Exchange Rate Bundle, an RunOpenCode project.
4
 *
5
 * (c) 2017 RunOpenCode
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
namespace RunOpenCode\Bundle\ExchangeRate\DependencyInjection;
11
12
use RunOpenCode\Bundle\ExchangeRate\DependencyInjection\Configuration as TreeConfiguration;
13
use RunOpenCode\Bundle\ExchangeRate\Security\AccessVoter;
14
use RunOpenCode\ExchangeRate\Configuration;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, RunOpenCode\Bundle\Excha...Injection\Configuration.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
15
use RunOpenCode\ExchangeRate\Utils\CurrencyCodeUtil;
16
use Symfony\Component\Config\FileLocator;
17
use Symfony\Component\DependencyInjection\ContainerBuilder;
18
use Symfony\Component\DependencyInjection\Definition;
19
use Symfony\Component\DependencyInjection\Extension\Extension as BaseExtension;
20
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
21
use Symfony\Component\DependencyInjection\Reference;
22
23
/**
24
 * Class Extension
25
 *
26
 * Bundle extension.
27
 *
28
 * @package RunOpenCode\Bundle\ExchangeRate\DependencyInjection
29
 */
30
class Extension extends BaseExtension
31
{
32
    /**
33
     * {@inheritdoc}
34
     */
35 9
    public function getAlias()
36
    {
37 9
        return "run_open_code_exchange_rate";
38
    }
39
40
    /**
41
     * {@inheritdoc}
42
     */
43 9
    public function getNamespace()
44
    {
45 9
        return 'http://www.runopencode.com/xsd-schema/exchange-rate-bundle';
46
    }
47
48
    /**
49
     * {@inheritdoc}
50
     */
51
    public function getXsdValidationBasePath()
52
    {
53
        return __DIR__.'/../Resources/config/schema';
0 ignored issues
show
Bug Best Practice introduced by
The return type of return __DIR__ . '/../Resources/config/schema'; (string) is incompatible with the return type of the parent method Symfony\Component\Depend...etXsdValidationBasePath of type boolean.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
54
    }
55
56
    /**
57
     * {@inheritdoc}
58
     */
59 9
    public function load(array $config, ContainerBuilder $container)
60
    {
61
62 9
        $configuration = new TreeConfiguration();
63 9
        $config = $this->processConfiguration($configuration, $config);
64
65 9
        $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config/services'));
66 9
        $loader->load('repository.xml');
67 9
        $loader->load('command.xml');
68 9
        $loader->load('form_type.xml');
69 9
        $loader->load('manager.xml');
70 9
        $loader->load('processor.xml');
71 9
        $loader->load('security.xml');
72 9
        $loader->load('source.xml');
73 9
        $loader->load('validator.xml');
74
75
        $this
76 9
            ->configureBaseCurrency($config, $container)
77 9
            ->configureRepository($config, $container)
78 9
            ->configureFileRepository($config, $container)
79 9
            ->configureDoctrineDbalRepository($config, $container)
80 9
            ->configureAccessVoter($config, $container)
81 9
            ->configureRates($config, $container)
82 9
            ->configureSources($config, $container)
83 9
            ->configureSourceType($config, $container)
84 9
            ->configureRateTypeType($config, $container)
85 9
            ->configureCurrencyCodeType($config, $container)
86 9
            ->configureForeignCurrencyCodeType($config, $container)
87 9
            ->configureRateType($config, $container)
88
        ;
89 9
    }
90
91
    /**
92
     * Configure base currency.
93
     *
94
     * @param array $config Configuration parameters.
95
     * @param ContainerBuilder $container Service container.
96
     *
97
     * @return Extension $this Fluent interface.
98
     * @throws \RunOpenCode\ExchangeRate\Exception\UnknownCurrencyCodeException
99
     */
100 9
    protected function configureBaseCurrency(array $config, ContainerBuilder $container)
101
    {
102 9
        $baseCurrency = CurrencyCodeUtil::clean($config['base_currency']);
103 9
        $container->setParameter('run_open_code.exchange_rate.base_currency', $baseCurrency);
104
105 9
        return $this;
106
    }
107
108
    /**
109
     * Configure rates.
110
     *
111
     * @param array $config Configuration parameters.
112
     * @param ContainerBuilder $container Service container.
113
     *
114
     * @return Extension $this Fluent interface.
115
     */
116 9
    protected function configureRates(array $config, ContainerBuilder $container)
117
    {
118 9
        foreach ($config['rates'] as $rate) {
119 9
            $definition = new Definition(Configuration::class);
120
121
            $arguments = [
122 9
                $rate['currency_code'],
123 9
                $rate['rate_type'],
124 9
                $rate['source'],
125 9
                (isset($rate['extra']) && $rate['extra']) ? $rate['extra'] : []
126
            ];
127
128
            $definition
129 9
                ->setArguments($arguments)
130 9
                ->setPublic(false)
131 9
                ->addTag('run_open_code.exchange_rate.rate_configuration')
132
                ;
133
134 9
            $container->setDefinition(sprintf('run_open_code.exchange_rate.rate_configuration.%s.%s.%s', $rate['currency_code'], $rate['rate_type'], $rate['source']), $definition);
135
        }
136
137 9
        return $this;
138
    }
139
140
141
    /**
142
     * Configure sources which does not have to be explicitly added to service container.
143
     *
144
     * @param array $config Configuration parameters.
145
     * @param ContainerBuilder $container Service container.
146
     *
147
     * @return Extension $this Fluent interface.
148
     */
149 9
    protected function configureSources(array $config, ContainerBuilder $container)
150
    {
151 9
        if (!empty($config['sources'])) {
152
153 1
            foreach ($config['sources'] as $name => $class) {
154
155 1
                $definition = new Definition($class);
156
                $definition
157 1
                    ->addTag('run_open_code.exchange_rate.source', ['alias' => $name]);
158
159 1
                $container->setDefinition(sprintf('run_open_code.exchange_rate.source.%s', $name), $definition);
160
            }
161
        }
162
163 9
        return $this;
164
    }
165
166
    /**
167
     * Configure required processors.
168
     *
169
     * @param array $config Configuration parameters.
170
     * @param ContainerBuilder $container Service container.
171
     *
172
     * @return Extension $this Fluent interface.
173
     */
174 9
    protected function configureRepository(array $config, ContainerBuilder $container)
175
    {
176 9
        $container->setParameter('run_open_code.exchange_rate.repository', $config['repository']);
177 9
        return $this;
178
    }
179
180
    /**
181
     * Configure file repository.
182
     *
183
     * @param array $config Configuration parameters.
184
     * @param ContainerBuilder $container Service container.
185
     *
186
     * @return Extension $this Fluent interface.
187
     */
188 9
    protected function configureFileRepository(array $config, ContainerBuilder $container)
189
    {
190 9
        $defintion = $container->getDefinition('run_open_code.exchange_rate.repository.file_repository');
191
192
        $defintion
193 9
            ->setArguments([
194 9
                $config['file_repository']['path'],
195
            ]);
196
197 9
        return $this;
198
    }
199
200
    /**
201
     * Configure Doctrine Dbal repository.
202
     *
203
     * @param array $config Configuration parameters.
204
     * @param ContainerBuilder $container Service container.
205
     *
206
     * @return Extension $this Fluent interface.
207
     */
208 9
    protected function configureDoctrineDbalRepository(array $config, ContainerBuilder $container)
209
    {
210 9
        $defintion = $container->getDefinition('run_open_code.exchange_rate.repository.doctrine_dbal_repository');
211
212
        $defintion
213 9
            ->setArguments([
214 9
                new Reference($config['doctrine_dbal_repository']['connection']),
215 9
                $config['doctrine_dbal_repository']['table_name'],
216
            ]);
217
218 9
        return $this;
219
    }
220
221
    /**
222
     * Configure access voter.
223
     *
224
     * @param array $config Configuration parameters.
225
     * @param ContainerBuilder $container Service container.
226
     *
227
     * @return Extension $this Fluent interface.
228
     */
229 9
    protected function configureAccessVoter(array $config, ContainerBuilder $container)
230
    {
231 9
        if ($config['security']['enabled']) {
232
233
            $container
234 8
                ->getDefinition('run_open_code.exchange_rate.security.access_voter')
235 8
                ->setArguments([
236
                    [
237 8
                        AccessVoter::VIEW => $config['security'][AccessVoter::VIEW],
238 8
                        AccessVoter::CREATE => $config['security'][AccessVoter::CREATE],
239 8
                        AccessVoter::EDIT => $config['security'][AccessVoter::EDIT],
240 8
                        AccessVoter::DELETE => $config['security'][AccessVoter::DELETE],
241
                    ]
242
                ]);
243
244
        } else {
245 1
            $container->removeDefinition('run_open_code.exchange_rate.security.access_voter');
246
        }
247
248 9
        return $this;
249
    }
250
251
    /**
252
     * Configure "RunOpenCode\\Bundle\\ExchangeRate\\Form\\Type\\SourceType" default settings.
253
     *
254
     * @param array $config Configuration parameters.
255
     * @param ContainerBuilder $container Service container.
256
     *
257
     * @return Extension $this Fluent interface.
258
     */
259 9 View Code Duplication
    protected function configureSourceType(array $config, ContainerBuilder $container)
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...
260
    {
261 9
        $definition = $container->getDefinition('run_open_code.exchange_rate.form_type.source_type');
262
263 9
        $arguments = $definition->getArguments();
264
265 9
        $arguments[1] = $config['form_types']['source_type'];
266
267 9
        $definition->setArguments($arguments);
268
269 9
        return $this;
270
    }
271
272
    /**
273
     * Configure "RunOpenCode\\Bundle\\ExchangeRate\\Form\\Type\\RateTypeType" default settings.
274
     *
275
     * @param array $config Configuration parameters.
276
     * @param ContainerBuilder $container Service container.
277
     *
278
     * @return Extension $this Fluent interface.
279
     */
280 9 View Code Duplication
    protected function configureRateTypeType(array $config, ContainerBuilder $container)
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...
281
    {
282 9
        $definition = $container->getDefinition('run_open_code.exchange_rate.form_type.rate_type_type');
283
284 9
        $arguments = $definition->getArguments();
285
286 9
        $arguments[1] = $config['form_types']['rate_type_type'];
287
288 9
        $definition->setArguments($arguments);
289
290 9
        return $this;
291
    }
292
293
    /**
294
     * Configure "RunOpenCode\\Bundle\\ExchangeRate\\Form\\Type\\CurrencyCodeType" default settings.
295
     *
296
     * @param array $config Configuration parameters.
297
     * @param ContainerBuilder $container Service container.
298
     * @return Extension $this Fluent interface.
299
     */
300 9
    protected function configureCurrencyCodeType(array $config, ContainerBuilder $container)
301
    {
302 9
        $definition = $container->getDefinition('run_open_code.exchange_rate.form_type.currency_code_type');
303
304 9
        $arguments = $definition->getArguments();
305
306 9
        $arguments[1] = CurrencyCodeUtil::clean($config['base_currency']);
307 9
        $arguments[2] = $config['form_types']['currency_code_type'];
308
309 9
        $definition->setArguments($arguments);
310
311 9
        return $this;
312
    }
313
314
    /**
315
     * Configure "RunOpenCode\\Bundle\\ExchangeRate\\Form\\Type\\ForeignCurrencyCodeType" default settings.
316
     *
317
     * @param array $config Configuration parameters.
318
     * @param ContainerBuilder $container Service container.
319
     *
320
     * @return Extension $this Fluent interface.
321
     */
322 9 View Code Duplication
    protected function configureForeignCurrencyCodeType(array $config, ContainerBuilder $container)
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...
323
    {
324
325 9
        $definition = $container->getDefinition('run_open_code.exchange_rate.form_type.foreign_currency_code_type');
326
327 9
        $arguments = $definition->getArguments();
328
329 9
        $arguments[1] = $config['form_types']['foreign_currency_code_type'];
330
331 9
        $definition->setArguments($arguments);
332
333 9
        return $this;
334
    }
335
336
    /**
337
     * Configure "RunOpenCode\\Bundle\\ExchangeRate\\Form\\Type\\RateType" default settings.
338
     *
339
     * @param array $config Configuration parameters.
340
     * @param ContainerBuilder $container Service container.
341
     *
342
     * @return Extension $this Fluent interface.
343
     */
344 9 View Code Duplication
    protected function configureRateType(array $config, ContainerBuilder $container)
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...
345
    {
346 9
        $definition = $container->getDefinition('run_open_code.exchange_rate.form_type.rate_type');
347
348 9
        $arguments = $definition->getArguments();
349
350 9
        $arguments[1] = $config['form_types']['rate_type'];
351
352 9
        $definition->setArguments($arguments);
353
354 9
        return $this;
355
    }
356
}
357