Completed
Pull Request — master (#542)
by Asmir
16:51
created

getJsonVisitorConfigs()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 34
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 34
rs 8.8571
cc 2
eloc 17
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 Symfony\Component\DependencyInjection\Compiler\ResolveParameterPlaceHoldersPass;
23
use Doctrine\Common\Annotations\AnnotationReader;
24
use JMS\SerializerBundle\JMSSerializerBundle;
25
use JMS\SerializerBundle\Tests\DependencyInjection\Fixture\SimpleObject;
26
use JMS\SerializerBundle\Tests\DependencyInjection\Fixture\VersionedObject;
27
use Symfony\Component\DependencyInjection\Compiler\ResolveDefinitionTemplatesPass;
28
use Symfony\Component\DependencyInjection\ContainerBuilder;
29
use Symfony\Component\HttpKernel\KernelInterface;
30
31
class JMSSerializerExtensionTest extends \PHPUnit_Framework_TestCase
32
{
33
    protected function setUp()
34
    {
35
        $this->clearTempDir();
36
    }
37
38
    protected function tearDown()
39
    {
40
        $this->clearTempDir();
41
    }
42
43
    private function clearTempDir()
44
    {
45
        // clear temporary directory
46
        $dir = sys_get_temp_dir().'/serializer';
47
        if (is_dir($dir)) {
48
            foreach (new \RecursiveDirectoryIterator($dir) as $file) {
49
                $filename = $file->getFileName();
50
                if ('.' === $filename || '..' === $filename) {
51
                    continue;
52
                }
53
54
                @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...
55
            }
56
57
            @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...
58
        }
59
    }
60
61
    public function testLoad()
62
    {
63
        $container = $this->getContainerForConfig(array(array()));
64
65
        $simpleObject = new SimpleObject('foo', 'bar');
66
        $versionedObject  = new VersionedObject('foo', 'bar');
67
        $serializer = $container->get('serializer');
68
69
        // test that all components have been wired correctly
70
        $this->assertEquals(json_encode(array('name' => 'bar')), $serializer->serialize($versionedObject, 'json'));
71
        $this->assertEquals($simpleObject, $serializer->deserialize($serializer->serialize($simpleObject, 'json'), get_class($simpleObject), 'json'));
72
        $this->assertEquals($simpleObject, $serializer->deserialize($serializer->serialize($simpleObject, 'xml'), get_class($simpleObject), 'xml'));
73
74
        $this->assertEquals(json_encode(array('name' => 'foo')), $serializer->serialize($versionedObject, 'json', SerializationContext::create()->setVersion('0.0.1')));
75
76
        $this->assertEquals(json_encode(array('name' => 'bar')), $serializer->serialize($versionedObject, 'json', SerializationContext::create()->setVersion('1.1.1')));
77
    }
78
79
    /**
80
     * @dataProvider getJsonVisitorConfigs
81
     */
82
    public function testJsonVisitorOptions($expectedOptions, $config)
83
    {
84
        $container = $this->getContainerForConfig(array($config));
85
        $this->assertSame($expectedOptions, $container->get('jms_serializer.json_serialization_visitor')->getOptions());
86
    }
87
88
    public function getJsonVisitorConfigs()
89
    {
90
        $configs = array();
91
92
        if (version_compare(PHP_VERSION, '5.4', '>=')) {
93
            $configs[] = array(JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT, array(
94
                'visitors' => array(
95
                    'json' => array(
96
                        'options' => array('JSON_UNESCAPED_UNICODE', 'JSON_PRETTY_PRINT')
97
                    )
98
                )
99
            ));
100
101
            $configs[] = array(JSON_UNESCAPED_UNICODE, array(
102
                'visitors' => array(
103
                    'json' => array(
104
                        'options' => 'JSON_UNESCAPED_UNICODE'
105
                    )
106
                )
107
            ));
108
        }
109
110
        $configs[] = array(128, array(
111
            'visitors' => array(
112
                'json' => array(
113
                    'options' => 128
114
                )
115
            )
116
        ));
117
118
        $configs[] = array(0, array());
119
120
        return $configs;
121
    }
122
123
    /**
124
     * @dataProvider getXmlVisitorWhitelists
125
     */
126
    public function testXmlVisitorOptions($expectedOptions, $config)
127
    {
128
        $container = $this->getContainerForConfig(array($config));
129
        $this->assertSame($expectedOptions, $container->get('jms_serializer.xml_deserialization_visitor')->getDoctypeWhitelist());
130
    }
131
132
    public function getXmlVisitorWhitelists()
133
    {
134
        $configs = array();
135
136
        $configs[] = array(array('good document', 'other good document'), array(
137
            'visitors' => array(
138
                'xml' => array(
139
                    'doctype_whitelist' => array('good document', 'other good document'),
140
                )
141
            )
142
        ));
143
144
        $configs[] = array(array(), array());
145
146
        return $configs;
147
    }
148
149
    private function getContainerForConfig(array $configs, KernelInterface $kernel = null)
150
    {
151
        if (null === $kernel) {
152
            $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...
153
            $kernel
154
                ->expects($this->any())
155
                ->method('getBundles')
156
                ->will($this->returnValue(array()))
157
            ;
158
        }
159
160
        $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...
161
        $extension = $bundle->getContainerExtension();
162
163
        $container = new ContainerBuilder();
164
        $container->setParameter('kernel.debug', true);
165
        $container->setParameter('kernel.cache_dir', sys_get_temp_dir().'/serializer');
166
        $container->setParameter('kernel.bundles', array());
167
        $container->set('annotation_reader', new AnnotationReader());
168
        $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...
169
        $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...
170
        $container->registerExtension($extension);
0 ignored issues
show
Bug introduced by
It seems like $extension defined by $bundle->getContainerExtension() on line 161 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...
171
        $extension->load($configs, $container);
172
173
        $bundle->build($container);
174
175
        $container->getCompilerPassConfig()->setOptimizationPasses(array(
176
            new ResolveParameterPlaceHoldersPass(),
177
            new ResolveDefinitionTemplatesPass(),
178
        ));
179
        $container->getCompilerPassConfig()->setRemovingPasses(array());
180
        $container->compile();
181
182
        return $container;
183
    }
184
}
185