Completed
Push — master ( 822871...f25de2 )
by Markus
09:46 queued 22s
created

MathielenImportEngineExtension   C

Complexity

Total Complexity 60

Size/Duplication

Total Lines 397
Duplicated Lines 9.07 %

Coupling/Cohesion

Components 1
Dependencies 8

Test Coverage

Coverage 88.76%

Importance

Changes 23
Bugs 3 Features 2
Metric Value
wmc 60
c 23
b 3
f 2
lcom 1
cbo 8
dl 36
loc 397
ccs 237
cts 267
cp 0.8876
rs 6.0975

14 Methods

Rating   Name   Duplication   Size   Complexity  
A load() 0 11 2
B parseConfig() 0 26 5
A generateObjectFactoryDef() 0 14 3
D generateFinderDef() 10 32 9
D generateImporterDef() 0 34 9
A generateFiltersDef() 0 14 2
B generateTransformerDef() 0 44 5
A generateValidatorDef() 0 11 1
B generateValidationDef() 0 55 7
A setSourceStorageDef() 0 7 1
C addStorageProviderDef() 26 75 9
A getStorageFileDefinitionFromUri() 0 10 2
B getStorageDef() 0 34 4
A getAlias() 0 4 1

How to fix   Duplicated Code    Complexity   

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:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like MathielenImportEngineExtension often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use MathielenImportEngineExtension, and based on these observations, apply Extract Interface, too.

1
<?php
2
namespace Mathielen\ImportEngineBundle\DependencyInjection;
3
4
use Mathielen\ImportEngine\Exception\InvalidConfigurationException;
5
use Mathielen\ImportEngine\Storage\Provider\Connection\DefaultConnectionFactory;
6
use Symfony\Component\DependencyInjection\ContainerBuilder;
7
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
8
use Symfony\Component\DependencyInjection\Extension\Extension;
9
use Symfony\Component\Config\FileLocator;
10
use Symfony\Component\DependencyInjection\Reference;
11
use Symfony\Component\DependencyInjection\Definition;
12
use Symfony\Component\ExpressionLanguage\Expression;
13
14
class MathielenImportEngineExtension extends Extension
15
{
16
17 11
    public function load(array $configs, ContainerBuilder $container)
18
    {
19 11
        $config = $this->processConfiguration(new Configuration(), $configs);
20
21 11
        if (!empty($config['importers'])) {
22 9
            $loader = new XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
23 9
            $loader->load('services.xml');
24
25 9
            $this->parseConfig($config, $container);
26 9
        }
27 11
    }
28
29 9
    private function parseConfig(array $config, ContainerBuilder $container)
30
    {
31 9
        $storageLocatorDef = $container->findDefinition('mathielen_importengine.import.storagelocator');
32 9
        foreach ($config['storageprovider'] as $name => $sourceConfig) {
33 5
            $this->addStorageProviderDef($storageLocatorDef, $sourceConfig, $name);
34 9
        }
35
36 9
        $importerRepositoryDef = $container->findDefinition('mathielen_importengine.importer.repository');
37 9
        foreach ($config['importers'] as $name => $importConfig) {
38 9
            $finderDef = null;
39 9
            if (isset($importConfig['preconditions'])) {
40 5
                $finderDef = $this->generateFinderDef($importConfig['preconditions']);
41 5
            }
42
43 9
            $objectFactoryDef = null;
44 9
            if (isset($importConfig['object_factory'])) {
45 5
                $objectFactoryDef = $this->generateObjectFactoryDef($importConfig['object_factory']);
46 5
            }
47
48 9
            $importerRepositoryDef->addMethodCall('register', array(
49 9
                $name,
50 9
                $this->generateImporterDef($importConfig, $objectFactoryDef),
51
                $finderDef
52 9
            ));
53 9
        }
54 9
    }
55
56 5
    private function generateObjectFactoryDef(array $config)
57
    {
58 5
        if (!class_exists($config['class'])) {
59
            throw new InvalidConfigurationException("Object-Factory target-class '".$config['class']."' does not exist.");
60
        }
61
62 5
        if ($config['type'] == 'jms_serializer') {
63 5
            return new Definition('Mathielen\DataImport\Writer\ObjectWriter\JmsSerializerObjectFactory', array(
64 5
                $config['class'],
65 5
                new Reference('jms_serializer')));
66
        }
67
68 5
        return new Definition('Mathielen\DataImport\Writer\ObjectWriter\DefaultObjectFactory', array($config['class']));
69
    }
70
71
    /**
72
     * @return \Symfony\Component\DependencyInjection\Definition
73
     */
74 5
    private function generateFinderDef(array $finderConfig)
75
    {
76 5
        $finderDef = new Definition('Mathielen\ImportEngine\Importer\ImporterPrecondition');
77
78 5
        if (isset($finderConfig['filename'])) {
79 5
            foreach ($finderConfig['filename'] as $conf) {
80 5
                $finderDef->addMethodCall('filename', array($conf));
81 5
            }
82 5
        }
83
84 5 View Code Duplication
        if (isset($finderConfig['format'])) {
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...
85 5
            foreach ($finderConfig['format'] as $conf) {
86 5
                $finderDef->addMethodCall('format', array($conf));
87 5
            }
88 5
        }
89
90 5
        if (isset($finderConfig['fieldcount'])) {
91 5
            $finderDef->addMethodCall('fieldcount', array($finderConfig['fieldcount']));
92 5
        }
93
94 5 View Code Duplication
        if (isset($finderConfig['fields'])) {
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...
95 5
            foreach ($finderConfig['fields'] as $conf) {
96 5
                $finderDef->addMethodCall('field', array($conf));
97 5
            }
98 5
        }
99
100 5
        if (isset($finderConfig['fieldset'])) {
101 5
            $finderDef->addMethodCall('fieldset', array($finderConfig['fieldset']));
102 5
        }
103
104 5
        return $finderDef;
105
    }
106
107
    /**
108
     * @return \Symfony\Component\DependencyInjection\Definition
109
     */
110 9
    private function generateImporterDef(array $importConfig, Definition $objectFactoryDef=null)
111
    {
112 9
        $importerDef = new Definition('Mathielen\ImportEngine\Importer\Importer', array(
113 9
            $this->getStorageDef($importConfig['target'], $objectFactoryDef)
114 9
        ));
115
116 9
        if (isset($importConfig['source'])) {
117 5
            $this->setSourceStorageDef($importConfig['source'], $importerDef);
118 5
        }
119
120
        //enable validation?
121 9
        if (isset($importConfig['validation']) && !empty($importConfig['validation'])) {
122 7
            $this->generateValidationDef($importConfig['validation'], $importerDef, $objectFactoryDef);
123 7
        }
124
125
        //add converters?
126 9
        if (isset($importConfig['mappings']) && !empty($importConfig['mappings'])) {
127 5
            $this->generateTransformerDef($importConfig['mappings'], $importerDef);
128 5
        }
129
130
        //add filters?
131 9
        if (isset($importConfig['filters']) && !empty($importConfig['filters'])) {
132
            $this->generateFiltersDef($importConfig['filters'], $importerDef);
133
        }
134
135
        //has static context?
136 9
        if (isset($importConfig['context'])) {
137 9
            $importerDef->addMethodCall('setContext', array(
138 9
                $importConfig['context']
139 9
            ));
140 9
        }
141
142 9
        return $importerDef;
143
    }
144
145
    private function generateFiltersDef(array $filtersOptions, Definition $importerDef)
146
    {
147
        $filtersDef = new Definition('Mathielen\ImportEngine\Filter\Filters');
148
149
        foreach ($filtersOptions as $filtersOption) {
150
            $filtersDef->addMethodCall('add', array(
151
                new Reference($filtersOption)
152
            ));
153
        }
154
155
        $importerDef->addMethodCall('filters', array(
156
            $filtersDef
157
        ));
158
    }
159
160 5
    private function generateTransformerDef(array $mappingOptions, Definition $importerDef)
161
    {
162 5
        $mappingsDef = new Definition('Mathielen\ImportEngine\Mapping\Mappings');
163
164
        //set converters
165 5
        foreach ($mappingOptions as $field=>$fieldMapping) {
166 5
            $converter = null;
167 5
            if (isset($fieldMapping['converter'])) {
168 5
                $converter = $fieldMapping['converter'];
169 5
            }
170
171 5
            if (isset($fieldMapping['to'])) {
172 5
                $mappingsDef->addMethodCall('add', array(
173 5
                    $field,
174 5
                    $fieldMapping['to'],
175
                    $converter
176 5
            ));
177 5
            } elseif ($converter) {
178 5
                $mappingsDef->addMethodCall('setConverter', array(
179 5
                    $converter,
180
                    $field
181 5
                ));
182 5
            }
183 5
        }
184
185 5
        $mappingFactoryDef = new Definition('Mathielen\ImportEngine\Mapping\DefaultMappingFactory', array(
186
            $mappingsDef
187 5
        ));
188 5
        $converterProviderDef = new Definition('Mathielen\ImportEngine\Mapping\Converter\Provider\ContainerAwareConverterProvider', array(
189 5
            new Reference('service_container')
190 5
        ));
191
192 5
        $transformerDef = new Definition('Mathielen\ImportEngine\Transformation\Transformation');
193 5
        $transformerDef->addMethodCall('setMappingFactory', array(
194
            $mappingFactoryDef
195 5
        ));
196 5
        $transformerDef->addMethodCall('setConverterProvider', array(
197
            $converterProviderDef
198 5
        ));
199
200 5
        $importerDef->addMethodCall('transformation', array(
201
            $transformerDef
202 5
        ));
203 5
    }
204
205 7
    private function generateValidatorDef(array $options)
206
    {
207
        //eventdispatcher aware source validatorfilter
208 7
        $validatorFilterDef = new Definition('Mathielen\DataImport\Filter\ValidatorFilter', array(
209 7
            new Reference('validator'),
210 7
            $options,
211 7
            new Reference('event_dispatcher')
212 7
        ));
213
214 7
        return $validatorFilterDef;
215
    }
216
217 7
    private function generateValidationDef(array $validationConfig, Definition $importerDef, Definition $objectFactoryDef=null)
218
    {
219 7
        $validationDef = new Definition('Mathielen\ImportEngine\Validation\ValidatorValidation', array(
220 7
            new Reference('validator')
221 7
        ));
222 7
        $importerDef->addMethodCall('validation', array(
223
            $validationDef
224 7
        ));
225
226 7
        $validatorFilterDef = $this->generateValidatorDef(
227 7
            isset($validationConfig['options'])?$validationConfig['options']:array()
228 7
        );
229
230 7
        if (isset($validationConfig['source'])) {
231 3
            $validationDef->addMethodCall('setSourceValidatorFilter', array(
232
                $validatorFilterDef
233 3
            ));
234
235 3
            foreach ($validationConfig['source']['constraints'] as $field=>$constraint) {
236 3
                $validationDef->addMethodCall('addSourceConstraint', array(
237 3
                    $field,
238 3
                    new Definition($constraint)
239 3
                ));
240 3
            }
241 3
        }
242
243
        //automatically apply class validation
244 7
        if (isset($validationConfig['target'])) {
245
246
            //using objects as result
247 7
            if ($objectFactoryDef) {
248
249
                //set eventdispatcher aware target CLASS-validatorfilter
250 5
                $validatorFilterDef = new Definition('Mathielen\DataImport\Filter\ClassValidatorFilter', array(
251 5
                    new Reference('validator'),
252 5
                    $objectFactoryDef,
253 5
                    new Reference('event_dispatcher')
254 5
                ));
255
256 5
            } else {
257 3
                foreach ($validationConfig['target']['constraints'] as $field=>$constraint) {
258 3
                    $validationDef->addMethodCall('addTargetConstraint', array(
259 3
                        $field,
260 3
                        new Definition($constraint)
261 3
                    ));
262 3
                }
263
            }
264
265 7
            $validationDef->addMethodCall('setTargetValidatorFilter', array(
266
                $validatorFilterDef
267 7
            ));
268 7
        }
269
270 7
        return $validationDef;
271
    }
272
273 5
    private function setSourceStorageDef(array $sourceConfig, Definition $importerDef)
274
    {
275 5
        $sDef = $this->getStorageDef($sourceConfig, $importerDef);
276 5
        $importerDef->addMethodCall('setSourceStorage', array(
277
            $sDef
278 5
        ));
279 5
    }
280
281 5
    private function addStorageProviderDef(Definition $storageLocatorDef, $config, $id = 'default')
282
    {
283 5
        $formatDiscoverLocalFileStorageFactoryDef = new Definition('Mathielen\ImportEngine\Storage\Factory\FormatDiscoverLocalFileStorageFactory', array(
284 5
            new Definition('Mathielen\ImportEngine\Storage\Format\Discovery\MimeTypeDiscoverStrategy', array(
285
                array(
286 5
                    'text/plain'=>new Definition('Mathielen\ImportEngine\Storage\Format\Factory\CsvAutoDelimiterFormatFactory'),
287 5
                    'text/csv'=>new Definition('Mathielen\ImportEngine\Storage\Format\Factory\CsvAutoDelimiterFormatFactory'),
288
                )
289 5
            )),
290 5
            new Reference('logger')
291 5
        ));
292
293 5
        switch ($config['type']) {
294 5
            case 'directory':
295 5
                $spFinderDef = new Definition('Symfony\Component\Finder\Finder');
296 5
                $spFinderDef->addMethodCall('in', array(
297 5
                    $config['uri']
298 5
                ));
299 5
                $spDef = new Definition('Mathielen\ImportEngine\Storage\Provider\FinderFileStorageProvider', array(
300 5
                    $spFinderDef,
301
                    $formatDiscoverLocalFileStorageFactoryDef
302 5
                ));
303 5
                break;
304 5
            case 'upload':
305 5
                $spDef = new Definition('Mathielen\ImportEngine\Storage\Provider\UploadFileStorageProvider', array(
306 5
                    $config['uri'],
307
                    $formatDiscoverLocalFileStorageFactoryDef
308 5
                ));
309 5
                break;
310 5 View Code Duplication
            case 'doctrine':
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...
311 5
                $listResolverDef = new Definition(StringOrFileList::class, array($config['queries']));
312 5
                if (!isset($config['connection_factory'])) {
313 5
                    $connectionFactoryDef = new Definition(DefaultConnectionFactory::class, array(array('default'=>new Reference('doctrine.orm.entity_manager'))));
314 5
                } else {
315
                    $connectionFactoryDef = new Reference($config['connection_factory']);
316
                }
317
318 5
                $spDef = new Definition('Mathielen\ImportEngine\Storage\Provider\DoctrineQueryStorageProvider', array(
319 5
                    $connectionFactoryDef,
320
                    $listResolverDef
321 5
                ));
322 5
                break;
323 5
            case 'service':
324 5
                $spDef = new Definition('Mathielen\ImportEngine\Storage\Provider\ServiceStorageProvider', array(
325 5
                    new Reference('service_container'),
326 5
                    $config['services']
327 5
                ));
328 5
                break;
329 5
            case 'file':
330 5
                $spDef = new Definition('Mathielen\ImportEngine\Storage\Provider\FileStorageProvider', array(
331
                    $formatDiscoverLocalFileStorageFactoryDef
332 5
                ));
333 5
                break;
334 View Code Duplication
            case 'dbal':
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...
335
                $listResolverDef = new Definition(StringOrFileList::class, array($config['queries']));
336
                if (!isset($config['connection_factory'])) {
337
                    $connectionFactoryDef = new Definition(DefaultConnectionFactory::class, array(array('default'=>new Reference('doctrine.dbal.default_connection'))));
338
                } else {
339
                    $connectionFactoryDef = new Reference($config['connection_factory']);
340
                }
341
342
                $spDef = new Definition('Mathielen\ImportEngine\Storage\Provider\DbalStorageProvider', array(
343
                    $connectionFactoryDef,
344
                    $listResolverDef
345
                ));
346
                break;
347
            default:
348
                throw new InvalidConfigurationException('Unknown type for storage provider: '.$config['type']);
349 5
        }
350
351 5
        $storageLocatorDef->addMethodCall('register', array(
352 5
            $id,
353
            $spDef
354 5
        ));
355 5
    }
356
357 9
    private function getStorageFileDefinitionFromUri($uri)
358
    {
359 9
        if (substr($uri, 0, 2) === '@=') {
360
            $uri = new Expression(substr($uri, 2));
361
        }
362
363 9
        return new Definition('SplFileInfo', array(
364
            $uri
365 9
        ));
366
    }
367
368
    /**
369
     * @return Definition
370
     */
371 9
    private function getStorageDef(array $config, Definition $objectFactoryDef=null)
372
    {
373 9
        switch ($config['type']) {
374 9
            case 'file':
375 9
                $fileDef = $this->getStorageFileDefinitionFromUri($config['uri']);
376
377 9
                $format = $config['format'];
378 9
                $storageDef = new Definition('Mathielen\ImportEngine\Storage\LocalFileStorage', array(
379 9
                    $fileDef,
380 9
                    new Definition('Mathielen\ImportEngine\Storage\Format\\'.ucfirst($format['type'])."Format", $format['arguments'])
381 9
                ));
382
383 9
                break;
384 5
            case 'doctrine':
385 5
                $storageDef = new Definition('Mathielen\ImportEngine\Storage\DoctrineStorage', array(
386 5
                    new Reference('doctrine.orm.entity_manager'),
387 5
                    $config['entity']
388 5
                ));
389
390 5
                break;
391 5
            case 'service':
392 5
                $storageDef = new Definition('Mathielen\ImportEngine\Storage\ServiceStorage', array(
393 5
                    array(new Reference($config['service']), $config['method']), //callable
394 5
                    array(),
395
                    $objectFactoryDef //from parameter array
396 5
                ));
397
398 5
                break;
399
            default:
400
                throw new InvalidConfigurationException('Unknown type for storage: '.$config['type']);
401 9
        }
402
403 9
        return $storageDef;
404
    }
405
406 11
    public function getAlias()
407
    {
408 11
        return 'mathielen_import_engine';
409
    }
410
}
411