GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — master ( 790e1c...16d896 )
by Asmir
03:45 queued 01:19
created

testExpressionLanguageDisabledVirtualProperties()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 11
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 7
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 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
     */
183
    public function testExpressionLanguageDisabledVirtualProperties()
184
    {
185
        if (!interface_exists('Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface')) {
186
            $this->markTestSkipped("The Symfony Expression Language is not available");
187
        }
188
        $container = $this->getContainerForConfig(array(array('expression_evaluator' => array('id' => null))));
189
        $serializer = $container->get('serializer');
190
        // test that all components have been wired correctly
191
        $object = new ObjectUsingExpressionProperties('foo');
192
        $serializer->serialize($object, 'json');
193
    }
194
195
    /**
196
     * @expectedException \JMS\Serializer\Exception\ExpressionLanguageRequiredException
197
     * @expectedExceptionMessage  To use conditional exclude/expose in JMS\SerializerBundle\Tests\DependencyInjection\Fixture\ObjectUsingExpressionLanguage you must configure the expression language.
198
     */
199
    public function testExpressionLanguageNotLoaded()
200
    {
201
        $container = $this->getContainerForConfig(array(array('expression_evaluator' => array('id' => null))));
202
        $serializer = $container->get('serializer');
203
        // test that all components have been wired correctly
204
        $object = new ObjectUsingExpressionLanguage('foo', true);
205
        $serializer->serialize($object, 'json');
206
    }
207
208
    /**
209
     * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException
210
     * @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
211
     */
212
    public function testExpressionInvalidEvaluator()
213
    {
214
        $this->getContainerForConfig(array(array('expression_evaluator' => array('id' => 'foo'))));
215
    }
216
217
    /**
218
     * @dataProvider getXmlVisitorWhitelists
219
     */
220
    public function testXmlVisitorOptions($expectedOptions, $config)
221
    {
222
        $container = $this->getContainerForConfig(array($config));
223
        $this->assertSame($expectedOptions, $container->get('jms_serializer.xml_deserialization_visitor')->getDoctypeWhitelist());
224
    }
225
226
    public function getXmlVisitorWhitelists()
227
    {
228
        $configs = array();
229
230
        $configs[] = array(array('good document', 'other good document'), array(
231
            'visitors' => array(
232
                'xml' => array(
233
                    'doctype_whitelist' => array('good document', 'other good document'),
234
                )
235
            )
236
        ));
237
238
        $configs[] = array(array(), array());
239
240
        return $configs;
241
    }
242
243
    public function testXmlVisitorFormatOutput()
244
    {
245
        $config = array(
246
            'visitors' => array(
247
                'xml' => array(
248
                    'format_output' => false,
249
                )
250
            )
251
        );
252
        $container = $this->getContainerForConfig(array($config));
253
254
        $this->assertFalse($container->get('jms_serializer.xml_serialization_visitor')->isFormatOutput());
255
    }
256
257
    public function testXmlVisitorDefaultValueToFormatOutput()
258
    {
259
        $container = $this->getContainerForConfig(array());
260
        $this->assertTrue($container->get('jms_serializer.xml_serialization_visitor')->isFormatOutput());
261
    }
262
263
    private function getContainerForConfig(array $configs, KernelInterface $kernel = null)
264
    {
265
        if (null === $kernel) {
266
            $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...
267
            $kernel
268
                ->expects($this->any())
269
                ->method('getBundles')
270
                ->will($this->returnValue(array()))
271
            ;
272
        }
273
274
        $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...
275
        $extension = $bundle->getContainerExtension();
276
277
        $container = new ContainerBuilder();
278
        $container->setParameter('kernel.debug', true);
279
        $container->setParameter('kernel.cache_dir', sys_get_temp_dir().'/serializer');
280
        $container->setParameter('kernel.bundles', array());
281
        $container->set('annotation_reader', new AnnotationReader());
282
        $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...
283
        $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...
284
        $container->registerExtension($extension);
0 ignored issues
show
Bug introduced by
It seems like $extension defined by $bundle->getContainerExtension() on line 275 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...
285
        $extension->load($configs, $container);
286
287
        $bundle->build($container);
288
289
        $container->getCompilerPassConfig()->setOptimizationPasses(array(
290
            new ResolveParameterPlaceHoldersPass(),
291
            new ResolveDefinitionTemplatesPass(),
292
        ));
293
        $container->getCompilerPassConfig()->setRemovingPasses(array());
294
        $container->compile();
295
296
        return $container;
297
    }
298
}
299