Completed
Push — master ( bca297...c408c0 )
by Asmir
05:23
created

JMSSerializerExtensionTest::testLoadWithOptions()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 29
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 29
rs 8.8571
c 0
b 0
f 0
cc 1
eloc 16
nc 1
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\ObjectUsingExpressionProperties;
26
use JMS\SerializerBundle\Tests\DependencyInjection\Fixture\SimpleObject;
27
use JMS\SerializerBundle\Tests\DependencyInjection\Fixture\VersionedObject;
28
use Symfony\Component\DependencyInjection\Compiler\ResolveDefinitionTemplatesPass;
29
use Symfony\Component\DependencyInjection\Compiler\ResolveParameterPlaceHoldersPass;
30
use Symfony\Component\DependencyInjection\ContainerBuilder;
31
use Symfony\Component\DependencyInjection\Definition;
32
use Symfony\Component\HttpKernel\KernelInterface;
33
34
class JMSSerializerExtensionTest extends \PHPUnit_Framework_TestCase
35
{
36
    protected function setUp()
37
    {
38
        $this->clearTempDir();
39
    }
40
41
    protected function tearDown()
42
    {
43
        $this->clearTempDir();
44
    }
45
46
    private function clearTempDir()
47
    {
48
        // clear temporary directory
49
        $dir = sys_get_temp_dir() . '/serializer';
50
        if (is_dir($dir)) {
51
            foreach (new \RecursiveDirectoryIterator($dir) as $file) {
52
                $filename = $file->getFileName();
53
                if ('.' === $filename || '..' === $filename) {
54
                    continue;
55
                }
56
57
                @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...
58
            }
59
60
            @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...
61
        }
62
    }
63
64
    public function testHasContextFactories()
65
    {
66
        $container = $this->getContainerForConfig(array(array()));
67
68
        $factory = $container->get('jms_serializer.configured_serialization_context_factory');
69
        $this->assertInstanceOf('JMS\Serializer\ContextFactory\SerializationContextFactoryInterface', $factory);
70
71
        $factory = $container->get('jms_serializer.configured_deserialization_context_factory');
72
        $this->assertInstanceOf('JMS\Serializer\ContextFactory\DeserializationContextFactoryInterface', $factory);
73
    }
74
75
    public function testSerializerContextFactoriesAreSet()
76
    {
77
        $container = $this->getContainerForConfig(array(array()));
78
79
        $def = $container->getDefinition('jms_serializer.serializer');
80
        $calls = $def->getMethodCalls();
81
82
        $this->assertCount(2, $calls);
83
84
        $serializationCall = $calls[0];
85
        $this->assertEquals('setSerializationContextFactory', $serializationCall[0]);
86
        $this->assertEquals('jms_serializer.serialization_context_factory', (string)$serializationCall[1][0]);
87
88
        $serializationCall = $calls[1];
89
        $this->assertEquals('setDeserializationContextFactory', $serializationCall[0]);
90
        $this->assertEquals('jms_serializer.deserialization_context_factory', (string)$serializationCall[1][0]);
91
92
        $this->assertEquals('jms_serializer.configured_deserialization_context_factory', (string)$container->getAlias('jms_serializer.deserialization_context_factory'));
93
        $this->assertEquals('jms_serializer.configured_serialization_context_factory', (string)$container->getAlias('jms_serializer.serialization_context_factory'));
94
    }
95
96
    public function testSerializerContextFactoriesWithId()
97
    {
98
        $config = array(
99
            'default_context' => array(
100
                'serialization' => array(
101
                    'id' => 'foo'
102
                ),
103
                'deserialization' => array(
104
                    'id' => 'bar'
105
                )
106
            )
107
        );
108
109
        $container = $this->getContainerForConfig(array($config));
110
111
        $def = $container->getDefinition('jms_serializer.serializer');
112
        $calls = $def->getMethodCalls();
113
114
        $this->assertCount(2, $calls);
115
116
        $serializationCall = $calls[0];
117
        $this->assertEquals('setSerializationContextFactory', $serializationCall[0]);
118
        $this->assertEquals('jms_serializer.serialization_context_factory', (string)$serializationCall[1][0]);
119
120
        $serializationCall = $calls[1];
121
        $this->assertEquals('setDeserializationContextFactory', $serializationCall[0]);
122
        $this->assertEquals('jms_serializer.deserialization_context_factory', (string)$serializationCall[1][0]);
123
124
        $this->assertEquals('bar', (string)$container->getAlias('jms_serializer.deserialization_context_factory'));
125
        $this->assertEquals('foo', (string)$container->getAlias('jms_serializer.serialization_context_factory'));
126
    }
127
128
    public function testConfiguringContextFactories()
129
    {
130
        $container = $this->getContainerForConfig(array(array()));
131
132
        $def = $container->getDefinition('jms_serializer.configured_serialization_context_factory');
133
        $this->assertCount(0, $def->getMethodCalls());
134
135
        $def = $container->getDefinition('jms_serializer.configured_deserialization_context_factory');
136
        $this->assertCount(0, $def->getMethodCalls());
137
    }
138
139
    public function testConfiguringContextFactoriesWithParams()
140
    {
141
        $config = array(
142
            'default_context' => array(
143
                'serialization' => array(
144
                    'version' => 1600,
145
                    'serialize_null' => true,
146
                    'attributes' => array('x' => 1720),
147
                    'groups' => array('Default', 'Registration'),
148
                    'enable_max_depth_checks' => true,
149
                ),
150
                'deserialization' => array(
151
                    'version' => 1640,
152
                    'serialize_null' => false,
153
                    'attributes' => array('x' => 1740),
154
                    'groups' => array('Default', 'Profile'),
155
                    'enable_max_depth_checks' => true,
156
                )
157
            )
158
        );
159
160
        $container = $this->getContainerForConfig(array($config));
161
        $services = [
162
            'serialization' => 'jms_serializer.configured_serialization_context_factory',
163
            'deserialization' => 'jms_serializer.configured_deserialization_context_factory',
164
        ];
165
        foreach ($services as $configKey => $serviceId) {
166
            $def = $container->getDefinition($serviceId);
167
            $values = $config['default_context'][$configKey];
168
169
            $this->assertSame($values['version'], $this->getDefinitionMethodCall($def, 'setVersion')[0]);
170
            $this->assertSame($values['serialize_null'], $this->getDefinitionMethodCall($def, 'setSerializeNulls')[0]);
171
            $this->assertSame($values['attributes'], $this->getDefinitionMethodCall($def, 'setAttributes')[0]);
172
            $this->assertSame($values['groups'], $this->getDefinitionMethodCall($def, 'setGroups')[0]);
173
            $this->assertSame($values['groups'], $this->getDefinitionMethodCall($def, 'setGroups')[0]);
174
            $this->assertSame(array(), $this->getDefinitionMethodCall($def, 'enableMaxDepthChecks'));
175
        }
176
    }
177
178
    public function testConfiguringContextFactoriesWithNullDefaults()
179
    {
180
        $config = array(
181
            'default_context' => array(
182
                'serialization' => array(
183
                    'version' => null,
184
                    'serialize_null' => null,
185
                    'attributes' => [],
186
                    'groups' => null,
187
                ),
188
                'deserialization' => array(
189
                    'version' => null,
190
                    'serialize_null' => null,
191
                    'attributes' => null,
192
                    'groups' => null,
193
                )
194
            )
195
        );
196
197
        $container = $this->getContainerForConfig(array($config));
198
        $services = [
199
            'serialization' => 'jms_serializer.configured_serialization_context_factory',
200
            'deserialization' => 'jms_serializer.configured_deserialization_context_factory',
201
        ];
202
        foreach ($services as $configKey => $serviceId) {
203
            $def = $container->getDefinition($serviceId);
204
            $this->assertCount(0, $def->getMethodCalls());
205
        }
206
    }
207
208
    private function getDefinitionMethodCall(Definition $def, $method)
209
    {
210
        foreach ($def->getMethodCalls() as $call) {
211
            if ($call[0] === $method) {
212
                return $call[1];
213
            }
214
        }
215
        return false;
216
    }
217
218
    public function testLoad()
219
    {
220
        $container = $this->getContainerForConfig(array(array()));
221
222
        $simpleObject = new SimpleObject('foo', 'bar');
223
        $versionedObject = new VersionedObject('foo', 'bar');
224
        $serializer = $container->get('serializer');
225
226
        $this->assertTrue($container->has('JMS\Serializer\SerializerInterface'), 'Alias should be defined to allow autowiring');
227
        $this->assertTrue($container->has('JMS\Serializer\ArrayTransformerInterface'), 'Alias should be defined to allow autowiring');
228
229
        $this->assertTrue($container->getDefinition('jms_serializer.array_collection_handler')->getArgument(0));
230
231
        // the logic is inverted because arg 0 on doctrine_proxy_subscriber is $skipVirtualTypeInit = false
232
        $this->assertFalse($container->getDefinition('jms_serializer.doctrine_proxy_subscriber')->getArgument(0));
233
        $this->assertTrue($container->getDefinition('jms_serializer.doctrine_proxy_subscriber')->getArgument(1));
234
235
        $this->assertEquals("null", $container->getDefinition('jms_serializer.doctrine_object_constructor')->getArgument(2));
236
237
        // test that all components have been wired correctly
238
        $this->assertEquals(json_encode(array('name' => 'bar')), $serializer->serialize($versionedObject, 'json'));
239
        $this->assertEquals($simpleObject, $serializer->deserialize($serializer->serialize($simpleObject, 'json'), get_class($simpleObject), 'json'));
240
        $this->assertEquals($simpleObject, $serializer->deserialize($serializer->serialize($simpleObject, 'xml'), get_class($simpleObject), 'xml'));
241
242
        $this->assertEquals(json_encode(array('name' => 'foo')), $serializer->serialize($versionedObject, 'json', SerializationContext::create()->setVersion('0.0.1')));
243
244
        $this->assertEquals(json_encode(array('name' => 'bar')), $serializer->serialize($versionedObject, 'json', SerializationContext::create()->setVersion('1.1.1')));
245
    }
246
247
    public function testLoadWithOptions()
248
    {
249
        $container = $this->getContainerForConfig(array(array(
250
            'subscribers' => [
251
                'doctrine_proxy' => [
252
                    'initialize_virtual_types' => false,
253
                    'initialize_excluded' => false,
254
                ],
255
            ],
256
            'object_constructors' => [
257
                'doctrine' => [
258
                    'fallback_strategy' => "exception",
259
                ],
260
            ],
261
            'handlers' => [
262
                'array_collection' => [
263
                    'initialize_excluded' => false,
264
                ],
265
            ],
266
        )));
267
268
        $this->assertFalse($container->getDefinition('jms_serializer.array_collection_handler')->getArgument(0));
269
270
        // the logic is inverted because arg 0 on doctrine_proxy_subscriber is $skipVirtualTypeInit = false
271
        $this->assertTrue($container->getDefinition('jms_serializer.doctrine_proxy_subscriber')->getArgument(0));
272
        $this->assertFalse($container->getDefinition('jms_serializer.doctrine_proxy_subscriber')->getArgument(1));
273
274
        $this->assertEquals("exception", $container->getDefinition('jms_serializer.doctrine_object_constructor')->getArgument(2));
275
    }
276
277
    /**
278
     * @dataProvider getJsonVisitorConfigs
279
     */
280
    public function testJsonVisitorOptions($expectedOptions, $config)
281
    {
282
        $container = $this->getContainerForConfig(array($config));
283
        $this->assertSame($expectedOptions, $container->get('jms_serializer.json_serialization_visitor')->getOptions());
284
    }
285
286
    public function getJsonVisitorConfigs()
287
    {
288
        $configs = array();
289
290
        if (version_compare(PHP_VERSION, '5.4', '>=')) {
291
            $configs[] = array(JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT, array(
292
                'visitors' => array(
293
                    'json' => array(
294
                        'options' => array('JSON_UNESCAPED_UNICODE', 'JSON_PRETTY_PRINT')
295
                    )
296
                )
297
            ));
298
299
            $configs[] = array(JSON_UNESCAPED_UNICODE, array(
300
                'visitors' => array(
301
                    'json' => array(
302
                        'options' => 'JSON_UNESCAPED_UNICODE'
303
                    )
304
                )
305
            ));
306
        }
307
308
        $configs[] = array(128, array(
309
            'visitors' => array(
310
                'json' => array(
311
                    'options' => 128
312
                )
313
            )
314
        ));
315
316
        $configs[] = array(0, array());
317
318
        return $configs;
319
    }
320
321
    public function testExpressionLanguage()
322
    {
323
        if (!interface_exists('Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface')) {
324
            $this->markTestSkipped("The Symfony Expression Language is not available");
325
        }
326
        $container = $this->getContainerForConfig(array(array()));
327
        $serializer = $container->get('serializer');
328
        // test that all components have been wired correctly
329
        $object = new ObjectUsingExpressionLanguage('foo', true);
330
        $this->assertEquals('{"name":"foo"}', $serializer->serialize($object, 'json'));
331
        $object = new ObjectUsingExpressionLanguage('foo', false);
332
        $this->assertEquals('{}', $serializer->serialize($object, 'json'));
333
    }
334
335
    public function testExpressionLanguageVirtualProperties()
336
    {
337
        if (!interface_exists('Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface')) {
338
            $this->markTestSkipped("The Symfony Expression Language is not available");
339
        }
340
        $container = $this->getContainerForConfig(array(array()));
341
        $serializer = $container->get('serializer');
342
        // test that all components have been wired correctly
343
        $object = new ObjectUsingExpressionProperties('foo');
344
        $this->assertEquals('{"v_prop_name":"foo"}', $serializer->serialize($object, 'json'));
345
    }
346
347
    /**
348
     * @expectedException \JMS\Serializer\Exception\ExpressionLanguageRequiredException
349
     */
350
    public function testExpressionLanguageDisabledVirtualProperties()
351
    {
352
        if (!interface_exists('Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface')) {
353
            $this->markTestSkipped("The Symfony Expression Language is not available");
354
        }
355
        $container = $this->getContainerForConfig(array(array('expression_evaluator' => array('id' => null))));
356
        $serializer = $container->get('serializer');
357
        // test that all components have been wired correctly
358
        $object = new ObjectUsingExpressionProperties('foo');
359
        $serializer->serialize($object, 'json');
360
    }
361
362
    /**
363
     * @expectedException \JMS\Serializer\Exception\ExpressionLanguageRequiredException
364
     * @expectedExceptionMessage  To use conditional exclude/expose in JMS\SerializerBundle\Tests\DependencyInjection\Fixture\ObjectUsingExpressionLanguage you must configure the expression language.
365
     */
366
    public function testExpressionLanguageNotLoaded()
367
    {
368
        $container = $this->getContainerForConfig(array(array('expression_evaluator' => array('id' => null))));
369
        $serializer = $container->get('serializer');
370
        // test that all components have been wired correctly
371
        $object = new ObjectUsingExpressionLanguage('foo', true);
372
        $serializer->serialize($object, 'json');
373
    }
374
375
    /**
376
     * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException
377
     * @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
378
     */
379
    public function testExpressionInvalidEvaluator()
380
    {
381
        if (interface_exists('Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface')) {
382
            $this->markTestSkipped('To pass this test the "symfony/expression-language" component should be available');
383
        }
384
        $this->getContainerForConfig(array(array('expression_evaluator' => array('id' => 'foo'))));
385
    }
386
387
    /**
388
     * @dataProvider getXmlVisitorWhitelists
389
     */
390
    public function testXmlVisitorOptions($expectedOptions, $config)
391
    {
392
        $container = $this->getContainerForConfig(array($config));
393
        $this->assertSame($expectedOptions, $container->get('jms_serializer.xml_deserialization_visitor')->getDoctypeWhitelist());
394
    }
395
396
    public function getXmlVisitorWhitelists()
397
    {
398
        $configs = array();
399
400
        $configs[] = array(array('good document', 'other good document'), array(
401
            'visitors' => array(
402
                'xml' => array(
403
                    'doctype_whitelist' => array('good document', 'other good document'),
404
                )
405
            )
406
        ));
407
408
        $configs[] = array(array(), array());
409
410
        return $configs;
411
    }
412
413
    public function testXmlVisitorFormatOutput()
414
    {
415
        $config = array(
416
            'visitors' => array(
417
                'xml' => array(
418
                    'format_output' => false,
419
                )
420
            )
421
        );
422
        $container = $this->getContainerForConfig(array($config));
423
424
        $this->assertFalse($container->get('jms_serializer.xml_serialization_visitor')->isFormatOutput());
425
    }
426
427
    public function testXmlVisitorDefaultValueToFormatOutput()
428
    {
429
        $container = $this->getContainerForConfig(array());
430
        $this->assertTrue($container->get('jms_serializer.xml_serialization_visitor')->isFormatOutput());
431
    }
432
433
    private function getContainerForConfig(array $configs, KernelInterface $kernel = null)
434
    {
435
        if (null === $kernel) {
436
            $kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\KernelInterface')->getMock();
437
            $kernel
438
                ->expects($this->any())
439
                ->method('getBundles')
440
                ->will($this->returnValue(array()));
441
        }
442
443
        $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...
444
        $extension = $bundle->getContainerExtension();
445
446
        $container = new ContainerBuilder();
447
        $container->setParameter('kernel.debug', true);
448
        $container->setParameter('kernel.cache_dir', sys_get_temp_dir() . '/serializer');
449
        $container->setParameter('kernel.bundles', array());
450
        $container->set('annotation_reader', new AnnotationReader());
451
        $container->set('translator', $this->getMockBuilder('Symfony\\Component\\Translation\\TranslatorInterface')->getMock());
452
        $container->set('debug.stopwatch', $this->getMockBuilder('Symfony\\Component\\Stopwatch\\Stopwatch')->getMock());
453
        $container->registerExtension($extension);
0 ignored issues
show
Bug introduced by
It seems like $extension defined by $bundle->getContainerExtension() on line 444 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...
454
        $extension->load($configs, $container);
455
456
        $bundle->build($container);
457
458
        $container->getCompilerPassConfig()->setOptimizationPasses(array(
459
            new ResolveParameterPlaceHoldersPass(),
460
            new ResolveDefinitionTemplatesPass(),
461
        ));
462
        $container->getCompilerPassConfig()->setRemovingPasses(array());
463
        $container->compile();
464
465
        return $container;
466
    }
467
}
468