Completed
Push — master ( 81469d...e47b50 )
by Nikola
03:24
created

Extension::configureFileRepository()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

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