Completed
Pull Request — master (#556)
by Evgenij
02:53
created

getJsonVisitorConfigs()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 34
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 34
rs 8.8571
cc 2
eloc 17
nc 2
nop 0
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\Tests\DependencyInjection;
20
21
use Doctrine\Common\Annotations\AnnotationReader;
22
use JMS\Serializer\SerializationContext;
23
use JMS\SerializerBundle\JMSSerializerBundle;
24
use JMS\SerializerBundle\Tests\DependencyInjection\Fixture\ObjectUsingExpressionLanguage;
25
use JMS\SerializerBundle\Tests\DependencyInjection\Fixture\SimpleObject;
26
use JMS\SerializerBundle\Tests\DependencyInjection\Fixture\VersionedObject;
27
use Symfony\Component\DependencyInjection\Compiler\ResolveDefinitionTemplatesPass;
28
use Symfony\Component\DependencyInjection\Compiler\ResolveParameterPlaceHoldersPass;
29
use Symfony\Component\DependencyInjection\ContainerBuilder;
30
use Symfony\Component\HttpKernel\KernelInterface;
31
32
class JMSSerializerExtensionTest extends \PHPUnit_Framework_TestCase
33
{
34
    protected function setUp()
35
    {
36
        $this->clearTempDir();
37
    }
38
39
    protected function tearDown()
40
    {
41
        $this->clearTempDir();
42
    }
43
44
    private function clearTempDir()
45
    {
46
        // clear temporary directory
47
        $dir = sys_get_temp_dir().'/serializer';
48
        if (is_dir($dir)) {
49
            foreach (new \RecursiveDirectoryIterator($dir) as $file) {
50
                $filename = $file->getFileName();
51
                if ('.' === $filename || '..' === $filename) {
52
                    continue;
53
                }
54
55
                @unlink($file->getPathName());
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
56
            }
57
58
            @rmdir($dir);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
59
        }
60
    }
61
62
    public function testHasContextFactories()
63
    {
64
        $container = $this->getContainerForConfig(array(array()));
65
66
        $factory = $container->get('jms_serializer.serialization_context_factory');
67
        $this->assertInstanceOf('JMS\Serializer\ContextFactory\SerializationContextFactoryInterface', $factory);
68
69
        $factory = $container->get('jms_serializer.deserialization_context_factory');
70
        $this->assertInstanceOf('JMS\Serializer\ContextFactory\DeserializationContextFactoryInterface', $factory);
71
    }
72
73
    public function testSerializerContextFactoriesAreSet()
74
    {
75
        $container = $this->getContainerForConfig(array(array()));
76
77
        $def = $container->getDefinition('jms_serializer.serializer');
78
        $calls = $def->getMethodCalls();
79
80
        $this->assertCount(2, $calls);
81
82
        $serializationCall = $calls[0];
83
        $this->assertEquals('setSerializationContextFactory', $serializationCall[0]);
84
        $this->assertEquals('jms_serializer.serialization_context_factory', (string)$serializationCall[1][0]);
85
86
        $serializationCall = $calls[1];
87
        $this->assertEquals('setDeserializationContextFactory', $serializationCall[0]);
88
        $this->assertEquals('jms_serializer.deserialization_context_factory', (string)$serializationCall[1][0]);
89
    }
90
91
    public function testConfiguringContextFactories()
92
    {
93
        $container = $this->getContainerForConfig(array(array()));
94
95
        $def = $container->getDefinition('jms_serializer.serialization_context_factory');
96
        $r   = new \ReflectionClass($def->getClass());
97
        $this->assertCount($r->getConstructor()->getNumberOfParameters(), $def->getArguments());
98
99
        $def = $container->getDefinition('jms_serializer.deserialization_context_factory');
100
        $r   = new \ReflectionClass($def->getClass());
101
        $this->assertCount($r->getConstructor()->getNumberOfParameters(), $def->getArguments());
102
    }
103
104
    public function testConfiguringContextFactoriesWithParams()
105
    {
106
        $config = array(
107
            'default_context' => array(
108
                'serialization' => array(
109
                    'version' => 1600,
110
                    'serialize_null' => true,
111
                    'attributes' => array('x' => 1720),
112
                    'groups' => array('Default', 'Registration')
113
                ),
114
                'deserialization' => array(
115
                    'version' => 1640,
116
                    'serialize_null' => false,
117
                    'attributes' => array('x' => 1740),
118
                    'groups' => array('Default', 'Profile')
119
                )
120
            )
121
        );
122
123
        $container = $this->getContainerForConfig(array($config));
124
        $services  = [
125
            'serialization' => 'jms_serializer.serialization_context_factory',
126
            'deserialization' => 'jms_serializer.deserialization_context_factory',
127
        ];
128
        foreach ($services as $configKey => $serviceId) {
129
            $def    = $container->getDefinition($serviceId);
130
            $values = $config['default_context'][$configKey];
131
            $this->assertSame($values['version'], $def->getArgument(0));
132
            $this->assertSame($values['serialize_null'], $def->getArgument(1));
133
            $this->assertSame($values['attributes'], $def->getArgument(2));
134
            $this->assertSame($values['groups'], $def->getArgument(3));
135
        }
136
    }
137
138
    public function testLoad()
139
    {
140
        $container = $this->getContainerForConfig(array(array()));
141
142
        $simpleObject = new SimpleObject('foo', 'bar');
143
        $versionedObject  = new VersionedObject('foo', 'bar');
144
        $serializer = $container->get('serializer');
145
146
        // test that all components have been wired correctly
147
        $this->assertEquals(json_encode(array('name' => 'bar')), $serializer->serialize($versionedObject, 'json'));
148
        $this->assertEquals($simpleObject, $serializer->deserialize($serializer->serialize($simpleObject, 'json'), get_class($simpleObject), 'json'));
149
        $this->assertEquals($simpleObject, $serializer->deserialize($serializer->serialize($simpleObject, 'xml'), get_class($simpleObject), 'xml'));
150
151
        $this->assertEquals(json_encode(array('name' => 'foo')), $serializer->serialize($versionedObject, 'json', SerializationContext::create()->setVersion('0.0.1')));
152
153
        $this->assertEquals(json_encode(array('name' => 'bar')), $serializer->serialize($versionedObject, 'json', SerializationContext::create()->setVersion('1.1.1')));
154
    }
155
156
    /**
157
     * @dataProvider getJsonVisitorConfigs
158
     */
159
    public function testJsonVisitorOptions($expectedOptions, $config)
160
    {
161
        $container = $this->getContainerForConfig(array($config));
162
        $this->assertSame($expectedOptions, $container->get('jms_serializer.json_serialization_visitor')->getOptions());
163
    }
164
165
    public function getJsonVisitorConfigs()
166
    {
167
        $configs = array();
168
169
        if (version_compare(PHP_VERSION, '5.4', '>=')) {
170
            $configs[] = array(JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT, array(
171
                'visitors' => array(
172
                    'json' => array(
173
                        'options' => array('JSON_UNESCAPED_UNICODE', 'JSON_PRETTY_PRINT')
174
                    )
175
                )
176
            ));
177
178
            $configs[] = array(JSON_UNESCAPED_UNICODE, array(
179
                'visitors' => array(
180
                    'json' => array(
181
                        'options' => 'JSON_UNESCAPED_UNICODE'
182
                    )
183
                )
184
            ));
185
        }
186
187
        $configs[] = array(128, array(
188
            'visitors' => array(
189
                'json' => array(
190
                    'options' => 128
191
                )
192
            )
193
        ));
194
195
        $configs[] = array(0, array());
196
197
        return $configs;
198
    }
199
200
    public function testExpressionLanguage()
201
    {
202
        if (!interface_exists('Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface')) {
203
            $this->markTestSkipped("The Symfony Expression Language is not available");
204
        }
205
        $container = $this->getContainerForConfig(array(array()));
206
        $serializer = $container->get('serializer');
207
        // test that all components have been wired correctly
208
        $object = new ObjectUsingExpressionLanguage('foo', true);
209
        $this->assertEquals('{"name":"foo"}', $serializer->serialize($object, 'json'));
210
        $object = new ObjectUsingExpressionLanguage('foo', false);
211
        $this->assertEquals('{}', $serializer->serialize($object, 'json'));
212
    }
213
214
    /**
215
     * @expectedException \JMS\Serializer\Exception\ExpressionLanguageRequiredException
216
     * @expectedExceptionMessage  To use conditional exclude/expose in JMS\SerializerBundle\Tests\DependencyInjection\Fixture\ObjectUsingExpressionLanguage you must configure the expression language.
217
     */
218
    public function testExpressionLanguageNotLoaded()
219
    {
220
        $container = $this->getContainerForConfig(array(array('expression_evaluator' => array('id' => null))));
221
        $serializer = $container->get('serializer');
222
        // test that all components have been wired correctly
223
        $object = new ObjectUsingExpressionLanguage('foo', true);
224
        $serializer->serialize($object, 'json');
225
    }
226
227
    /**
228
     * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException
229
     * @expectedExceptionMessage Invalid configuration for path "jms_serializer.expression_evaluator.id": You need at least symfony/expression language v2.6 or v3.0 to use the expression evaluator features
230
     */
231
    public function testExpressionInvalidEvaluator()
232
    {
233
        $this->getContainerForConfig(array(array('expression_evaluator' => array('id' => 'foo'))));
234
    }
235
236
    /**
237
     * @dataProvider getXmlVisitorWhitelists
238
     */
239
    public function testXmlVisitorOptions($expectedOptions, $config)
240
    {
241
        $container = $this->getContainerForConfig(array($config));
242
        $this->assertSame($expectedOptions, $container->get('jms_serializer.xml_deserialization_visitor')->getDoctypeWhitelist());
243
    }
244
245
    public function getXmlVisitorWhitelists()
246
    {
247
        $configs = array();
248
249
        $configs[] = array(array('good document', 'other good document'), array(
250
            'visitors' => array(
251
                'xml' => array(
252
                    'doctype_whitelist' => array('good document', 'other good document'),
253
                )
254
            )
255
        ));
256
257
        $configs[] = array(array(), array());
258
259
        return $configs;
260
    }
261
262
    public function testXmlVisitorFormatOutput()
263
    {
264
        $config = array(
265
            'visitors' => array(
266
                'xml' => array(
267
                    'format_output' => false,
268
                )
269
            )
270
        );
271
        $container = $this->getContainerForConfig(array($config));
272
273
        $this->assertFalse($container->get('jms_serializer.xml_serialization_visitor')->isFormatOutput());
274
    }
275
276
    public function testXmlVisitorDefaultValueToFormatOutput()
277
    {
278
        $container = $this->getContainerForConfig(array());
279
        $this->assertTrue($container->get('jms_serializer.xml_serialization_visitor')->isFormatOutput());
280
    }
281
282
    private function getContainerForConfig(array $configs, KernelInterface $kernel = null)
283
    {
284
        if (null === $kernel) {
285
            $kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\KernelInterface')->getMock();
286
            $kernel
287
                ->expects($this->any())
288
                ->method('getBundles')
289
                ->will($this->returnValue(array()))
290
            ;
291
        }
292
293
        $bundle = new JMSSerializerBundle($kernel);
0 ignored issues
show
Unused Code introduced by
The call to JMSSerializerBundle::__construct() has too many arguments starting with $kernel.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
294
        $extension = $bundle->getContainerExtension();
295
296
        $container = new ContainerBuilder();
297
        $container->setParameter('kernel.debug', true);
298
        $container->setParameter('kernel.cache_dir', sys_get_temp_dir().'/serializer');
299
        $container->setParameter('kernel.bundles', array());
300
        $container->set('annotation_reader', new AnnotationReader());
301
        $container->set('translator', $this->getMockBuilder('Symfony\\Component\\Translation\\TranslatorInterface')->getMock());
302
        $container->set('debug.stopwatch', $this->getMockBuilder('Symfony\\Component\\Stopwatch\\Stopwatch')->getMock());
303
        $container->registerExtension($extension);
0 ignored issues
show
Bug introduced by
It seems like $extension defined by $bundle->getContainerExtension() on line 294 can be null; however, Symfony\Component\Depend...er::registerExtension() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
304
        $extension->load($configs, $container);
305
306
        $bundle->build($container);
307
308
        $container->getCompilerPassConfig()->setOptimizationPasses(array(
309
            new ResolveParameterPlaceHoldersPass(),
310
            new ResolveDefinitionTemplatesPass(),
311
        ));
312
        $container->getCompilerPassConfig()->setRemovingPasses(array());
313
        $container->compile();
314
315
        return $container;
316
    }
317
}
318