Completed
Push — master ( f17611...81469d )
by Nikola
04:23
created

Extension::configureRates()   B

Complexity

Conditions 5
Paths 6

Size

Total Lines 27
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 5.009

Importance

Changes 0
Metric Value
dl 0
loc 27
ccs 13
cts 14
cp 0.9286
rs 8.439
c 0
b 0
f 0
cc 5
eloc 16
nc 6
nop 2
crap 5.009
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\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...
14
use RunOpenCode\ExchangeRate\Utils\CurrencyCodeUtil;
15
use Symfony\Component\Config\FileLocator;
16
use Symfony\Component\DependencyInjection\ContainerBuilder;
17
use Symfony\Component\DependencyInjection\Definition;
18
use Symfony\Component\DependencyInjection\Extension\Extension as BaseExtension;
19
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
20
use Symfony\Component\DependencyInjection\Reference;
21
22
/**
23
 * Class Extension
24
 *
25
 * Bundle extension.
26
 *
27
 * @package RunOpenCode\Bundle\ExchangeRate\DependencyInjection
28
 */
29
class Extension extends BaseExtension
30
{
31
    /**
32
     * {@inheritdoc}
33
     */
34 5
    public function getAlias()
35
    {
36 5
        return "run_open_code_exchange_rate";
37
    }
38
39
    /**
40
     * {@inheritdoc}
41
     */
42 5
    public function getNamespace()
43
    {
44 5
        return 'http://www.runopencode.com/xsd-schema/exchange-rate-bundle';
45
    }
46
47
    /**
48
     * {@inheritdoc}
49
     */
50
    public function getXsdValidationBasePath()
51
    {
52
        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...
53
    }
54
55
    /**
56
     * {@inheritdoc}
57
     */
58 5
    public function load(array $config, ContainerBuilder $container)
59
    {
60
61 5
        $configuration = new TreeConfiguration();
62 5
        $config = $this->processConfiguration($configuration, $config);
63
64 5
        $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config/services'));
65 5
        $loader->load('repository.xml');
66 5
        $loader->load('command.xml');
67 5
        $loader->load('controller.xml');
68 5
        $loader->load('form_type.xml');
69 5
        $loader->load('manager.xml');
70 5
        $loader->load('processor.xml');
71 5
        $loader->load('source.xml');
72 5
        $loader->load('validator.xml');
73
74
        $this
75 5
            ->configureBaseCurrency($config, $container)
76 5
            ->configureRepository($config, $container)
77 5
            ->configureFileRepository($config, $container)
78 5
            ->configureDoctrineDbalRepository($config, $container)
79 5
            ->configureController($config, $container)
80 5
            ->configureRates($config, $container)
81 5
            ->configureSimpleSources($config, $container)
82 5
            ->configureSourceType($config, $container)
83 5
            ->configureRateTypeType($config, $container)
84 5
            ->configureCurrencyCodeType($config, $container)
85 5
            ->configureForeignCurrencyCodeType($config, $container)
86 5
            ->configureRateType($config, $container)
87
        ;
88 5
    }
89
90
    /**
91
     * Configure base currency.
92
     *
93
     * @param array $config Configuration parameters.
94
     * @param ContainerBuilder $container Service container.
95
     *
96
     * @return Extension $this Fluent interface.
97
     * @throws \RunOpenCode\ExchangeRate\Exception\UnknownCurrencyCodeException
98
     */
99 5
    protected function configureBaseCurrency(array $config, ContainerBuilder $container)
100
    {
101 5
        $baseCurrency = CurrencyCodeUtil::clean($config['base_currency']);
102 5
        $container->setParameter('run_open_code.exchange_rate.base_currency', $baseCurrency);
103
104 5
        return $this;
105
    }
106
107
    /**
108
     * Configure rates.
109
     *
110
     * @param array $config Configuration parameters.
111
     * @param ContainerBuilder $container Service container.
112
     *
113
     * @return Extension $this Fluent interface.
114
     */
115 5
    protected function configureRates(array $config, ContainerBuilder $container)
116
    {
117 5
        if (count($config['rates']) === 0) {
118
            throw new \RuntimeException('You have to configure which rates you would like to use in your project.');
119
        }
120
121 5
        foreach ($config['rates'] as $rate) {
122 5
            $definition = new Definition(Configuration::class);
123
124
            $arguments = [
125 5
                $rate['currency_code'],
126 5
                $rate['rate_type'],
127 5
                $rate['source'],
128 5
                (isset($rate['extra']) && $rate['extra']) ? $rate['extra'] : []
129
            ];
130
131
            $definition
132 5
                ->setArguments($arguments)
133 5
                ->setPublic(false)
134 5
                ->addTag('run_open_code.exchange_rate.rate_configuration')
135
                ;
136
137 5
            $container->setDefinition(sprintf('run_open_code.exchange_rate.rate_configuration.%s.%s.%s', $rate['currency_code'], $rate['rate_type'], $rate['source']), $definition);
138
        }
139
140 5
        return $this;
141
    }
142
143
    /**
144
     * Configure required processors.
145
     *
146
     * @param array $config Configuration parameters.
147
     * @param ContainerBuilder $container Service container.
148
     *
149
     * @return Extension $this Fluent interface.
150
     */
151 5
    protected function configureRepository(array $config, ContainerBuilder $container)
152
    {
153 5
        $container->setParameter('run_open_code.exchange_rate.repository', $config['repository']);
154 5
        return $this;
155
    }
156
157
    /**
158
     * Configure file repository.
159
     *
160
     * @param array $config Configuration parameters.
161
     * @param ContainerBuilder $container Service container.
162
     *
163
     * @return Extension $this Fluent interface.
164
     */
165 5
    protected function configureFileRepository(array $config, ContainerBuilder $container)
166
    {
167 5
        $defintion = $container->getDefinition('run_open_code.exchange_rate.repository.file_repository');
168
169
        $defintion
170 5
            ->setArguments([
171 5
                $config['file_repository']['path'],
172
            ]);
173
174 5
        return $this;
175
    }
176
177
    /**
178
     * Configure Doctrine Dbal repository.
179
     *
180
     * @param array $config Configuration parameters.
181
     * @param ContainerBuilder $container Service container.
182
     *
183
     * @return Extension $this Fluent interface.
184
     */
185 5
    protected function configureDoctrineDbalRepository(array $config, ContainerBuilder $container)
186
    {
187 5
        $defintion = $container->getDefinition('run_open_code.exchange_rate.repository.doctrine_dbal_repository');
188
189
        $defintion
190 5
            ->setArguments([
191 5
                new Reference($config['doctrine_dbal_repository']['connection']),
192 5
                $config['doctrine_dbal_repository']['table_name'],
193
            ]);
194
195 5
        return $this;
196
    }
197
198
    /**
199
     * Configure controller.
200
     *
201
     * @param array $config Configuration parameters.
202
     * @param ContainerBuilder $container Service container.
203
     * @return Extension $this Fluent interface.
204
     */
205 5
    protected function configureController(array $config, ContainerBuilder $container)
206
    {
207 5
        $container->setParameter(
208 5
            'run_open_code.exchange_rate.controller.access_roles_configuration',
209 5
            $config['access_roles']
210
        );
211
212 5
        return $this;
213
    }
214
215
    /**
216
     * Configure simple sources which does not have to be explicitly added to service container.
217
     *
218
     * @param array $config Configuration parameters.
219
     * @param ContainerBuilder $container Service container.
220
     * @return Extension $this Fluent interface.
221
     */
222 5
    protected function configureSimpleSources(array $config, ContainerBuilder $container)
223
    {
224 5
        if (!empty($config['sources']) && count($config['sources']) > 0) {
225
            $container->setParameter('run_open_code.exchange_rate.source.registered_simple_sources', $config['sources']);
226
        }
227
228 5
        return $this;
229
    }
230
231
    /**
232
     * Configure "RunOpenCode\\Bundle\\ExchangeRate\\Form\\Type\\SourceType" default settings.
233
     *
234
     * @param array $config Configuration parameters.
235
     * @param ContainerBuilder $container Service container.
236
     * @return Extension $this Fluent interface.
237
     */
238 5 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...
239
    {
240 5
        $defaults = array_merge($config['form_types']['source_type'], array('choices' => array()));
241
242 5
        foreach ($config['rates'] as $rate) {
243 5
            $defaults['choices'][sprintf('exchange_rate.source.%s', $rate['source'])] = $rate['source'];
244
        }
245
246 5
        $container->setParameter('run_open_code.exchange_rate.form_type.source_type', $defaults);
247
248 5
        return $this;
249
    }
250
251
    /**
252
     * Configure "RunOpenCode\\Bundle\\ExchangeRate\\Form\\Type\\RateTypeType" default settings.
253
     *
254
     * @param array $config Configuration parameters.
255
     * @param ContainerBuilder $container Service container.
256
     * @return Extension $this Fluent interface.
257
     */
258 5
    protected function configureRateTypeType(array $config, ContainerBuilder $container)
259
    {
260 5
        $defaults = array_merge($config['form_types']['rate_type_type'], array('choices' => array()));
261
262 5
        foreach ($config['rates'] as $rate) {
263 5
            $defaults['choices'][$rate['rate_type']] = sprintf('exchange_rate.rate_type.%s.%s', $rate['source'], $rate['rate_type']);
264
        }
265
266 5
        $defaults['choices'] = array_flip($defaults['choices']);
267
268 5
        $container->setParameter('run_open_code.exchange_rate.form_type.rate_type_type', $defaults);
269
270 5
        return $this;
271
    }
272
273
    /**
274
     * Configure "RunOpenCode\\Bundle\\ExchangeRate\\Form\\Type\\CurrencyCodeType" default settings.
275
     *
276
     * @param array $config Configuration parameters.
277
     * @param ContainerBuilder $container Service container.
278
     * @return Extension $this Fluent interface.
279
     */
280 5
    protected function configureCurrencyCodeType(array $config, ContainerBuilder $container)
281
    {
282 5
        $defaults = array_merge($config['form_types']['currency_code_type'], array('choices' => array()));
283
284 5
        foreach ($config['rates'] as $rate) {
285 5
            $defaults['choices'][$rate['currency_code']] = $rate['currency_code'];
286
        }
287
288 5
        asort($defaults['choices']);
289
290 5
        $defaults['choices'] = array_merge(array($config['base_currency'] => $config['base_currency']), $defaults['choices']);
291
292 5
        $container->setParameter('run_open_code.exchange_rate.form_type.currency_code_type', $defaults);
293
294 5
        return $this;
295
    }
296
297
    /**
298
     * Configure "RunOpenCode\\Bundle\\ExchangeRate\\Form\\Type\\ForeignCurrencyCodeType" default settings.
299
     *
300
     * @param array $config Configuration parameters.
301
     * @param ContainerBuilder $container Service container.
302
     * @return Extension $this Fluent interface.
303
     */
304 5 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...
305
    {
306 5
        $defaults = array_merge($config['form_types']['currency_code_type'], array('choices' => array()));
307
308 5
        foreach ($config['rates'] as $rate) {
309 5
            $defaults['choices'][$rate['currency_code']] = $rate['currency_code'];
310
        }
311
312 5
        asort($defaults['choices']);
313
314 5
        $container->setParameter('run_open_code.exchange_rate.form_type.foreign_currency_code_type', $defaults);
315
316 5
        return $this;
317
    }
318
319
    /**
320
     * Configure "RunOpenCode\\Bundle\\ExchangeRate\\Form\\Type\\RateType" default settings.
321
     *
322
     * @param array $config Configuration parameters.
323
     * @param ContainerBuilder $container Service container.
324
     * @return Extension $this Fluent interface.
325
     */
326 5
    protected function configureRateType(array $config, ContainerBuilder $container)
327
    {
328 5
        $container->setParameter('run_open_code.exchange_rate.form_type.rate_type', $config['form_types']['rate_type']);
329
330 5
        return $this;
331
    }
332
}
333