Completed
Pull Request — master (#608)
by Lars
09:34
created

testSerializerIsNotShared()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 16
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 11
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\ObjectUsingExpressionProperties;
26
use JMS\SerializerBundle\Tests\DependencyInjection\Fixture\SimpleObject;
27
use JMS\SerializerBundle\Tests\DependencyInjection\Fixture\VersionedObject;
28
use PHPUnit\Framework\TestCase;
29
use Symfony\Component\DependencyInjection\ContainerBuilder;
30
use Symfony\Component\DependencyInjection\Definition;
31
32
class JMSSerializerExtensionTest extends 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');
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 testSerializerIsNotShared()
92
    {
93
        $unsharedServices = array(
94
            'jms_serializer',
95
            'jms_serializer.json_serialization_visitor',
96
            'jms_serializer.xml_serialization_visitor',
97
            'jms_serializer.yaml_serialization_visitor',
98
            'jms_serializer.json_deserialization_visitor',
99
            'jms_serializer.xml_deserialization_visitor',
100
        );
101
102
        $container = $this->getContainerForConfig(array(array()));
103
        foreach ($unsharedServices as $serviceId) {
104
            $this->assertFalse($container->getDefinition($serviceId)->isShared(), $serviceId . ' is not shared');
105
        }
106
    }
107
108
    public function testSerializerContextFactoriesWithId()
109
    {
110
        $config = array(
111
            'default_context' => array(
112
                'serialization' => array(
113
                    'id' => 'foo'
114
                ),
115
                'deserialization' => array(
116
                    'id' => 'bar'
117
                )
118
            )
119
        );
120
121
        $container = $this->getContainerForConfig(array($config), function(ContainerBuilder $containerBuilder){
122
            $containerBuilder->setDefinition('foo', new Definition('stdClass'));
123
            $containerBuilder->setDefinition('bar', new Definition('stdClass'));
124
        });
125
126
        $def = $container->getDefinition('jms_serializer');
127
        $calls = $def->getMethodCalls();
128
129
        $this->assertCount(2, $calls);
130
131
        $serializationCall = $calls[0];
132
        $this->assertEquals('setSerializationContextFactory', $serializationCall[0]);
133
        $this->assertEquals('foo', (string)$serializationCall[1][0]);
134
135
        $serializationCall = $calls[1];
136
        $this->assertEquals('setDeserializationContextFactory', $serializationCall[0]);
137
        $this->assertEquals('bar', (string)$serializationCall[1][0]);
138
139
        $this->assertEquals('bar', (string)$container->getAlias('jms_serializer.deserialization_context_factory'));
140
        $this->assertEquals('foo', (string)$container->getAlias('jms_serializer.serialization_context_factory'));
141
    }
142
143
    public function testLoadWithoutTranslator()
144
    {
145
        $container = $this->getContainerForConfig(array(array()), function(ContainerBuilder $containerBuilder){
146
            $containerBuilder->set('translator', null);
0 ignored issues
show
Documentation introduced by
null is of type null, but the function expects a object.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
147
        });
148
149
        $def = $container->getDefinition('jms_serializer.form_error_handler');
150
        $this->assertSame(null, $def->getArgument(0));
151
    }
152
153
    public function testConfiguringContextFactories()
154
    {
155
        $container = $this->getContainerForConfig(array(array()));
156
157
        $def = $container->getDefinition('jms_serializer.serialization_context_factory');
158
        $this->assertCount(0, $def->getMethodCalls());
159
160
        $def = $container->getDefinition('jms_serializer.deserialization_context_factory');
161
        $this->assertCount(0, $def->getMethodCalls());
162
    }
163
164
    public function testConfiguringContextFactoriesWithParams()
165
    {
166
        $config = array(
167
            'default_context' => array(
168
                'serialization' => array(
169
                    'version' => 1600,
170
                    'serialize_null' => true,
171
                    'attributes' => array('x' => 1720),
172
                    'groups' => array('Default', 'Registration'),
173
                    'enable_max_depth_checks' => true,
174
                ),
175
                'deserialization' => array(
176
                    'version' => 1640,
177
                    'serialize_null' => false,
178
                    'attributes' => array('x' => 1740),
179
                    'groups' => array('Default', 'Profile'),
180
                    'enable_max_depth_checks' => true,
181
                )
182
            )
183
        );
184
185
        $container = $this->getContainerForConfig(array($config));
186
        $services = [
187
            'serialization' => 'jms_serializer.serialization_context_factory',
188
            'deserialization' => 'jms_serializer.deserialization_context_factory',
189
        ];
190
        foreach ($services as $configKey => $serviceId) {
191
            $def = $container->getDefinition($serviceId);
192
            $values = $config['default_context'][$configKey];
193
194
            $this->assertSame($values['version'], $this->getDefinitionMethodCall($def, 'setVersion')[0]);
195
            $this->assertSame($values['serialize_null'], $this->getDefinitionMethodCall($def, 'setSerializeNulls')[0]);
196
            $this->assertSame($values['attributes'], $this->getDefinitionMethodCall($def, 'setAttributes')[0]);
197
            $this->assertSame($values['groups'], $this->getDefinitionMethodCall($def, 'setGroups')[0]);
198
            $this->assertSame($values['groups'], $this->getDefinitionMethodCall($def, 'setGroups')[0]);
199
            $this->assertSame(array(), $this->getDefinitionMethodCall($def, 'enableMaxDepthChecks'));
200
        }
201
    }
202
203
    public function testConfiguringContextFactoriesWithNullDefaults()
204
    {
205
        $config = array(
206
            'default_context' => array(
207
                'serialization' => array(
208
                    'version' => null,
209
                    'serialize_null' => null,
210
                    'attributes' => [],
211
                    'groups' => null,
212
                ),
213
                'deserialization' => array(
214
                    'version' => null,
215
                    'serialize_null' => null,
216
                    'attributes' => null,
217
                    'groups' => null,
218
                )
219
            )
220
        );
221
222
        $container = $this->getContainerForConfig(array($config));
223
        $services = [
224
            'serialization' => 'jms_serializer.serialization_context_factory',
225
            'deserialization' => 'jms_serializer.deserialization_context_factory',
226
        ];
227
        foreach ($services as $configKey => $serviceId) {
228
            $def = $container->getDefinition($serviceId);
229
            $this->assertCount(0, $def->getMethodCalls());
230
        }
231
    }
232
233
    private function getDefinitionMethodCall(Definition $def, $method)
234
    {
235
        foreach ($def->getMethodCalls() as $call) {
236
            if ($call[0] === $method) {
237
                return $call[1];
238
            }
239
        }
240
        return false;
241
    }
242
243
    public function testLoad()
244
    {
245
        $container = $this->getContainerForConfig(array(array()), function(ContainerBuilder $container) {
246
            $container->getDefinition('jms_serializer.doctrine_object_constructor')->setPublic(true);
247
            $container->getAlias('JMS\Serializer\SerializerInterface')->setPublic(true);
248
            $container->getAlias('JMS\Serializer\ArrayTransformerInterface')->setPublic(true);
249
        });
250
251
        $simpleObject = new SimpleObject('foo', 'bar');
252
        $versionedObject = new VersionedObject('foo', 'bar');
253
        $serializer = $container->get('jms_serializer');
254
255
        $this->assertTrue($container->has('JMS\Serializer\SerializerInterface'), 'Alias should be defined to allow autowiring');
256
        $this->assertTrue($container->has('JMS\Serializer\ArrayTransformerInterface'), 'Alias should be defined to allow autowiring');
257
258
        $this->assertFalse($container->getDefinition('jms_serializer.array_collection_handler')->getArgument(0));
259
260
        // the logic is inverted because arg 0 on doctrine_proxy_subscriber is $skipVirtualTypeInit = false
261
        $this->assertTrue($container->getDefinition('jms_serializer.doctrine_proxy_subscriber')->getArgument(0));
262
        $this->assertFalse($container->getDefinition('jms_serializer.doctrine_proxy_subscriber')->getArgument(1));
263
264
        $this->assertEquals("null", $container->getDefinition('jms_serializer.doctrine_object_constructor')->getArgument(2));
265
266
        // test that all components have been wired correctly
267
        $this->assertEquals(json_encode(array('name' => 'bar')), $serializer->serialize($versionedObject, 'json'));
268
        $this->assertEquals($simpleObject, $serializer->deserialize($serializer->serialize($simpleObject, 'json'), get_class($simpleObject), 'json'));
269
        $this->assertEquals($simpleObject, $serializer->deserialize($serializer->serialize($simpleObject, 'xml'), get_class($simpleObject), 'xml'));
270
271
        $this->assertEquals(json_encode(array('name' => 'foo')), $serializer->serialize($versionedObject, 'json', SerializationContext::create()->setVersion('0.0.1')));
272
273
        $this->assertEquals(json_encode(array('name' => 'bar')), $serializer->serialize($versionedObject, 'json', SerializationContext::create()->setVersion('1.1.1')));
274
    }
275
276
    public function testLoadWithOptions()
277
    {
278
        $container = $this->getContainerForConfig(array(array(
279
            'subscribers' => [
280
                'doctrine_proxy' => [
281
                    'initialize_virtual_types' => true,
282
                    'initialize_excluded' => true,
283
                ],
284
            ],
285
            'object_constructors' => [
286
                'doctrine' => [
287
                    'fallback_strategy' => "exception",
288
                ],
289
            ],
290
            'handlers' => [
291
                'array_collection' => [
292
                    'initialize_excluded' => true,
293
                ],
294
            ],
295
        )), function($container){
296
            $container->getDefinition('jms_serializer.doctrine_object_constructor')->setPublic(true);
297
        });
298
299
        $this->assertTrue($container->getDefinition('jms_serializer.array_collection_handler')->getArgument(0));
300
301
        // the logic is inverted because arg 0 on doctrine_proxy_subscriber is $skipVirtualTypeInit = false
302
        $this->assertFalse($container->getDefinition('jms_serializer.doctrine_proxy_subscriber')->getArgument(0));
303
        $this->assertTrue($container->getDefinition('jms_serializer.doctrine_proxy_subscriber')->getArgument(1));
304
305
        $this->assertEquals("exception", $container->getDefinition('jms_serializer.doctrine_object_constructor')->getArgument(2));
306
    }
307
308
    public function testLoadExistentMetadataDir()
309
    {
310
        $container = $this->getContainerForConfig(array(array(
311
            'metadata' => [
312
                'directories' => [
313
                    'foo' => [
314
                        'namespace_prefix' => 'foo_ns',
315
                        'path' => __DIR__,
316
                    ]
317
                ]
318
            ]
319
        )), function ($container){
320
            $container->getDefinition('jms_serializer.metadata.file_locator')->setPublic(true);
321
        });
322
323
        $fileLocatorDef = $container->getDefinition('jms_serializer.metadata.file_locator');
324
        $directories = $fileLocatorDef->getArgument(0);
325
        $this->assertEquals(['foo_ns' => __DIR__], $directories);
326
    }
327
328
    /**
329
     * @expectedException \JMS\Serializer\Exception\RuntimeException
330
     * @expectedExceptionMessage  The metadata directory "foo_dir" does not exist for the namespace "foo_ns"
331
     */
332
    public function testLoadNotExistentMetadataDir()
333
    {
334
        $this->getContainerForConfig(array(array(
335
            'metadata' => [
336
                'directories' => [
337
                    'foo' => [
338
                        'namespace_prefix' => 'foo_ns',
339
                        'path' => 'foo_dir',
340
                    ]
341
                ]
342
            ]
343
        )));
344
    }
345
346
    /**
347
     * @dataProvider getJsonVisitorConfigs
348
     */
349
    public function testJsonVisitorOptions($expectedOptions, $config)
350
    {
351
        $container = $this->getContainerForConfig(array($config));
352
        $this->assertSame($expectedOptions, $container->get('jms_serializer.json_serialization_visitor')->getOptions());
353
    }
354
355
    public function getJsonVisitorConfigs()
356
    {
357
        $configs = array();
358
359
        if (version_compare(PHP_VERSION, '5.4', '>=')) {
360
            $configs[] = array(JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT, array(
361
                'visitors' => array(
362
                    'json' => array(
363
                        'options' => array('JSON_UNESCAPED_UNICODE', 'JSON_PRETTY_PRINT')
364
                    )
365
                )
366
            ));
367
368
            $configs[] = array(JSON_UNESCAPED_UNICODE, array(
369
                'visitors' => array(
370
                    'json' => array(
371
                        'options' => 'JSON_UNESCAPED_UNICODE'
372
                    )
373
                )
374
            ));
375
        }
376
377
        $configs[] = array(128, array(
378
            'visitors' => array(
379
                'json' => array(
380
                    'options' => 128
381
                )
382
            )
383
        ));
384
385
        $configs[] = array(0, array());
386
387
        return $configs;
388
    }
389
390
    public function testExpressionLanguage()
391
    {
392
        if (!interface_exists('Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface')) {
393
            $this->markTestSkipped("The Symfony Expression Language is not available");
394
        }
395
        $container = $this->getContainerForConfig(array(array()));
396
        $serializer = $container->get('jms_serializer');
397
        // test that all components have been wired correctly
398
        $object = new ObjectUsingExpressionLanguage('foo', true);
399
        $this->assertEquals('{"name":"foo"}', $serializer->serialize($object, 'json'));
400
        $object = new ObjectUsingExpressionLanguage('foo', false);
401
        $this->assertEquals('{}', $serializer->serialize($object, 'json'));
402
    }
403
404
    public function testExpressionLanguageVirtualProperties()
405
    {
406
        if (!interface_exists('Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface')) {
407
            $this->markTestSkipped("The Symfony Expression Language is not available");
408
        }
409
        $container = $this->getContainerForConfig(array(array()));
410
        $serializer = $container->get('jms_serializer');
411
        // test that all components have been wired correctly
412
        $object = new ObjectUsingExpressionProperties('foo');
413
        $this->assertEquals('{"v_prop_name":"foo"}', $serializer->serialize($object, 'json'));
414
    }
415
416
    /**
417
     * @expectedException \JMS\Serializer\Exception\ExpressionLanguageRequiredException
418
     */
419
    public function testExpressionLanguageDisabledVirtualProperties()
420
    {
421
        if (!interface_exists('Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface')) {
422
            $this->markTestSkipped("The Symfony Expression Language is not available");
423
        }
424
        $container = $this->getContainerForConfig(array(array('expression_evaluator' => array('id' => null))));
425
        $serializer = $container->get('jms_serializer');
426
        // test that all components have been wired correctly
427
        $object = new ObjectUsingExpressionProperties('foo');
428
        $serializer->serialize($object, 'json');
429
    }
430
431
    /**
432
     * @expectedException \JMS\Serializer\Exception\ExpressionLanguageRequiredException
433
     * @expectedExceptionMessage  To use conditional exclude/expose in JMS\SerializerBundle\Tests\DependencyInjection\Fixture\ObjectUsingExpressionLanguage you must configure the expression language.
434
     */
435
    public function testExpressionLanguageNotLoaded()
436
    {
437
        $container = $this->getContainerForConfig(array(array('expression_evaluator' => array('id' => null))));
438
        $serializer = $container->get('jms_serializer');
439
        // test that all components have been wired correctly
440
        $object = new ObjectUsingExpressionLanguage('foo', true);
441
        $serializer->serialize($object, 'json');
442
    }
443
444
    /**
445
     * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException
446
     * @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
447
     */
448
    public function testExpressionInvalidEvaluator()
449
    {
450
        if (interface_exists('Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface')) {
451
            $this->markTestSkipped('To pass this test the "symfony/expression-language" component should be available');
452
        }
453
        $this->getContainerForConfig(array(array('expression_evaluator' => array('id' => 'foo'))));
454
    }
455
456
    /**
457
     * @dataProvider getXmlVisitorWhitelists
458
     */
459
    public function testXmlVisitorOptions($expectedOptions, $config)
460
    {
461
        $container = $this->getContainerForConfig(array($config));
462
        $this->assertSame($expectedOptions, $container->get('jms_serializer.xml_deserialization_visitor')->getDoctypeWhitelist());
463
    }
464
465
    public function getXmlVisitorWhitelists()
466
    {
467
        $configs = array();
468
469
        $configs[] = array(array('good document', 'other good document'), array(
470
            'visitors' => array(
471
                'xml' => array(
472
                    'doctype_whitelist' => array('good document', 'other good document'),
473
                )
474
            )
475
        ));
476
477
        $configs[] = array(array(), array());
478
479
        return $configs;
480
    }
481
482
    public function testXmlVisitorFormatOutput()
483
    {
484
        $config = array(
485
            'visitors' => array(
486
                'xml' => array(
487
                    'format_output' => false,
488
                )
489
            )
490
        );
491
        $container = $this->getContainerForConfig(array($config));
492
493
        $this->assertFalse($container->get('jms_serializer.xml_serialization_visitor')->isFormatOutput());
494
    }
495
496
    public function testXmlVisitorDefaultValueToFormatOutput()
497
    {
498
        $container = $this->getContainerForConfig(array());
499
        $this->assertTrue($container->get('jms_serializer.xml_serialization_visitor')->isFormatOutput());
500
    }
501
502
    private function getContainerForConfig(array $configs, callable $configurator = null)
503
    {
504
        $bundle = new JMSSerializerBundle();
505
        $extension = $bundle->getContainerExtension();
506
507
        $container = new ContainerBuilder();
508
        $container->setParameter('kernel.debug', true);
509
        $container->setParameter('kernel.cache_dir', sys_get_temp_dir() . '/serializer');
510
        $container->setParameter('kernel.bundles', array());
511
        $container->set('annotation_reader', new AnnotationReader());
512
        $container->setDefinition('doctrine', new Definition(Registry::class));
513
        $container->set('translator', $this->getMockBuilder('Symfony\\Component\\Translation\\TranslatorInterface')->getMock());
514
        $container->set('debug.stopwatch', $this->getMockBuilder('Symfony\\Component\\Stopwatch\\Stopwatch')->getMock());
515
        $container->registerExtension($extension);
0 ignored issues
show
Bug introduced by
It seems like $extension defined by $bundle->getContainerExtension() on line 505 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...
516
        $extension->load($configs, $container);
517
518
        $bundle->build($container);
519
520
        if ($configurator) {
521
            call_user_func($configurator, $container);
522
        }
523
524
        $container->compile();
525
526
        return $container;
527
    }
528
}
529