Completed
Push — master ( 3168f7...d93623 )
by Asmir
9s
created

testSerializerContextFactoriesAreSet()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 17
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 17
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 11
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 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 testHasContextFactories()
62
    {
63
        $container = $this->getContainerForConfig(array(array()));
64
65
        $factory = $container->get('jms_serializer.serialization_context_factory');
66
        $this->assertInstanceOf('JMS\Serializer\ContextFactory\SerializationContextFactoryInterface', $factory);
67
68
        $factory = $container->get('jms_serializer.deserialization_context_factory');
69
        $this->assertInstanceOf('JMS\Serializer\ContextFactory\DeserializationContextFactoryInterface', $factory);
70
    }
71
72
    public function testSerializerContextFactoriesAreSet()
73
    {
74
        $container = $this->getContainerForConfig(array(array()));
75
76
        $def = $container->getDefinition('jms_serializer.serializer');
77
        $calls = $def->getMethodCalls();
78
79
        $this->assertCount(2, $calls);
80
81
        $serializationCall = $calls[0];
82
        $this->assertEquals('setSerializationContextFactory', $serializationCall[0]);
83
        $this->assertEquals('jms_serializer.serialization_context_factory', (string)$serializationCall[1][0]);
84
85
        $serializationCall = $calls[1];
86
        $this->assertEquals('setDeserializationContextFactory', $serializationCall[0]);
87
        $this->assertEquals('jms_serializer.deserialization_context_factory', (string)$serializationCall[1][0]);
88
    }
89
90
    public function testLoad()
91
    {
92
        $container = $this->getContainerForConfig(array(array()));
93
94
        $simpleObject = new SimpleObject('foo', 'bar');
95
        $versionedObject  = new VersionedObject('foo', 'bar');
96
        $serializer = $container->get('serializer');
97
98
        // test that all components have been wired correctly
99
        $this->assertEquals(json_encode(array('name' => 'bar')), $serializer->serialize($versionedObject, 'json'));
100
        $this->assertEquals($simpleObject, $serializer->deserialize($serializer->serialize($simpleObject, 'json'), get_class($simpleObject), 'json'));
101
        $this->assertEquals($simpleObject, $serializer->deserialize($serializer->serialize($simpleObject, 'xml'), get_class($simpleObject), 'xml'));
102
103
        $this->assertEquals(json_encode(array('name' => 'foo')), $serializer->serialize($versionedObject, 'json', SerializationContext::create()->setVersion('0.0.1')));
104
105
        $this->assertEquals(json_encode(array('name' => 'bar')), $serializer->serialize($versionedObject, 'json', SerializationContext::create()->setVersion('1.1.1')));
106
    }
107
108
    /**
109
     * @dataProvider getJsonVisitorConfigs
110
     */
111
    public function testJsonVisitorOptions($expectedOptions, $config)
112
    {
113
        $container = $this->getContainerForConfig(array($config));
114
        $this->assertSame($expectedOptions, $container->get('jms_serializer.json_serialization_visitor')->getOptions());
115
    }
116
117
    public function getJsonVisitorConfigs()
118
    {
119
        $configs = array();
120
121
        if (version_compare(PHP_VERSION, '5.4', '>=')) {
122
            $configs[] = array(JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT, array(
123
                'visitors' => array(
124
                    'json' => array(
125
                        'options' => array('JSON_UNESCAPED_UNICODE', 'JSON_PRETTY_PRINT')
126
                    )
127
                )
128
            ));
129
130
            $configs[] = array(JSON_UNESCAPED_UNICODE, array(
131
                'visitors' => array(
132
                    'json' => array(
133
                        'options' => 'JSON_UNESCAPED_UNICODE'
134
                    )
135
                )
136
            ));
137
        }
138
139
        $configs[] = array(128, array(
140
            'visitors' => array(
141
                'json' => array(
142
                    'options' => 128
143
                )
144
            )
145
        ));
146
147
        $configs[] = array(0, array());
148
149
        return $configs;
150
    }
151
152
    /**
153
     * @dataProvider getXmlVisitorWhitelists
154
     */
155
    public function testXmlVisitorOptions($expectedOptions, $config)
156
    {
157
        $container = $this->getContainerForConfig(array($config));
158
        $this->assertSame($expectedOptions, $container->get('jms_serializer.xml_deserialization_visitor')->getDoctypeWhitelist());
159
    }
160
161
    public function getXmlVisitorWhitelists()
162
    {
163
        $configs = array();
164
165
        $configs[] = array(array('good document', 'other good document'), array(
166
            'visitors' => array(
167
                'xml' => array(
168
                    'doctype_whitelist' => array('good document', 'other good document'),
169
                )
170
            )
171
        ));
172
173
        $configs[] = array(array(), array());
174
175
        return $configs;
176
    }
177
178
    private function getContainerForConfig(array $configs, KernelInterface $kernel = null)
179
    {
180
        if (null === $kernel) {
181
            $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...
182
            $kernel
183
                ->expects($this->any())
184
                ->method('getBundles')
185
                ->will($this->returnValue(array()))
186
            ;
187
        }
188
189
        $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...
190
        $extension = $bundle->getContainerExtension();
191
192
        $container = new ContainerBuilder();
193
        $container->setParameter('kernel.debug', true);
194
        $container->setParameter('kernel.cache_dir', sys_get_temp_dir().'/serializer');
195
        $container->setParameter('kernel.bundles', array());
196
        $container->set('annotation_reader', new AnnotationReader());
197
        $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...
198
        $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...
199
        $container->registerExtension($extension);
0 ignored issues
show
Bug introduced by
It seems like $extension defined by $bundle->getContainerExtension() on line 190 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...
200
        $extension->load($configs, $container);
201
202
        $bundle->build($container);
203
204
        $container->getCompilerPassConfig()->setOptimizationPasses(array(
205
            new ResolveParameterPlaceHoldersPass(),
206
            new ResolveDefinitionTemplatesPass(),
207
        ));
208
        $container->getCompilerPassConfig()->setRemovingPasses(array());
209
        $container->compile();
210
211
        return $container;
212
    }
213
}
214