Completed
Push — master ( 85ee03...d3810b )
by Asmir
04:47
created

JMSSerializerExtension::loadInternal()   F

Complexity

Conditions 25
Paths > 20000

Size

Total Lines 159
Code Lines 99

Duplication

Lines 12
Ratio 7.55 %

Code Coverage

Tests 100
CRAP Score 25.2542

Importance

Changes 0
Metric Value
dl 12
loc 159
ccs 100
cts 108
cp 0.9259
rs 2
c 0
b 0
f 0
cc 25
eloc 99
nc 26408
nop 2
crap 25.2542

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