Completed
Pull Request — master (#615)
by Asmir
05:17
created

JMSSerializerExtension   A

Complexity

Total Complexity 27

Size/Duplication

Total Lines 175
Duplicated Lines 6.86 %

Coupling/Cohesion

Components 0
Dependencies 10

Test Coverage

Coverage 93.1%

Importance

Changes 0
Metric Value
wmc 27
lcom 0
cbo 10
dl 12
loc 175
rs 10
c 0
b 0
f 0
ccs 108
cts 116
cp 0.931

2 Methods

Rating   Name   Duplication   Size   Complexity  
F loadInternal() 12 167 26
A getConfiguration() 0 4 1

How to fix   Duplicated Code   

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:

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