Completed
Push — master ( 5dfaac...d37f4d )
by Asmir
16:56 queued 07:42
created

JMSSerializerExtension   A

Complexity

Total Complexity 30

Size/Duplication

Total Lines 181
Duplicated Lines 6.63 %

Coupling/Cohesion

Components 0
Dependencies 11

Test Coverage

Coverage 90.83%

Importance

Changes 0
Metric Value
wmc 30
lcom 0
cbo 11
dl 12
loc 181
ccs 109
cts 120
cp 0.9083
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A getConfiguration() 0 4 1
F loadInternal() 12 173 29

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