Completed
Pull Request — master (#556)
by Evgenij
02:50
created

JMSSerializerExtension::loadInternal()   F

Complexity

Conditions 22
Paths 12148

Size

Total Lines 139
Code Lines 85

Duplication

Lines 12
Ratio 8.63 %

Code Coverage

Tests 84
CRAP Score 22.3187

Importance

Changes 0
Metric Value
dl 12
loc 139
rs 2
c 0
b 0
f 0
ccs 84
cts 92
cp 0.913
cc 22
eloc 85
nc 12148
nop 2
crap 22.3187

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/*
4
 * Copyright 2011 Johannes M. Schmitt <[email protected]>
5
 *
6
 * Licensed under the Apache License, Version 2.0 (the "License");
7
 * you may not use this file except in compliance with the License.
8
 * You may obtain a copy of the License at
9
 *
10
 * http://www.apache.org/licenses/LICENSE-2.0
11
 *
12
 * Unless required by applicable law or agreed to in writing, software
13
 * distributed under the License is distributed on an "AS IS" BASIS,
14
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
 * See the License for the specific language governing permissions and
16
 * limitations under the License.
17
 */
18
19
namespace JMS\SerializerBundle\DependencyInjection;
20
21
use JMS\Serializer\Exception\RuntimeException;
22
use Symfony\Component\Config\FileLocator;
23
use Symfony\Component\DependencyInjection\Alias;
24
use Symfony\Component\DependencyInjection\ContainerBuilder;
25
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
26
use Symfony\Component\DependencyInjection\Reference;
27
use Symfony\Component\HttpKernel\DependencyInjection\ConfigurableExtension;
28
29
class JMSSerializerExtension extends ConfigurableExtension
30
{
31 37
    public function loadInternal(array $config, ContainerBuilder $container)
32
    {
33 37
        $loader = new XmlFileLoader($container, new FileLocator(array(
34 37
                        __DIR__.'/../Resources/config/')));
35 37
        $loader->load('services.xml');
36
37
        // Built-in handlers.
38 37
        $container->getDefinition('jms_serializer.datetime_handler')
39 37
            ->addArgument($config['handlers']['datetime']['default_format'])
40 37
            ->addArgument($config['handlers']['datetime']['default_timezone'])
41 37
            ->addArgument($config['handlers']['datetime']['cdata'])
42
        ;
43
44
        // property naming
45
        $container
46 37
            ->getDefinition('jms_serializer.camel_case_naming_strategy')
47 37
            ->addArgument($config['property_naming']['separator'])
48 37
            ->addArgument($config['property_naming']['lower_case'])
49
        ;
50 37
        if ($config['property_naming']['enable_cache']) {
51
            $container
52 37
                ->getDefinition('jms_serializer.cache_naming_strategy')
53 37
                ->addArgument(new Reference((string) $container->getAlias('jms_serializer.naming_strategy')))
54
            ;
55 37
            $container->setAlias('jms_serializer.naming_strategy', 'jms_serializer.cache_naming_strategy');
56 37
        }
57
58 37
        $bundles = $container->getParameter('kernel.bundles');
59
60 37
        if (!empty($config['expression_evaluator']['id'])) {
61
            $container
62 35
                ->getDefinition('jms_serializer.serializer')
63 35
                ->replaceArgument(7, new Reference($config['expression_evaluator']['id']));
64
65
            $container
66 35
                ->setAlias('jms_serializer.accessor_strategy', 'jms_serializer.accessor_strategy.expression');
67
68 35
        } else {
69 2
            $container->removeDefinition('jms_serializer.expression_evaluator');
70 2
            $container->removeDefinition('jms_serializer.accessor_strategy.expression');
71
        }
72
73
        // metadata
74 37
        if ('none' === $config['metadata']['cache']) {
75
            $container->removeAlias('jms_serializer.metadata.cache');
76 37
        } elseif ('file' === $config['metadata']['cache']) {
77
            $container
78 37
                ->getDefinition('jms_serializer.metadata.cache.file_cache')
79 37
                ->replaceArgument(0, $config['metadata']['file_cache']['dir'])
80
            ;
81
82 37
            $dir = $container->getParameterBag()->resolveValue($config['metadata']['file_cache']['dir']);
83 37
            if (!is_dir($dir) && !@mkdir($dir, 0777, true) && !is_dir($dir)) {
84
                throw new RuntimeException(sprintf('Could not create cache directory "%s".', $dir));
85
            }
86 37
        } else {
87
            $container->setAlias('jms_serializer.metadata.cache', new Alias($config['metadata']['cache'], false));
88
        }
89
90 37
        if ($config['metadata']['infer_types_from_doctrine_metadata'] === false) {
91 1
            $container->setParameter('jms_serializer.infer_types_from_doctrine_metadata', false);
92 1
        }
93
94
        $container
95 37
            ->getDefinition('jms_serializer.metadata_factory')
96 37
            ->replaceArgument(2, $config['metadata']['debug'])
97
        ;
98
99
        // directories
100 37
        $directories = array();
101 37
        if ($config['metadata']['auto_detection']) {
102 37
            foreach ($bundles as $name => $class) {
103 1
                $ref = new \ReflectionClass($class);
104
105 1
                $directories[$ref->getNamespaceName()] = dirname($ref->getFileName()).'/Resources/config/serializer';
106 37
            }
107 37
        }
108 37
        foreach ($config['metadata']['directories'] as $directory) {
109 1
            $directory['path'] = rtrim(str_replace('\\', '/', $directory['path']), '/');
110
111 1
            if ('@' === $directory['path'][0]) {
112 1
                $pathParts = explode('/', $directory['path']);
113 1
                $bundleName = substr($pathParts[0], 1);
114
115 1
                if (!isset($bundles[$bundleName])) {
116
                    throw new RuntimeException(sprintf('The bundle "%s" has not been registered with AppKernel. Available bundles: %s', $bundleName, implode(', ', array_keys($bundles))));
117
                }
118
119 1
                $ref = new \ReflectionClass($bundles[$bundleName]);
120 1
                $directory['path'] = dirname($ref->getFileName()).substr($directory['path'], strlen('@'.$bundleName));
121 1
            }
122
123 1
            $directories[rtrim($directory['namespace_prefix'], '\\')] = rtrim($directory['path'], '\\/');
124 37
        }
125
        $container
126 37
            ->getDefinition('jms_serializer.metadata.file_locator')
127 37
            ->replaceArgument(0, $directories)
128
        ;
129
130 37
        $container->setParameter('jms_serializer.xml_deserialization_visitor.doctype_whitelist', $config['visitors']['xml']['doctype_whitelist']);
131 37
        $container->setParameter('jms_serializer.xml_serialization_visitor.format_output', $config['visitors']['xml']['format_output']);
132 37
        $container->setParameter('jms_serializer.json_serialization_visitor.options', $config['visitors']['json']['options']);
133
134 37
        if ( ! $config['enable_short_alias']) {
135
            $container->removeAlias('serializer');
136
        }
137
138 37
        if ( ! $container->getParameter('kernel.debug')) {
139
            $container->removeDefinition('jms_serializer.stopwatch_subscriber');
140
        }
141
142
        // context factories
143
        $services = [
144 37
            'serialization' => 'jms_serializer.configured_serialization_context_factory',
145 37
            'deserialization' => 'jms_serializer.configured_deserialization_context_factory',
146 37
        ];
147 37
        foreach ($services as $configKey => $serviceId) {
148 37
            $contextFactory = $container->getDefinition($serviceId);
149
150 37
            if (isset($config['default_context'][$configKey]['id'])) {
151 1
                $container->setAlias('jms_serializer.' . $configKey . '_context_factory', $config['default_context'][$configKey]['id']);
152 1
                $container->removeDefinition($serviceId);
153 1
                continue;
154
            }
155
156 36 View Code Duplication
            if (isset($config['default_context'][$configKey]['version'])) {
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...
157 1
                $contextFactory->addMethodCall('setVersion', [$config['default_context'][$configKey]['version']]);
158 1
            }
159 36 View Code Duplication
            if (isset($config['default_context'][$configKey]['serialize_null'])) {
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...
160 1
                $contextFactory->addMethodCall('setSerializeNulls', [$config['default_context'][$configKey]['serialize_null']]);
161 1
            }
162 36 View Code Duplication
            if (!empty($config['default_context'][$configKey]['attributes'])) {
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...
163 1
                $contextFactory->addMethodCall('setAttributes', [$config['default_context'][$configKey]['attributes']]);
164 1
            }
165 36 View Code Duplication
            if (!empty($config['default_context'][$configKey]['groups'])) {
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...
166 1
                $contextFactory->addMethodCall('setGroups', [$config['default_context'][$configKey]['groups']]);
167 1
            }
168 37
        }
169 37
    }
170
171 37
    public function getConfiguration(array $config, ContainerBuilder $container)
172
    {
173 37
        return new Configuration($container->getParameterBag()->resolveValue('%kernel.debug%'));
174
    }
175
}
176