Completed
Push — master ( 739ea2...dd79ae )
by Asmir
13s
created

DependencyInjection/JMSSerializerExtension.php (4 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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