Completed
Pull Request — master (#545)
by Asmir
05:48
created

testHasContextFactories()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 6
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 JMS\Serializer\SerializationContext;
22
use JMS\SerializerBundle\Tests\DependencyInjection\Fixture\ObjectUsingExpressionLanguage;
23
use JMS\SerializerBundle\Tests\DependencyInjection\Fixture\ObjectUsingExpressionProperties;
24
use Symfony\Component\DependencyInjection\Compiler\ResolveParameterPlaceHoldersPass;
25
use Doctrine\Common\Annotations\AnnotationReader;
26
use JMS\SerializerBundle\JMSSerializerBundle;
27
use JMS\SerializerBundle\Tests\DependencyInjection\Fixture\SimpleObject;
28
use JMS\SerializerBundle\Tests\DependencyInjection\Fixture\VersionedObject;
29
use Symfony\Component\DependencyInjection\Compiler\ResolveDefinitionTemplatesPass;
30
use Symfony\Component\DependencyInjection\ContainerBuilder;
31
use Symfony\Component\HttpKernel\KernelInterface;
32
33
class JMSSerializerExtensionTest extends \PHPUnit_Framework_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.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 testLoad()
93
    {
94
        $container = $this->getContainerForConfig(array(array()));
95
96
        $simpleObject = new SimpleObject('foo', 'bar');
97
        $versionedObject  = new VersionedObject('foo', 'bar');
98
        $serializer = $container->get('serializer');
99
100
        // test that all components have been wired correctly
101
        $this->assertEquals(json_encode(array('name' => 'bar')), $serializer->serialize($versionedObject, 'json'));
102
        $this->assertEquals($simpleObject, $serializer->deserialize($serializer->serialize($simpleObject, 'json'), get_class($simpleObject), 'json'));
103
        $this->assertEquals($simpleObject, $serializer->deserialize($serializer->serialize($simpleObject, 'xml'), get_class($simpleObject), 'xml'));
104
105
        $this->assertEquals(json_encode(array('name' => 'foo')), $serializer->serialize($versionedObject, 'json', SerializationContext::create()->setVersion('0.0.1')));
106
107
        $this->assertEquals(json_encode(array('name' => 'bar')), $serializer->serialize($versionedObject, 'json', SerializationContext::create()->setVersion('1.1.1')));
108
    }
109
110
    /**
111
     * @dataProvider getJsonVisitorConfigs
112
     */
113
    public function testJsonVisitorOptions($expectedOptions, $config)
114
    {
115
        $container = $this->getContainerForConfig(array($config));
116
        $this->assertSame($expectedOptions, $container->get('jms_serializer.json_serialization_visitor')->getOptions());
117
    }
118
119
    public function getJsonVisitorConfigs()
120
    {
121
        $configs = array();
122
123
        if (version_compare(PHP_VERSION, '5.4', '>=')) {
124
            $configs[] = array(JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT, array(
125
                'visitors' => array(
126
                    'json' => array(
127
                        'options' => array('JSON_UNESCAPED_UNICODE', 'JSON_PRETTY_PRINT')
128
                    )
129
                )
130
            ));
131
132
            $configs[] = array(JSON_UNESCAPED_UNICODE, array(
133
                'visitors' => array(
134
                    'json' => array(
135
                        'options' => 'JSON_UNESCAPED_UNICODE'
136
                    )
137
                )
138
            ));
139
        }
140
141
        $configs[] = array(128, array(
142
            'visitors' => array(
143
                'json' => array(
144
                    'options' => 128
145
                )
146
            )
147
        ));
148
149
        $configs[] = array(0, array());
150
151
        return $configs;
152
    }
153
154
    public function testExpressionLanguage()
155
    {
156
        if (!interface_exists('Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface')) {
157
            $this->markTestSkipped("The Symfony Expression Language is not available");
158
        }
159
        $container = $this->getContainerForConfig(array(array()));
160
        $serializer = $container->get('serializer');
161
        // test that all components have been wired correctly
162
        $object = new ObjectUsingExpressionLanguage('foo', true);
163
        $this->assertEquals('{"name":"foo"}', $serializer->serialize($object, 'json'));
164
        $object = new ObjectUsingExpressionLanguage('foo', false);
165
        $this->assertEquals('{}', $serializer->serialize($object, 'json'));
166
    }
167
168
    public function testExpressionLanguageVirtualProperties()
169
    {
170
        if (!interface_exists('Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface')) {
171
            $this->markTestSkipped("The Symfony Expression Language is not available");
172
        }
173
        $container = $this->getContainerForConfig(array(array()));
174
        $serializer = $container->get('serializer');
175
        // test that all components have been wired correctly
176
        $object = new ObjectUsingExpressionProperties('foo');
177
        $this->assertEquals('{"v_prop_name":"foo"}', $serializer->serialize($object, 'json'));
178
    }
179
180
    /**
181
     * @expectedException \JMS\Serializer\Exception\ExpressionLanguageRequiredException
182
     * @expectedExceptionMessage The property v_prop_name on JMS\SerializerBundle\Tests\DependencyInjection\Fixture\ObjectUsingExpressionProperties requires the expression evaluator to be enabled
183
     */
184
    public function testExpressionLanguageDisabledVirtualProperties()
185
    {
186
        if (!interface_exists('Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface')) {
187
            $this->markTestSkipped("The Symfony Expression Language is not available");
188
        }
189
        $container = $this->getContainerForConfig(array(array('expression_evaluator' => array('id' => null))));
190
        $serializer = $container->get('serializer');
191
        // test that all components have been wired correctly
192
        $object = new ObjectUsingExpressionProperties('foo');
193
        $serializer->serialize($object, 'json');
194
    }
195
196
    /**
197
     * @expectedException \JMS\Serializer\Exception\ExpressionLanguageRequiredException
198
     * @expectedExceptionMessage  To use conditional exclude/expose in JMS\SerializerBundle\Tests\DependencyInjection\Fixture\ObjectUsingExpressionLanguage you must configure the expression language.
199
     */
200
    public function testExpressionLanguageNotLoaded()
201
    {
202
        $container = $this->getContainerForConfig(array(array('expression_evaluator' => array('id' => null))));
203
        $serializer = $container->get('serializer');
204
        // test that all components have been wired correctly
205
        $object = new ObjectUsingExpressionLanguage('foo', true);
206
        $serializer->serialize($object, 'json');
207
    }
208
209
    /**
210
     * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException
211
     * @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
212
     */
213
    public function testExpressionInvalidEvaluator()
214
    {
215
        $this->getContainerForConfig(array(array('expression_evaluator' => array('id' => 'foo'))));
216
    }
217
218
    /**
219
     * @dataProvider getXmlVisitorWhitelists
220
     */
221
    public function testXmlVisitorOptions($expectedOptions, $config)
222
    {
223
        $container = $this->getContainerForConfig(array($config));
224
        $this->assertSame($expectedOptions, $container->get('jms_serializer.xml_deserialization_visitor')->getDoctypeWhitelist());
225
    }
226
227
    public function getXmlVisitorWhitelists()
228
    {
229
        $configs = array();
230
231
        $configs[] = array(array('good document', 'other good document'), array(
232
            'visitors' => array(
233
                'xml' => array(
234
                    'doctype_whitelist' => array('good document', 'other good document'),
235
                )
236
            )
237
        ));
238
239
        $configs[] = array(array(), array());
240
241
        return $configs;
242
    }
243
244
    public function testXmlVisitorFormatOutput()
245
    {
246
        $config = array(
247
            'visitors' => array(
248
                'xml' => array(
249
                    'format_output' => false,
250
                )
251
            )
252
        );
253
        $container = $this->getContainerForConfig(array($config));
254
255
        $this->assertFalse($container->get('jms_serializer.xml_serialization_visitor')->isFormatOutput());
256
    }
257
258
    public function testXmlVisitorDefaultValueToFormatOutput()
259
    {
260
        $container = $this->getContainerForConfig(array());
261
        $this->assertTrue($container->get('jms_serializer.xml_serialization_visitor')->isFormatOutput());
262
    }
263
264
    private function getContainerForConfig(array $configs, KernelInterface $kernel = null)
265
    {
266
        if (null === $kernel) {
267
            $kernel = $this->getMock('Symfony\Component\HttpKernel\KernelInterface');
0 ignored issues
show
Deprecated Code introduced by
The method PHPUnit_Framework_TestCase::getMock() has been deprecated with message: Method deprecated since Release 5.4.0; use createMock() or getMockBuilder() instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
268
            $kernel
269
                ->expects($this->any())
270
                ->method('getBundles')
271
                ->will($this->returnValue(array()))
272
            ;
273
        }
274
275
        $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...
276
        $extension = $bundle->getContainerExtension();
277
278
        $container = new ContainerBuilder();
279
        $container->setParameter('kernel.debug', true);
280
        $container->setParameter('kernel.cache_dir', sys_get_temp_dir().'/serializer');
281
        $container->setParameter('kernel.bundles', array());
282
        $container->set('annotation_reader', new AnnotationReader());
283
        $container->set('translator', $this->getMock('Symfony\\Component\\Translation\\TranslatorInterface'));
0 ignored issues
show
Deprecated Code introduced by
The method PHPUnit_Framework_TestCase::getMock() has been deprecated with message: Method deprecated since Release 5.4.0; use createMock() or getMockBuilder() instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
284
        $container->set('debug.stopwatch', $this->getMock('Symfony\\Component\\Stopwatch\\Stopwatch'));
0 ignored issues
show
Deprecated Code introduced by
The method PHPUnit_Framework_TestCase::getMock() has been deprecated with message: Method deprecated since Release 5.4.0; use createMock() or getMockBuilder() instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
285
        $container->registerExtension($extension);
0 ignored issues
show
Bug introduced by
It seems like $extension defined by $bundle->getContainerExtension() on line 276 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...
286
        $extension->load($configs, $container);
287
288
        $bundle->build($container);
289
290
        $container->getCompilerPassConfig()->setOptimizationPasses(array(
291
            new ResolveParameterPlaceHoldersPass(),
292
            new ResolveDefinitionTemplatesPass(),
293
        ));
294
        $container->getCompilerPassConfig()->setRemovingPasses(array());
295
        $container->compile();
296
297
        return $container;
298
    }
299
}
300