Completed
Pull Request — master (#612)
by Benjamin
10:49
created

JMSSerializerExtension::loadInternal()   F

Complexity

Conditions 29
Paths > 20000

Size

Total Lines 173
Code Lines 110

Duplication

Lines 12
Ratio 6.94 %

Code Coverage

Tests 110
CRAP Score 29.2621

Importance

Changes 0
Metric Value
dl 12
loc 173
ccs 110
cts 118
cp 0.9322
rs 2
c 0
b 0
f 0
cc 29
eloc 110
nc 105616
nop 2
crap 29.2621

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