Completed
Push — master ( bca297...c408c0 )
by Asmir
05:23
created

JMSSerializerExtension::loadInternal()   F

Complexity

Conditions 24
Paths > 20000

Size

Total Lines 153
Code Lines 96

Duplication

Lines 12
Ratio 7.84 %

Code Coverage

Tests 97
CRAP Score 24.2548

Importance

Changes 0
Metric Value
dl 12
loc 153
ccs 97
cts 105
cp 0.9238
rs 2
c 0
b 0
f 0
cc 24
eloc 96
nc 45800
nop 2
crap 24.2548

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 43
    public function loadInternal(array $config, ContainerBuilder $container)
32
    {
33 43
        $loader = new XmlFileLoader($container, new FileLocator(array(
34 43
            __DIR__ . '/../Resources/config/')));
35 43
        $loader->load('services.xml');
36
37
        // Built-in handlers.
38 43
        $container->getDefinition('jms_serializer.datetime_handler')
39 43
            ->addArgument($config['handlers']['datetime']['default_format'])
40 43
            ->addArgument($config['handlers']['datetime']['default_timezone'])
41 43
            ->addArgument($config['handlers']['datetime']['cdata']);
42
43 43
        $container->getDefinition('jms_serializer.array_collection_handler')
44 43
            ->replaceArgument(0, $config['handlers']['array_collection']['initialize_excluded']);
45
46
        // Built-in subscribers.
47 43
        $container->getDefinition('jms_serializer.doctrine_proxy_subscriber')
48 43
            ->replaceArgument(0, !$config['subscribers']['doctrine_proxy']['initialize_virtual_types'])
49 43
            ->replaceArgument(1, $config['subscribers']['doctrine_proxy']['initialize_excluded']);
50
51
        // Built-in object constructor.
52 43
        $container->getDefinition('jms_serializer.doctrine_object_constructor')
53 43
            ->replaceArgument(2, $config['object_constructors']['doctrine']['fallback_strategy']);
54
55
        // property naming
56
        $container
57 43
            ->getDefinition('jms_serializer.camel_case_naming_strategy')
58 43
            ->addArgument($config['property_naming']['separator'])
59 43
            ->addArgument($config['property_naming']['lower_case']);
60
61 43
        if (!empty($config['property_naming']['id'])) {
62 1
            $container->setAlias('jms_serializer.naming_strategy', $config['property_naming']['id']);
63 1
        }
64
65 43
        if ($config['property_naming']['enable_cache']) {
66
            $container
67 42
                ->getDefinition('jms_serializer.cache_naming_strategy')
68 42
                ->addArgument(new Reference((string)$container->getAlias('jms_serializer.naming_strategy')));
69 42
            $container->setAlias('jms_serializer.naming_strategy', 'jms_serializer.cache_naming_strategy');
70 42
        }
71
72 43
        $bundles = $container->getParameter('kernel.bundles');
73
74 43
        if (!empty($config['expression_evaluator']['id'])) {
75
            $container
76 41
                ->getDefinition('jms_serializer.serializer')
77 41
                ->replaceArgument(7, new Reference($config['expression_evaluator']['id']));
78
79
            $container
80 41
                ->setAlias('jms_serializer.accessor_strategy', 'jms_serializer.accessor_strategy.expression');
81
82 41
        } else {
83 2
            $container->removeDefinition('jms_serializer.expression_evaluator');
84 2
            $container->removeDefinition('jms_serializer.accessor_strategy.expression');
85
        }
86
87
        // metadata
88 43
        if ('none' === $config['metadata']['cache']) {
89
            $container->removeAlias('jms_serializer.metadata.cache');
90 43
        } elseif ('file' === $config['metadata']['cache']) {
91
            $container
92 43
                ->getDefinition('jms_serializer.metadata.cache.file_cache')
93 43
                ->replaceArgument(0, $config['metadata']['file_cache']['dir']);
94
95 43
            $dir = $container->getParameterBag()->resolveValue($config['metadata']['file_cache']['dir']);
96 43
            if (!is_dir($dir) && !@mkdir($dir, 0777, true) && !is_dir($dir)) {
97
                throw new RuntimeException(sprintf('Could not create cache directory "%s".', $dir));
98
            }
99 43
        } else {
100
            $container->setAlias('jms_serializer.metadata.cache', new Alias($config['metadata']['cache'], false));
101
        }
102
103 43
        if ($config['metadata']['infer_types_from_doctrine_metadata'] === false) {
104 1
            $container->setParameter('jms_serializer.infer_types_from_doctrine_metadata', false);
105 1
        }
106
107
        $container
108 43
            ->getDefinition('jms_serializer.metadata_factory')
109 43
            ->replaceArgument(2, $config['metadata']['debug']);
110
111
        // directories
112 43
        $directories = array();
113 43
        if ($config['metadata']['auto_detection']) {
114 43
            foreach ($bundles as $name => $class) {
115 1
                $ref = new \ReflectionClass($class);
116
117 1
                $directories[$ref->getNamespaceName()] = dirname($ref->getFileName()) . '/Resources/config/serializer';
118 43
            }
119 43
        }
120 43
        foreach ($config['metadata']['directories'] as $directory) {
121 1
            $directory['path'] = rtrim(str_replace('\\', '/', $directory['path']), '/');
122
123 1
            if ('@' === $directory['path'][0]) {
124 1
                $pathParts = explode('/', $directory['path']);
125 1
                $bundleName = substr($pathParts[0], 1);
126
127 1
                if (!isset($bundles[$bundleName])) {
128
                    throw new RuntimeException(sprintf('The bundle "%s" has not been registered with AppKernel. Available bundles: %s', $bundleName, implode(', ', array_keys($bundles))));
129
                }
130
131 1
                $ref = new \ReflectionClass($bundles[$bundleName]);
132 1
                $directory['path'] = dirname($ref->getFileName()) . substr($directory['path'], strlen('@' . $bundleName));
133 1
            }
134
135 1
            $directories[rtrim($directory['namespace_prefix'], '\\')] = rtrim($directory['path'], '\\/');
136 43
        }
137
        $container
138 43
            ->getDefinition('jms_serializer.metadata.file_locator')
139 43
            ->replaceArgument(0, $directories);
140
141 43
        $container->setParameter('jms_serializer.xml_deserialization_visitor.doctype_whitelist', $config['visitors']['xml']['doctype_whitelist']);
142 43
        $container->setParameter('jms_serializer.xml_serialization_visitor.format_output', $config['visitors']['xml']['format_output']);
143 43
        $container->setParameter('jms_serializer.json_serialization_visitor.options', $config['visitors']['json']['options']);
144
145 43
        if (!$config['enable_short_alias']) {
146
            $container->removeAlias('serializer');
147
        }
148
149 43
        if (!$container->getParameter('kernel.debug')) {
150
            $container->removeDefinition('jms_serializer.stopwatch_subscriber');
151
        }
152
153
        // context factories
154
        $services = [
155 43
            'serialization' => 'jms_serializer.configured_serialization_context_factory',
156 43
            'deserialization' => 'jms_serializer.configured_deserialization_context_factory',
157 43
        ];
158 43
        foreach ($services as $configKey => $serviceId) {
159 43
            $contextFactory = $container->getDefinition($serviceId);
160
161 43
            if (isset($config['default_context'][$configKey]['id'])) {
162 1
                $container->setAlias('jms_serializer.' . $configKey . '_context_factory', $config['default_context'][$configKey]['id']);
163 1
                $container->removeDefinition($serviceId);
164 1
                continue;
165
            }
166
167 42 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...
168 1
                $contextFactory->addMethodCall('setVersion', [$config['default_context'][$configKey]['version']]);
169 1
            }
170 42 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...
171 1
                $contextFactory->addMethodCall('setSerializeNulls', [$config['default_context'][$configKey]['serialize_null']]);
172 1
            }
173 42 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...
174 1
                $contextFactory->addMethodCall('setAttributes', [$config['default_context'][$configKey]['attributes']]);
175 1
            }
176 42 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...
177 1
                $contextFactory->addMethodCall('setGroups', [$config['default_context'][$configKey]['groups']]);
178 1
            }
179 42
            if (!empty($config['default_context'][$configKey]['enable_max_depth_checks'])) {
180 1
                $contextFactory->addMethodCall('enableMaxDepthChecks');
181 1
            }
182 43
        }
183 43
    }
184
185 43
    public function getConfiguration(array $config, ContainerBuilder $container)
186
    {
187 43
        return new Configuration($container->getParameterBag()->resolveValue('%kernel.debug%'));
188
    }
189
}
190