Completed
Pull Request — master (#615)
by Asmir
01:42
created

JMSSerializerExtension   A

Complexity

Total Complexity 27

Size/Duplication

Total Lines 174
Duplicated Lines 6.9 %

Coupling/Cohesion

Components 0
Dependencies 10

Test Coverage

Coverage 90.43%

Importance

Changes 0
Metric Value
wmc 27
lcom 0
cbo 10
dl 12
loc 174
rs 10
c 0
b 0
f 0
ccs 104
cts 115
cp 0.9043

2 Methods

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