Completed
Push — master ( d93623...edf55a )
by Asmir
11s
created

testExpressionInvalidEvaluator()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
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 Symfony\Component\DependencyInjection\Compiler\ResolveParameterPlaceHoldersPass;
24
use Doctrine\Common\Annotations\AnnotationReader;
25
use JMS\SerializerBundle\JMSSerializerBundle;
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\ContainerBuilder;
30
use Symfony\Component\HttpKernel\KernelInterface;
31
32
class JMSSerializerExtensionTest extends \PHPUnit_Framework_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.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 testLoad()
92
    {
93
        $container = $this->getContainerForConfig(array(array()));
94
95
        $simpleObject = new SimpleObject('foo', 'bar');
96
        $versionedObject  = new VersionedObject('foo', 'bar');
97
        $serializer = $container->get('serializer');
98
99
        // test that all components have been wired correctly
100
        $this->assertEquals(json_encode(array('name' => 'bar')), $serializer->serialize($versionedObject, 'json'));
101
        $this->assertEquals($simpleObject, $serializer->deserialize($serializer->serialize($simpleObject, 'json'), get_class($simpleObject), 'json'));
102
        $this->assertEquals($simpleObject, $serializer->deserialize($serializer->serialize($simpleObject, 'xml'), get_class($simpleObject), 'xml'));
103
104
        $this->assertEquals(json_encode(array('name' => 'foo')), $serializer->serialize($versionedObject, 'json', SerializationContext::create()->setVersion('0.0.1')));
105
106
        $this->assertEquals(json_encode(array('name' => 'bar')), $serializer->serialize($versionedObject, 'json', SerializationContext::create()->setVersion('1.1.1')));
107
    }
108
109
    /**
110
     * @dataProvider getJsonVisitorConfigs
111
     */
112
    public function testJsonVisitorOptions($expectedOptions, $config)
113
    {
114
        $container = $this->getContainerForConfig(array($config));
115
        $this->assertSame($expectedOptions, $container->get('jms_serializer.json_serialization_visitor')->getOptions());
116
    }
117
118
    public function getJsonVisitorConfigs()
119
    {
120
        $configs = array();
121
122
        if (version_compare(PHP_VERSION, '5.4', '>=')) {
123
            $configs[] = array(JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT, array(
124
                'visitors' => array(
125
                    'json' => array(
126
                        'options' => array('JSON_UNESCAPED_UNICODE', 'JSON_PRETTY_PRINT')
127
                    )
128
                )
129
            ));
130
131
            $configs[] = array(JSON_UNESCAPED_UNICODE, array(
132
                'visitors' => array(
133
                    'json' => array(
134
                        'options' => 'JSON_UNESCAPED_UNICODE'
135
                    )
136
                )
137
            ));
138
        }
139
140
        $configs[] = array(128, array(
141
            'visitors' => array(
142
                'json' => array(
143
                    'options' => 128
144
                )
145
            )
146
        ));
147
148
        $configs[] = array(0, array());
149
150
        return $configs;
151
    }
152
153
    public function testExpressionLanguage()
154
    {
155
        if (!interface_exists('Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface')) {
156
            $this->markTestSkipped("The Symfony Expression Language is not available");
157
        }
158
        $container = $this->getContainerForConfig(array(array()));
159
        $serializer = $container->get('serializer');
160
        // test that all components have been wired correctly
161
        $object = new ObjectUsingExpressionLanguage('foo', true);
162
        $this->assertEquals('{"name":"foo"}', $serializer->serialize($object, 'json'));
163
        $object = new ObjectUsingExpressionLanguage('foo', false);
164
        $this->assertEquals('{}', $serializer->serialize($object, 'json'));
165
    }
166
167
    /**
168
     * @expectedException \JMS\Serializer\Exception\ExpressionLanguageRequiredException
169
     * @expectedExceptionMessage  To use conditional exclude/expose in JMS\SerializerBundle\Tests\DependencyInjection\Fixture\ObjectUsingExpressionLanguage you must configure the expression language.
170
     */
171
    public function testExpressionLanguageNotLoaded()
172
    {
173
        $container = $this->getContainerForConfig(array(array('expression_evaluator' => array('id' => null))));
174
        $serializer = $container->get('serializer');
175
        // test that all components have been wired correctly
176
        $object = new ObjectUsingExpressionLanguage('foo', true);
177
        $serializer->serialize($object, 'json');
178
    }
179
180
    /**
181
     * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException
182
     * @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
183
     */
184
    public function testExpressionInvalidEvaluator()
185
    {
186
        $this->getContainerForConfig(array(array('expression_evaluator' => array('id' => 'foo'))));
187
    }
188
189
    /**
190
     * @dataProvider getXmlVisitorWhitelists
191
     */
192
    public function testXmlVisitorOptions($expectedOptions, $config)
193
    {
194
        $container = $this->getContainerForConfig(array($config));
195
        $this->assertSame($expectedOptions, $container->get('jms_serializer.xml_deserialization_visitor')->getDoctypeWhitelist());
196
    }
197
198
    public function getXmlVisitorWhitelists()
199
    {
200
        $configs = array();
201
202
        $configs[] = array(array('good document', 'other good document'), array(
203
            'visitors' => array(
204
                'xml' => array(
205
                    'doctype_whitelist' => array('good document', 'other good document'),
206
                )
207
            )
208
        ));
209
210
        $configs[] = array(array(), array());
211
212
        return $configs;
213
    }
214
215
    private function getContainerForConfig(array $configs, KernelInterface $kernel = null)
216
    {
217
        if (null === $kernel) {
218
            $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...
219
            $kernel
220
                ->expects($this->any())
221
                ->method('getBundles')
222
                ->will($this->returnValue(array()))
223
            ;
224
        }
225
226
        $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...
227
        $extension = $bundle->getContainerExtension();
228
229
        $container = new ContainerBuilder();
230
        $container->setParameter('kernel.debug', true);
231
        $container->setParameter('kernel.cache_dir', sys_get_temp_dir().'/serializer');
232
        $container->setParameter('kernel.bundles', array());
233
        $container->set('annotation_reader', new AnnotationReader());
234
        $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...
235
        $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...
236
        $container->registerExtension($extension);
0 ignored issues
show
Bug introduced by
It seems like $extension defined by $bundle->getContainerExtension() on line 227 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...
237
        $extension->load($configs, $container);
238
239
        $bundle->build($container);
240
241
        $container->getCompilerPassConfig()->setOptimizationPasses(array(
242
            new ResolveParameterPlaceHoldersPass(),
243
            new ResolveDefinitionTemplatesPass(),
244
        ));
245
        $container->getCompilerPassConfig()->setRemovingPasses(array());
246
        $container->compile();
247
248
        return $container;
249
    }
250
}
251