Issues (42)

Security Analysis    no request data  

This project does not seem to handle request data directly as such no vulnerable execution paths were found.

  Cross-Site Scripting
Cross-Site Scripting enables an attacker to inject code into the response of a web-request that is viewed by other users. It can for example be used to bypass access controls, or even to take over other users' accounts.
  File Exposure
File Exposure allows an attacker to gain access to local files that he should not be able to access. These files can for example include database credentials, or other configuration files.
  File Manipulation
File Manipulation enables an attacker to write custom data to files. This potentially leads to injection of arbitrary code on the server.
  Object Injection
Object Injection enables an attacker to inject an object into PHP code, and can lead to arbitrary code execution, file exposure, or file manipulation attacks.
  Code Injection
Code Injection enables an attacker to execute arbitrary code on the server.
  Response Splitting
Response Splitting can be used to send arbitrary responses.
  File Inclusion
File Inclusion enables an attacker to inject custom files into PHP's file loading mechanism, either explicitly passed to include, or for example via PHP's auto-loading mechanism.
  Command Injection
Command Injection enables an attacker to inject a shell command that is execute with the privileges of the web-server. This can be used to expose sensitive data, or gain access of your server.
  SQL Injection
SQL Injection enables an attacker to execute arbitrary SQL code on your database server gaining access to user data, or manipulating user data.
  XPath Injection
XPath Injection enables an attacker to modify the parts of XML document that are read. If that XML document is for example used for authentication, this can lead to further vulnerabilities similar to SQL Injection.
  LDAP Injection
LDAP Injection enables an attacker to inject LDAP statements potentially granting permission to run unauthorized queries, or modify content inside the LDAP tree.
  Header Injection
  Other Vulnerability
This category comprises other attack vectors such as manipulating the PHP runtime, loading custom extensions, freezing the runtime, or similar.
  Regex Injection
Regex Injection enables an attacker to execute arbitrary code in your PHP process.
  XML Injection
XML Injection enables an attacker to read files on your local filesystem including configuration files, or can be abused to freeze your web-server process.
  Variable Injection
Variable Injection enables an attacker to overwrite program variables with custom data, and can lead to further vulnerabilities.
Unfortunately, the security analysis is currently not available for your project. If you are a non-commercial open-source project, please contact support to gain access.

DependencyInjection/JMSSerializerExtensionTest.php (6 issues)

Upgrade to new PHP Analysis Engine

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

1
<?php
2
3
/*
4
 * Copyright 2011 Johannes M. Schmitt <[email protected]>
5
 *
6
 * Licensed under the Apache License, Version 2.0 (the "License");
7
 * you may not use this file except in compliance with the License.
8
 * You may obtain a copy of the License at
9
 *
10
 * http://www.apache.org/licenses/LICENSE-2.0
11
 *
12
 * Unless required by applicable law or agreed to in writing, software
13
 * distributed under the License is distributed on an "AS IS" BASIS,
14
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
 * See the License for the specific language governing permissions and
16
 * limitations under the License.
17
 */
18
19
namespace JMS\SerializerBundle\Tests\DependencyInjection;
20
21
use Doctrine\Common\Annotations\AnnotationReader;
22
use JMS\Serializer\SerializationContext;
23
use JMS\Serializer\EventDispatcher\EventSubscriberInterface;
24
use JMS\SerializerBundle\JMSSerializerBundle;
25
use JMS\SerializerBundle\Tests\DependencyInjection\Fixture\ObjectUsingExpressionLanguage;
26
use JMS\SerializerBundle\Tests\DependencyInjection\Fixture\ObjectUsingExpressionProperties;
27
use JMS\SerializerBundle\Tests\DependencyInjection\Fixture\SimpleObject;
28
use JMS\SerializerBundle\Tests\DependencyInjection\Fixture\VersionedObject;
29
use PHPUnit\Framework\TestCase;
30
use Symfony\Component\DependencyInjection\ContainerBuilder;
31
use Symfony\Component\DependencyInjection\Definition;
32
33
class JMSSerializerExtensionTest extends TestCase
34
{
35
    protected function setUp()
36
    {
37
        $this->clearTempDir();
38
    }
39
40
    protected function tearDown()
41
    {
42
        $this->clearTempDir();
43
    }
44
45
    private function clearTempDir()
46
    {
47
        // clear temporary directory
48
        $dir = sys_get_temp_dir() . '/serializer';
49
        if (is_dir($dir)) {
50
            foreach (new \RecursiveDirectoryIterator($dir) as $file) {
51
                $filename = $file->getFileName();
52
                if ('.' === $filename || '..' === $filename) {
53
                    continue;
54
                }
55
56
                @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...
57
            }
58
59
            @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...
60
        }
61
    }
62
63
    public function testHasContextFactories()
64
    {
65
        $container = $this->getContainerForConfig(array(array()));
66
67
        $factory = $container->get('jms_serializer.serialization_context_factory');
68
        $this->assertInstanceOf('JMS\Serializer\ContextFactory\SerializationContextFactoryInterface', $factory);
69
70
        $factory = $container->get('jms_serializer.deserialization_context_factory');
71
        $this->assertInstanceOf('JMS\Serializer\ContextFactory\DeserializationContextFactoryInterface', $factory);
72
    }
73
74
    public function testSerializerContextFactoriesAreSet()
75
    {
76
        $container = $this->getContainerForConfig(array(array()));
77
78
        $def = $container->getDefinition('jms_serializer');
79
        $calls = $def->getMethodCalls();
80
81
        $this->assertCount(2, $calls);
82
83
        $serializationCall = $calls[0];
84
        $this->assertEquals('setSerializationContextFactory', $serializationCall[0]);
85
        $this->assertEquals('jms_serializer.serialization_context_factory', (string)$serializationCall[1][0]);
86
87
        $serializationCall = $calls[1];
88
        $this->assertEquals('setDeserializationContextFactory', $serializationCall[0]);
89
        $this->assertEquals('jms_serializer.deserialization_context_factory', (string)$serializationCall[1][0]);
90
    }
91
92
    public function testSerializerContextFactoriesWithId()
93
    {
94
        $config = array(
95
            'default_context' => array(
96
                'serialization' => array(
97
                    'id' => 'foo'
98
                ),
99
                'deserialization' => array(
100
                    'id' => 'bar'
101
                )
102
            )
103
        );
104
105
        $foo = new Definition('stdClass');
106
        $foo->setPublic(true);
107
        $bar = new Definition('stdClass');
108
        $bar->setPublic(true);
109
110
        $container = $this->getContainerForConfig(array($config), function (ContainerBuilder $containerBuilder) use ($foo, $bar) {
111
            $containerBuilder->setDefinition('foo', $foo);
112
            $containerBuilder->setDefinition('bar', $bar);
113
        });
114
115
        $def = $container->getDefinition('jms_serializer');
116
        $calls = $def->getMethodCalls();
117
118
        $this->assertCount(2, $calls);
119
120
        $serializationCall = $calls[0];
121
        $this->assertEquals('setSerializationContextFactory', $serializationCall[0]);
122
        $this->assertEquals('foo', (string)$serializationCall[1][0]);
123
124
        $serializationCall = $calls[1];
125
        $this->assertEquals('setDeserializationContextFactory', $serializationCall[0]);
126
        $this->assertEquals('bar', (string)$serializationCall[1][0]);
127
128
        $this->assertEquals('bar', (string)$container->getAlias('jms_serializer.deserialization_context_factory'));
129
        $this->assertEquals('foo', (string)$container->getAlias('jms_serializer.serialization_context_factory'));
130
    }
131
132
    public function testLoadWithoutTranslator()
133
    {
134
        $container = $this->getContainerForConfig(array(array()), function (ContainerBuilder $containerBuilder) {
135
            $containerBuilder->set('translator', null);
0 ignored issues
show
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...
136
            $containerBuilder->getDefinition('jms_serializer.form_error_handler')->setPublic(true);
137
        });
138
139
        $def = $container->getDefinition('jms_serializer.form_error_handler');
140
        $this->assertSame(null, $def->getArgument(0));
141
    }
142
143
    public function testConfiguringContextFactories()
144
    {
145
        $container = $this->getContainerForConfig(array(array()));
146
147
        $def = $container->getDefinition('jms_serializer.serialization_context_factory');
148
        $this->assertCount(0, $def->getMethodCalls());
149
150
        $def = $container->getDefinition('jms_serializer.deserialization_context_factory');
151
        $this->assertCount(0, $def->getMethodCalls());
152
    }
153
154
    public function testConfiguringContextFactoriesWithParams()
155
    {
156
        $config = array(
157
            'default_context' => array(
158
                'serialization' => array(
159
                    'version' => 1600,
160
                    'serialize_null' => true,
161
                    'attributes' => array('x' => 1720),
162
                    'groups' => array('Default', 'Registration'),
163
                    'enable_max_depth_checks' => true,
164
                ),
165
                'deserialization' => array(
166
                    'version' => 1640,
167
                    'serialize_null' => false,
168
                    'attributes' => array('x' => 1740),
169
                    'groups' => array('Default', 'Profile'),
170
                    'enable_max_depth_checks' => true,
171
                )
172
            )
173
        );
174
175
        $container = $this->getContainerForConfig(array($config));
176
        $services = [
177
            'serialization' => 'jms_serializer.serialization_context_factory',
178
            'deserialization' => 'jms_serializer.deserialization_context_factory',
179
        ];
180
        foreach ($services as $configKey => $serviceId) {
181
            $def = $container->getDefinition($serviceId);
182
            $values = $config['default_context'][$configKey];
183
184
            $this->assertSame($values['version'], $this->getDefinitionMethodCall($def, 'setVersion')[0]);
185
            $this->assertSame($values['serialize_null'], $this->getDefinitionMethodCall($def, 'setSerializeNulls')[0]);
186
            $this->assertSame($values['attributes'], $this->getDefinitionMethodCall($def, 'setAttributes')[0]);
187
            $this->assertSame($values['groups'], $this->getDefinitionMethodCall($def, 'setGroups')[0]);
188
            $this->assertSame($values['groups'], $this->getDefinitionMethodCall($def, 'setGroups')[0]);
189
            $this->assertSame(array(), $this->getDefinitionMethodCall($def, 'enableMaxDepthChecks'));
190
        }
191
    }
192
193
    public function testConfiguringContextFactoriesWithNullDefaults()
194
    {
195
        $config = array(
196
            'default_context' => array(
197
                'serialization' => array(
198
                    'version' => null,
199
                    'serialize_null' => null,
200
                    'attributes' => [],
201
                    'groups' => null,
202
                ),
203
                'deserialization' => array(
204
                    'version' => null,
205
                    'serialize_null' => null,
206
                    'attributes' => null,
207
                    'groups' => null,
208
                )
209
            )
210
        );
211
212
        $container = $this->getContainerForConfig(array($config));
213
        $services = [
214
            'serialization' => 'jms_serializer.serialization_context_factory',
215
            'deserialization' => 'jms_serializer.deserialization_context_factory',
216
        ];
217
        foreach ($services as $configKey => $serviceId) {
218
            $def = $container->getDefinition($serviceId);
219
            $this->assertCount(0, $def->getMethodCalls());
220
        }
221
    }
222
223
    private function getDefinitionMethodCall(Definition $def, $method)
224
    {
225
        foreach ($def->getMethodCalls() as $call) {
226
            if ($call[0] === $method) {
227
                return $call[1];
228
            }
229
        }
230
        return false;
231
    }
232
233
    public function testLoad()
234
    {
235
        $container = $this->getContainerForConfig(array(array()), function (ContainerBuilder $container) {
236
            $container->getDefinition('jms_serializer.doctrine_object_constructor')->setPublic(true);
237
            $container->getDefinition('jms_serializer.array_collection_handler')->setPublic(true);
238
            $container->getDefinition('jms_serializer.doctrine_proxy_subscriber')->setPublic(true);
239
            $container->getAlias('JMS\Serializer\SerializerInterface')->setPublic(true);
240
            $container->getAlias('JMS\Serializer\ArrayTransformerInterface')->setPublic(true);
241
        });
242
243
        $simpleObject = new SimpleObject('foo', 'bar');
244
        $versionedObject = new VersionedObject('foo', 'bar');
245
        $serializer = $container->get('jms_serializer');
246
247
        $this->assertTrue($container->has('JMS\Serializer\SerializerInterface'), 'Alias should be defined to allow autowiring');
248
        $this->assertTrue($container->has('JMS\Serializer\ArrayTransformerInterface'), 'Alias should be defined to allow autowiring');
249
250
        $this->assertFalse($container->getDefinition('jms_serializer.array_collection_handler')->getArgument(0));
251
252
        // the logic is inverted because arg 0 on doctrine_proxy_subscriber is $skipVirtualTypeInit = false
253
        $this->assertTrue($container->getDefinition('jms_serializer.doctrine_proxy_subscriber')->getArgument(0));
254
        $this->assertFalse($container->getDefinition('jms_serializer.doctrine_proxy_subscriber')->getArgument(1));
255
256
        $this->assertEquals("null", $container->getDefinition('jms_serializer.doctrine_object_constructor')->getArgument(2));
257
258
        // test that all components have been wired correctly
259
        $this->assertEquals(json_encode(array('name' => 'bar')), $serializer->serialize($versionedObject, 'json'));
260
        $this->assertEquals($simpleObject, $serializer->deserialize($serializer->serialize($simpleObject, 'json'), get_class($simpleObject), 'json'));
261
        $this->assertEquals($simpleObject, $serializer->deserialize($serializer->serialize($simpleObject, 'xml'), get_class($simpleObject), 'xml'));
262
263
        $this->assertEquals(json_encode(array('name' => 'foo')), $serializer->serialize($versionedObject, 'json', SerializationContext::create()->setVersion('0.0.1')));
264
265
        $this->assertEquals(json_encode(array('name' => 'bar')), $serializer->serialize($versionedObject, 'json', SerializationContext::create()->setVersion('1.1.1')));
266
    }
267
268
    public function testLoadWithOptions()
269
    {
270
        $container = $this->getContainerForConfig(array(array(
271
            'subscribers' => [
272
                'doctrine_proxy' => [
273
                    'initialize_virtual_types' => true,
274
                    'initialize_excluded' => true,
275
                ],
276
            ],
277
            'object_constructors' => [
278
                'doctrine' => [
279
                    'fallback_strategy' => "exception",
280
                ],
281
            ],
282
            'handlers' => [
283
                'array_collection' => [
284
                    'initialize_excluded' => true,
285
                ],
286
            ],
287
        )), function ($container) {
288
            $container->getDefinition('jms_serializer.doctrine_object_constructor')->setPublic(true);
289
            $container->getDefinition('jms_serializer.array_collection_handler')->setPublic(true);
290
            $container->getDefinition('jms_serializer.doctrine_proxy_subscriber')->setPublic(true);
291
        });
292
293
        $this->assertTrue($container->getDefinition('jms_serializer.array_collection_handler')->getArgument(0));
294
295
        // the logic is inverted because arg 0 on doctrine_proxy_subscriber is $skipVirtualTypeInit = false
296
        $this->assertFalse($container->getDefinition('jms_serializer.doctrine_proxy_subscriber')->getArgument(0));
297
        $this->assertTrue($container->getDefinition('jms_serializer.doctrine_proxy_subscriber')->getArgument(1));
298
299
        $this->assertEquals("exception", $container->getDefinition('jms_serializer.doctrine_object_constructor')->getArgument(2));
300
    }
301
302
    public function testLoadExistentMetadataDir()
303
    {
304
        $container = $this->getContainerForConfig(array(array(
305
            'metadata' => [
306
                'directories' => [
307
                    'foo' => [
308
                        'namespace_prefix' => 'foo_ns',
309
                        'path' => __DIR__,
310
                    ]
311
                ]
312
            ]
313
        )), function ($container) {
314
            $container->getDefinition('jms_serializer.metadata.file_locator')->setPublic(true);
315
        });
316
317
        $fileLocatorDef = $container->getDefinition('jms_serializer.metadata.file_locator');
318
        $directories = $fileLocatorDef->getArgument(0);
319
        $this->assertEquals(['foo_ns' => __DIR__], $directories);
320
    }
321
322
    public function testWarmUpWithDirs()
323
    {
324
        $container = $this->getContainerForConfig([[
325
            'metadata' => [
326
                'warmup' => [
327
                    'paths' => [
328
                        'included' => ['a'],
329
                        'excluded' => ['b']
330
                    ]
331
                ]
332
            ]
333
        ]], function ($container){
334
            $container->getDefinition('jms_serializer.cache.cache_warmer')->setPublic(true);
335
        });
336
337
        $this->assertTrue($container->hasDefinition('jms_serializer.cache.cache_warmer'));
338
339
        $def = $container->getDefinition('jms_serializer.cache.cache_warmer');
340
341
        $this->assertEquals(['a'], $def->getArgument(0));
342
        $this->assertEquals(['b'], $def->getArgument(2));
343
    }
344
345
    public function testWarmUpWithDirsWithNoPaths()
346
    {
347
        $this->getContainerForConfig([[]], function ($container) {
348
            $this->assertFalse($container->hasDefinition('jms_serializer.cache.cache_warmer'));
349
        });
350
    }
351
352
    /**
353
     * @expectedException \JMS\Serializer\Exception\RuntimeException
354
     * @expectedExceptionMessage  The metadata directory "foo_dir" does not exist for the namespace "foo_ns"
355
     */
356
    public function testLoadNotExistentMetadataDir()
357
    {
358
        $this->getContainerForConfig(array(array(
359
            'metadata' => [
360
                'directories' => [
361
                    'foo' => [
362
                        'namespace_prefix' => 'foo_ns',
363
                        'path' => 'foo_dir',
364
                    ]
365
                ]
366
            ]
367
        )));
368
    }
369
370
    /**
371
     * @dataProvider getJsonVisitorConfigs
372
     */
373 View Code Duplication
    public function testJsonVisitorOptions($expectedOptions, $config)
0 ignored issues
show
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
374
    {
375
        $container = $this->getContainerForConfig(array($config), function ($container) {
376
            $container->getDefinition('jms_serializer.json_serialization_visitor')->setPublic(true);
377
        });
378
        $this->assertSame($expectedOptions, $container->get('jms_serializer.json_serialization_visitor')->getOptions());
379
    }
380
381
    public function getJsonVisitorConfigs()
382
    {
383
        $configs = array();
384
385
        if (version_compare(PHP_VERSION, '5.4', '>=')) {
386
            $configs[] = array(JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT, array(
387
                'visitors' => array(
388
                    'json' => array(
389
                        'options' => array('JSON_UNESCAPED_UNICODE', 'JSON_PRETTY_PRINT')
390
                    )
391
                )
392
            ));
393
394
            $configs[] = array(JSON_UNESCAPED_UNICODE, array(
395
                'visitors' => array(
396
                    'json' => array(
397
                        'options' => 'JSON_UNESCAPED_UNICODE'
398
                    )
399
                )
400
            ));
401
        }
402
403
        $configs[] = array(128, array(
404
            'visitors' => array(
405
                'json' => array(
406
                    'options' => 128
407
                )
408
            )
409
        ));
410
411
        $configs[] = array(0, array());
412
413
        return $configs;
414
    }
415
416
    public function testExpressionLanguage()
417
    {
418
        if (!interface_exists('Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface')) {
419
            $this->markTestSkipped("The Symfony Expression Language is not available");
420
        }
421
        $container = $this->getContainerForConfig(array(array()));
422
        $serializer = $container->get('jms_serializer');
423
        // test that all components have been wired correctly
424
        $object = new ObjectUsingExpressionLanguage('foo', true);
425
        $this->assertEquals('{"name":"foo"}', $serializer->serialize($object, 'json'));
426
        $object = new ObjectUsingExpressionLanguage('foo', false);
427
        $this->assertEquals('{}', $serializer->serialize($object, 'json'));
428
    }
429
430
    public function testExpressionLanguageVirtualProperties()
431
    {
432
        if (!interface_exists('Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface')) {
433
            $this->markTestSkipped("The Symfony Expression Language is not available");
434
        }
435
        $container = $this->getContainerForConfig(array(array()));
436
        $serializer = $container->get('jms_serializer');
437
        // test that all components have been wired correctly
438
        $object = new ObjectUsingExpressionProperties('foo');
439
        $this->assertEquals('{"v_prop_name":"foo"}', $serializer->serialize($object, 'json'));
440
    }
441
442
    /**
443
     * @expectedException \JMS\Serializer\Exception\ExpressionLanguageRequiredException
444
     */
445
    public function testExpressionLanguageDisabledVirtualProperties()
446
    {
447
        if (!interface_exists('Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface')) {
448
            $this->markTestSkipped("The Symfony Expression Language is not available");
449
        }
450
        $container = $this->getContainerForConfig(array(array('expression_evaluator' => array('id' => null))));
451
        $serializer = $container->get('jms_serializer');
452
        // test that all components have been wired correctly
453
        $object = new ObjectUsingExpressionProperties('foo');
454
        $serializer->serialize($object, 'json');
455
    }
456
457
    /**
458
     * @expectedException \JMS\Serializer\Exception\ExpressionLanguageRequiredException
459
     * @expectedExceptionMessage  To use conditional exclude/expose in JMS\SerializerBundle\Tests\DependencyInjection\Fixture\ObjectUsingExpressionLanguage you must configure the expression language.
460
     */
461
    public function testExpressionLanguageNotLoaded()
462
    {
463
        $container = $this->getContainerForConfig(array(array('expression_evaluator' => array('id' => null))));
464
        $serializer = $container->get('jms_serializer');
465
        // test that all components have been wired correctly
466
        $object = new ObjectUsingExpressionLanguage('foo', true);
467
        $serializer->serialize($object, 'json');
468
    }
469
470
    /**
471
     * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException
472
     * @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
473
     */
474
    public function testExpressionInvalidEvaluator()
475
    {
476
        if (interface_exists('Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface')) {
477
            $this->markTestSkipped('To pass this test the "symfony/expression-language" component should be available');
478
        }
479
        $this->getContainerForConfig(array(array('expression_evaluator' => array('id' => 'foo'))));
480
    }
481
482
    /**
483
     * @dataProvider getXmlVisitorWhitelists
484
     */
485 View Code Duplication
    public function testXmlVisitorOptions($expectedOptions, $config)
0 ignored issues
show
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
486
    {
487
        $container = $this->getContainerForConfig(array($config), function ($container) {
488
            $container->getDefinition('jms_serializer.xml_deserialization_visitor')->setPublic(true);
489
        });
490
        $this->assertSame($expectedOptions, $container->get('jms_serializer.xml_deserialization_visitor')->getDoctypeWhitelist());
491
    }
492
493
    public function getXmlVisitorWhitelists()
494
    {
495
        $configs = array();
496
497
        $configs[] = array(array('good document', 'other good document'), array(
498
            'visitors' => array(
499
                'xml' => array(
500
                    'doctype_whitelist' => array('good document', 'other good document'),
501
                )
502
            )
503
        ));
504
505
        $configs[] = array(array(), array());
506
507
        return $configs;
508
    }
509
510
    public function testXmlVisitorFormatOutput()
511
    {
512
        $config = array(
513
            'visitors' => array(
514
                'xml' => array(
515
                    'format_output' => false,
516
                )
517
            )
518
        );
519
        $container = $this->getContainerForConfig(array($config), function ($container) {
520
            $container->getDefinition('jms_serializer.xml_serialization_visitor')->setPublic(true);
521
        });
522
523
        $this->assertFalse($container->get('jms_serializer.xml_serialization_visitor')->isFormatOutput());
524
    }
525
526
    public function testXmlVisitorDefaultValueToFormatOutput()
527
    {
528
        $container = $this->getContainerForConfig(array(), function ($container) {
529
            $container->getDefinition('jms_serializer.xml_serialization_visitor')->setPublic(true);
530
        });
531
        $this->assertTrue($container->get('jms_serializer.xml_serialization_visitor')->isFormatOutput());
532
    }
533
534
    public function testAutoconfigureSubscribers()
535
    {
536
        $container = $this->getContainerForConfig(array());
537
538
        if (!method_exists($container, 'registerForAutoconfiguration')) {
539
            $this->markTestSkipped(
540
                'registerForAutoconfiguration method is not available in the container'
541
            );
542
        }
543
544
        $autoconfigureInstance = $container->getAutoconfiguredInstanceof();
545
546
        $this->assertTrue(array_key_exists(EventSubscriberInterface::class, $autoconfigureInstance));
547
        $this->assertTrue($autoconfigureInstance[EventSubscriberInterface::class]->hasTag('jms_serializer.event_subscriber'));
548
    }
549
550
    private function getContainerForConfig(array $configs, callable $configurator = null)
551
    {
552
        $bundle = new JMSSerializerBundle();
553
        $extension = $bundle->getContainerExtension();
554
555
        $container = new ContainerBuilder();
556
        $container->setParameter('kernel.debug', true);
557
        $container->setParameter('kernel.cache_dir', sys_get_temp_dir() . '/serializer');
558
        $container->setParameter('kernel.bundles', array());
559
        $container->set('annotation_reader', new AnnotationReader());
560
        $container->setDefinition('doctrine', new Definition(Registry::class));
561
        $container->set('translator', $this->getMockBuilder('Symfony\\Component\\Translation\\TranslatorInterface')->getMock());
562
        $container->set('debug.stopwatch', $this->getMockBuilder('Symfony\\Component\\Stopwatch\\Stopwatch')->getMock());
563
        $container->registerExtension($extension);
0 ignored issues
show
It seems like $extension defined by $bundle->getContainerExtension() on line 553 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...
564
        $extension->load($configs, $container);
565
566
        $bundle->build($container);
567
568
        if ($configurator) {
569
            call_user_func($configurator, $container);
570
        }
571
572
        $container->compile();
573
574
        return $container;
575
    }
576
}
577