Completed
Push — master ( 85ee03...d3810b )
by Asmir
04:47
created

testLoadExistentMetadataDir()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 17
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 10
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('jms_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->assertFalse($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->assertTrue($container->getDefinition('jms_serializer.doctrine_proxy_subscriber')->getArgument(0));
233
        $this->assertFalse($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' => true,
253
                    'initialize_excluded' => true,
254
                ],
255
            ],
256
            'object_constructors' => [
257
                'doctrine' => [
258
                    'fallback_strategy' => "exception",
259
                ],
260
            ],
261
            'handlers' => [
262
                'array_collection' => [
263
                    'initialize_excluded' => true,
264
                ],
265
            ],
266
        )));
267
268
        $this->assertTrue($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->assertFalse($container->getDefinition('jms_serializer.doctrine_proxy_subscriber')->getArgument(0));
272
        $this->assertTrue($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
    public function testLoadExistentMetadataDir()
278
    {
279
        $container = $this->getContainerForConfig(array(array(
280
            'metadata' => [
281
                'directories' => [
282
                    'foo' => [
283
                        'namespace_prefix' => 'foo_ns',
284
                        'path' => __DIR__,
285
                    ]
286
                ]
287
            ]
288
        )));
289
290
        $fileLocatorDef = $container->getDefinition('jms_serializer.metadata.file_locator');
291
        $directories = $fileLocatorDef->getArgument(0);
292
        $this->assertEquals(['foo_ns' => __DIR__], $directories);
293
    }
294
295
    /**
296
     * @expectedException \JMS\Serializer\Exception\RuntimeException
297
     * @expectedExceptionMessage  The metadata directory "foo_dir" does not exist for the namespace "foo_ns"
298
     */
299
    public function testLoadNotExistentMetadataDir()
300
    {
301
        $this->getContainerForConfig(array(array(
302
            'metadata' => [
303
                'directories' => [
304
                    'foo' => [
305
                        'namespace_prefix' => 'foo_ns',
306
                        'path' => 'foo_dir',
307
                    ]
308
                ]
309
            ]
310
        )));
311
    }
312
313
    /**
314
     * @dataProvider getJsonVisitorConfigs
315
     */
316
    public function testJsonVisitorOptions($expectedOptions, $config)
317
    {
318
        $container = $this->getContainerForConfig(array($config));
319
        $this->assertSame($expectedOptions, $container->get('jms_serializer.json_serialization_visitor')->getOptions());
320
    }
321
322
    public function getJsonVisitorConfigs()
323
    {
324
        $configs = array();
325
326
        if (version_compare(PHP_VERSION, '5.4', '>=')) {
327
            $configs[] = array(JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT, array(
328
                'visitors' => array(
329
                    'json' => array(
330
                        'options' => array('JSON_UNESCAPED_UNICODE', 'JSON_PRETTY_PRINT')
331
                    )
332
                )
333
            ));
334
335
            $configs[] = array(JSON_UNESCAPED_UNICODE, array(
336
                'visitors' => array(
337
                    'json' => array(
338
                        'options' => 'JSON_UNESCAPED_UNICODE'
339
                    )
340
                )
341
            ));
342
        }
343
344
        $configs[] = array(128, array(
345
            'visitors' => array(
346
                'json' => array(
347
                    'options' => 128
348
                )
349
            )
350
        ));
351
352
        $configs[] = array(0, array());
353
354
        return $configs;
355
    }
356
357
    public function testExpressionLanguage()
358
    {
359
        if (!interface_exists('Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface')) {
360
            $this->markTestSkipped("The Symfony Expression Language is not available");
361
        }
362
        $container = $this->getContainerForConfig(array(array()));
363
        $serializer = $container->get('jms_serializer');
364
        // test that all components have been wired correctly
365
        $object = new ObjectUsingExpressionLanguage('foo', true);
366
        $this->assertEquals('{"name":"foo"}', $serializer->serialize($object, 'json'));
367
        $object = new ObjectUsingExpressionLanguage('foo', false);
368
        $this->assertEquals('{}', $serializer->serialize($object, 'json'));
369
    }
370
371
    public function testExpressionLanguageVirtualProperties()
372
    {
373
        if (!interface_exists('Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface')) {
374
            $this->markTestSkipped("The Symfony Expression Language is not available");
375
        }
376
        $container = $this->getContainerForConfig(array(array()));
377
        $serializer = $container->get('jms_serializer');
378
        // test that all components have been wired correctly
379
        $object = new ObjectUsingExpressionProperties('foo');
380
        $this->assertEquals('{"v_prop_name":"foo"}', $serializer->serialize($object, 'json'));
381
    }
382
383
    /**
384
     * @expectedException \JMS\Serializer\Exception\ExpressionLanguageRequiredException
385
     */
386
    public function testExpressionLanguageDisabledVirtualProperties()
387
    {
388
        if (!interface_exists('Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface')) {
389
            $this->markTestSkipped("The Symfony Expression Language is not available");
390
        }
391
        $container = $this->getContainerForConfig(array(array('expression_evaluator' => array('id' => null))));
392
        $serializer = $container->get('jms_serializer');
393
        // test that all components have been wired correctly
394
        $object = new ObjectUsingExpressionProperties('foo');
395
        $serializer->serialize($object, 'json');
396
    }
397
398
    /**
399
     * @expectedException \JMS\Serializer\Exception\ExpressionLanguageRequiredException
400
     * @expectedExceptionMessage  To use conditional exclude/expose in JMS\SerializerBundle\Tests\DependencyInjection\Fixture\ObjectUsingExpressionLanguage you must configure the expression language.
401
     */
402
    public function testExpressionLanguageNotLoaded()
403
    {
404
        $container = $this->getContainerForConfig(array(array('expression_evaluator' => array('id' => null))));
405
        $serializer = $container->get('jms_serializer');
406
        // test that all components have been wired correctly
407
        $object = new ObjectUsingExpressionLanguage('foo', true);
408
        $serializer->serialize($object, 'json');
409
    }
410
411
    /**
412
     * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException
413
     * @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
414
     */
415
    public function testExpressionInvalidEvaluator()
416
    {
417
        if (interface_exists('Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface')) {
418
            $this->markTestSkipped('To pass this test the "symfony/expression-language" component should be available');
419
        }
420
        $this->getContainerForConfig(array(array('expression_evaluator' => array('id' => 'foo'))));
421
    }
422
423
    /**
424
     * @dataProvider getXmlVisitorWhitelists
425
     */
426
    public function testXmlVisitorOptions($expectedOptions, $config)
427
    {
428
        $container = $this->getContainerForConfig(array($config));
429
        $this->assertSame($expectedOptions, $container->get('jms_serializer.xml_deserialization_visitor')->getDoctypeWhitelist());
430
    }
431
432
    public function getXmlVisitorWhitelists()
433
    {
434
        $configs = array();
435
436
        $configs[] = array(array('good document', 'other good document'), array(
437
            'visitors' => array(
438
                'xml' => array(
439
                    'doctype_whitelist' => array('good document', 'other good document'),
440
                )
441
            )
442
        ));
443
444
        $configs[] = array(array(), array());
445
446
        return $configs;
447
    }
448
449
    public function testXmlVisitorFormatOutput()
450
    {
451
        $config = array(
452
            'visitors' => array(
453
                'xml' => array(
454
                    'format_output' => false,
455
                )
456
            )
457
        );
458
        $container = $this->getContainerForConfig(array($config));
459
460
        $this->assertFalse($container->get('jms_serializer.xml_serialization_visitor')->isFormatOutput());
461
    }
462
463
    public function testXmlVisitorDefaultValueToFormatOutput()
464
    {
465
        $container = $this->getContainerForConfig(array());
466
        $this->assertTrue($container->get('jms_serializer.xml_serialization_visitor')->isFormatOutput());
467
    }
468
469
    private function getContainerForConfig(array $configs, KernelInterface $kernel = null)
470
    {
471
        if (null === $kernel) {
472
            $kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\KernelInterface')->getMock();
473
            $kernel
474
                ->expects($this->any())
475
                ->method('getBundles')
476
                ->will($this->returnValue(array()));
477
        }
478
479
        $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...
480
        $extension = $bundle->getContainerExtension();
481
482
        $container = new ContainerBuilder();
483
        $container->setParameter('kernel.debug', true);
484
        $container->setParameter('kernel.cache_dir', sys_get_temp_dir() . '/serializer');
485
        $container->setParameter('kernel.bundles', array());
486
        $container->set('annotation_reader', new AnnotationReader());
487
        $container->set('translator', $this->getMockBuilder('Symfony\\Component\\Translation\\TranslatorInterface')->getMock());
488
        $container->set('debug.stopwatch', $this->getMockBuilder('Symfony\\Component\\Stopwatch\\Stopwatch')->getMock());
489
        $container->registerExtension($extension);
0 ignored issues
show
Bug introduced by
It seems like $extension defined by $bundle->getContainerExtension() on line 480 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...
490
        $extension->load($configs, $container);
491
492
        $bundle->build($container);
493
494
        $container->getCompilerPassConfig()->setOptimizationPasses(array(
495
            new ResolveParameterPlaceHoldersPass(),
496
            new ResolveDefinitionTemplatesPass(),
497
        ));
498
        $container->getCompilerPassConfig()->setRemovingPasses(array());
499
        $container->compile();
500
501
        return $container;
502
    }
503
}
504