Completed
Push — master ( d7c858...c3a5e7 )
by Markus
02:53
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 92.49%

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