Actualización

This commit is contained in:
Xes
2025-04-10 12:24:57 +02:00
parent 8969cc929d
commit 45420b6f0d
39760 changed files with 4303286 additions and 0 deletions

View File

@@ -0,0 +1,78 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Serializer\Tests\Encoder;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Serializer\Encoder\ChainDecoder;
class ChainDecoderTest extends TestCase
{
const FORMAT_1 = 'format1';
const FORMAT_2 = 'format2';
const FORMAT_3 = 'format3';
private $chainDecoder;
private $decoder1;
private $decoder2;
protected function setUp()
{
$this->decoder1 = $this
->getMockBuilder('Symfony\Component\Serializer\Encoder\DecoderInterface')
->getMock();
$this->decoder1
->method('supportsDecoding')
->willReturnMap([
[self::FORMAT_1, [], true],
[self::FORMAT_2, [], false],
[self::FORMAT_3, [], false],
[self::FORMAT_3, ['foo' => 'bar'], true],
]);
$this->decoder2 = $this
->getMockBuilder('Symfony\Component\Serializer\Encoder\DecoderInterface')
->getMock();
$this->decoder2
->method('supportsDecoding')
->willReturnMap([
[self::FORMAT_1, [], false],
[self::FORMAT_2, [], true],
[self::FORMAT_3, [], false],
]);
$this->chainDecoder = new ChainDecoder([$this->decoder1, $this->decoder2]);
}
public function testSupportsDecoding()
{
$this->assertTrue($this->chainDecoder->supportsDecoding(self::FORMAT_1));
$this->assertTrue($this->chainDecoder->supportsDecoding(self::FORMAT_2));
$this->assertFalse($this->chainDecoder->supportsDecoding(self::FORMAT_3));
$this->assertTrue($this->chainDecoder->supportsDecoding(self::FORMAT_3, ['foo' => 'bar']));
}
public function testDecode()
{
$this->decoder1->expects($this->never())->method('decode');
$this->decoder2->expects($this->once())->method('decode');
$this->chainDecoder->decode('string_to_decode', self::FORMAT_2);
}
public function testDecodeUnsupportedFormat()
{
$this->expectException('Symfony\Component\Serializer\Exception\RuntimeException');
$this->chainDecoder->decode('string_to_decode', self::FORMAT_3);
}
}

View File

@@ -0,0 +1,106 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Serializer\Tests\Encoder;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Serializer\Encoder\ChainEncoder;
use Symfony\Component\Serializer\Encoder\EncoderInterface;
use Symfony\Component\Serializer\Encoder\NormalizationAwareInterface;
class ChainEncoderTest extends TestCase
{
const FORMAT_1 = 'format1';
const FORMAT_2 = 'format2';
const FORMAT_3 = 'format3';
private $chainEncoder;
private $encoder1;
private $encoder2;
protected function setUp()
{
$this->encoder1 = $this
->getMockBuilder('Symfony\Component\Serializer\Encoder\EncoderInterface')
->getMock();
$this->encoder1
->method('supportsEncoding')
->willReturnMap([
[self::FORMAT_1, [], true],
[self::FORMAT_2, [], false],
[self::FORMAT_3, [], false],
[self::FORMAT_3, ['foo' => 'bar'], true],
]);
$this->encoder2 = $this
->getMockBuilder('Symfony\Component\Serializer\Encoder\EncoderInterface')
->getMock();
$this->encoder2
->method('supportsEncoding')
->willReturnMap([
[self::FORMAT_1, [], false],
[self::FORMAT_2, [], true],
[self::FORMAT_3, [], false],
]);
$this->chainEncoder = new ChainEncoder([$this->encoder1, $this->encoder2]);
}
public function testSupportsEncoding()
{
$this->assertTrue($this->chainEncoder->supportsEncoding(self::FORMAT_1));
$this->assertTrue($this->chainEncoder->supportsEncoding(self::FORMAT_2));
$this->assertFalse($this->chainEncoder->supportsEncoding(self::FORMAT_3));
$this->assertTrue($this->chainEncoder->supportsEncoding(self::FORMAT_3, ['foo' => 'bar']));
}
public function testEncode()
{
$this->encoder1->expects($this->never())->method('encode');
$this->encoder2->expects($this->once())->method('encode');
$this->chainEncoder->encode(['foo' => 123], self::FORMAT_2);
}
public function testEncodeUnsupportedFormat()
{
$this->expectException('Symfony\Component\Serializer\Exception\RuntimeException');
$this->chainEncoder->encode(['foo' => 123], self::FORMAT_3);
}
public function testNeedsNormalizationBasic()
{
$this->assertTrue($this->chainEncoder->needsNormalization(self::FORMAT_1));
$this->assertTrue($this->chainEncoder->needsNormalization(self::FORMAT_2));
}
public function testNeedsNormalizationNormalizationAware()
{
$encoder = new NormalizationAwareEncoder();
$sut = new ChainEncoder([$encoder]);
$this->assertFalse($sut->needsNormalization(self::FORMAT_1));
}
}
class NormalizationAwareEncoder implements EncoderInterface, NormalizationAwareInterface
{
public function supportsEncoding($format)
{
return true;
}
public function encode($data, $format, array $context = [])
{
}
}

View File

@@ -0,0 +1,348 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Serializer\Tests\Encoder;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Serializer\Encoder\CsvEncoder;
/**
* @author Kévin Dunglas <dunglas@gmail.com>
*/
class CsvEncoderTest extends TestCase
{
/**
* @var CsvEncoder
*/
private $encoder;
protected function setUp()
{
$this->encoder = new CsvEncoder();
}
public function testTrueFalseValues()
{
$data = [
'string' => 'foo',
'int' => 2,
'false' => false,
'true' => true,
'int_one' => 1,
'string_one' => '1',
];
// Check that true and false are appropriately handled
$this->assertSame($csv = <<<'CSV'
string,int,false,true,int_one,string_one
foo,2,0,1,1,1
CSV
, $this->encoder->encode($data, 'csv'));
$this->assertSame([
'string' => 'foo',
'int' => '2',
'false' => '0',
'true' => '1',
'int_one' => '1',
'string_one' => '1',
], $this->encoder->decode($csv, 'csv'));
}
/**
* @requires PHP 7.4
*/
public function testDoubleQuotesAndSlashes()
{
$this->assertSame($csv = <<<'CSV'
0,1,2,3,4,5
,"""","foo""","\""",\,foo\
CSV
, $this->encoder->encode($data = ['', '"', 'foo"', '\\"', '\\', 'foo\\'], 'csv'));
$this->assertSame($data, $this->encoder->decode($csv, 'csv'));
}
/**
* @requires PHP 7.4
*/
public function testSingleSlash()
{
$this->assertSame($csv = "0\n\\\n", $this->encoder->encode($data = ['\\'], 'csv'));
$this->assertSame($data, $this->encoder->decode($csv, 'csv'));
$this->assertSame($data, $this->encoder->decode(trim($csv), 'csv'));
}
public function testSupportEncoding()
{
$this->assertTrue($this->encoder->supportsEncoding('csv'));
$this->assertFalse($this->encoder->supportsEncoding('foo'));
}
public function testEncode()
{
$value = ['foo' => 'hello', 'bar' => 'hey ho'];
$this->assertEquals(<<<'CSV'
foo,bar
hello,"hey ho"
CSV
, $this->encoder->encode($value, 'csv'));
}
public function testEncodeCollection()
{
$value = [
['foo' => 'hello', 'bar' => 'hey ho'],
['foo' => 'hi', 'bar' => 'let\'s go'],
];
$this->assertEquals(<<<'CSV'
foo,bar
hello,"hey ho"
hi,"let's go"
CSV
, $this->encoder->encode($value, 'csv'));
}
public function testEncodePlainIndexedArray()
{
$this->assertEquals(<<<'CSV'
0,1,2
a,b,c
CSV
, $this->encoder->encode(['a', 'b', 'c'], 'csv'));
}
public function testEncodeNonArray()
{
$this->assertEquals(<<<'CSV'
0
foo
CSV
, $this->encoder->encode('foo', 'csv'));
}
public function testEncodeNestedArrays()
{
$value = ['foo' => 'hello', 'bar' => [
['id' => 'yo', 1 => 'wesh'],
['baz' => 'Halo', 'foo' => 'olá'],
]];
$this->assertEquals(<<<'CSV'
foo,bar.0.id,bar.0.1,bar.1.baz,bar.1.foo
hello,yo,wesh,Halo,olá
CSV
, $this->encoder->encode($value, 'csv'));
}
public function testEncodeCustomSettings()
{
$this->encoder = new CsvEncoder(';', "'", '|', '-');
$value = ['a' => 'he\'llo', 'c' => ['d' => 'foo']];
$this->assertEquals(<<<'CSV'
a;c-d
'he''llo';foo
CSV
, $this->encoder->encode($value, 'csv'));
}
public function testEncodeCustomSettingsPassedInContext()
{
$value = ['a' => 'he\'llo', 'c' => ['d' => 'foo']];
$this->assertSame(<<<'CSV'
a;c-d
'he''llo';foo
CSV
, $this->encoder->encode($value, 'csv', [
CsvEncoder::DELIMITER_KEY => ';',
CsvEncoder::ENCLOSURE_KEY => "'",
CsvEncoder::ESCAPE_CHAR_KEY => '|',
CsvEncoder::KEY_SEPARATOR_KEY => '-',
]));
}
public function testEncodeEmptyArray()
{
$this->assertEquals("\n\n", $this->encoder->encode([], 'csv'));
$this->assertEquals("\n\n", $this->encoder->encode([[]], 'csv'));
}
public function testEncodeVariableStructure()
{
$value = [
['a' => ['foo', 'bar']],
['a' => [], 'b' => 'baz'],
['a' => ['bar', 'foo'], 'c' => 'pong'],
];
$csv = <<<CSV
a.0,a.1,c,b
foo,bar,,
,,,baz
bar,foo,pong,
CSV;
$this->assertEquals($csv, $this->encoder->encode($value, 'csv'));
}
public function testEncodeCustomHeaders()
{
$context = [
CsvEncoder::HEADERS_KEY => [
'b',
'c',
],
];
$value = [
['a' => 'foo', 'b' => 'bar'],
];
$csv = <<<CSV
b,c,a
bar,,foo
CSV;
$this->assertEquals($csv, $this->encoder->encode($value, 'csv', $context));
}
public function testSupportsDecoding()
{
$this->assertTrue($this->encoder->supportsDecoding('csv'));
$this->assertFalse($this->encoder->supportsDecoding('foo'));
}
public function testDecode()
{
$expected = ['foo' => 'a', 'bar' => 'b'];
$this->assertEquals($expected, $this->encoder->decode(<<<'CSV'
foo,bar
a,b
CSV
, 'csv'));
}
public function testDecodeCollection()
{
$expected = [
['foo' => 'a', 'bar' => 'b'],
['foo' => 'c', 'bar' => 'd'],
['foo' => 'f'],
];
$this->assertEquals($expected, $this->encoder->decode(<<<'CSV'
foo,bar
a,b
c,d
f
CSV
, 'csv'));
}
public function testDecodeToManyRelation()
{
$expected = [
['foo' => 'bar', 'relations' => [['a' => 'b'], ['a' => 'b']]],
['foo' => 'bat', 'relations' => [['a' => 'b'], ['a' => '']]],
['foo' => 'bat', 'relations' => [['a' => 'b']]],
['foo' => 'baz', 'relations' => [['a' => 'c'], ['a' => 'c']]],
];
$this->assertEquals($expected, $this->encoder->decode(<<<'CSV'
foo,relations.0.a,relations.1.a
bar,b,b
bat,b,
bat,b
baz,c,c
CSV
, 'csv'));
}
public function testDecodeNestedArrays()
{
$expected = [
['foo' => 'a', 'bar' => ['baz' => ['bat' => 'b']]],
['foo' => 'c', 'bar' => ['baz' => ['bat' => 'd']]],
];
$this->assertEquals($expected, $this->encoder->decode(<<<'CSV'
foo,bar.baz.bat
a,b
c,d
CSV
, 'csv'));
}
public function testDecodeCustomSettings()
{
$this->encoder = new CsvEncoder(';', "'", '|', '-');
$expected = ['a' => 'hell\'o', 'bar' => ['baz' => 'b']];
$this->assertEquals($expected, $this->encoder->decode(<<<'CSV'
a;bar-baz
'hell''o';b;c
CSV
, 'csv'));
}
public function testDecodeCustomSettingsPassedInContext()
{
$expected = ['a' => 'hell\'o', 'bar' => ['baz' => 'b']];
$this->assertEquals($expected, $this->encoder->decode(<<<'CSV'
a;bar-baz
'hell''o';b;c
CSV
, 'csv', [
CsvEncoder::DELIMITER_KEY => ';',
CsvEncoder::ENCLOSURE_KEY => "'",
CsvEncoder::ESCAPE_CHAR_KEY => '|',
CsvEncoder::KEY_SEPARATOR_KEY => '-',
]));
}
public function testDecodeMalformedCollection()
{
$expected = [
['foo' => 'a', 'bar' => 'b'],
['foo' => 'c', 'bar' => 'd'],
['foo' => 'f'],
];
$this->assertEquals($expected, $this->encoder->decode(<<<'CSV'
foo,bar
a,b,e
c,d,g,h
f
CSV
, 'csv'));
}
public function testDecodeEmptyArray()
{
$this->assertEquals([], $this->encoder->decode('', 'csv'));
}
}

View File

@@ -0,0 +1,75 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Serializer\Tests\Encoder;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Serializer\Encoder\JsonDecode;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
class JsonDecodeTest extends TestCase
{
/** @var \Symfony\Component\Serializer\Encoder\JsonDecode */
private $decode;
protected function setUp()
{
$this->decode = new JsonDecode();
}
public function testSupportsDecoding()
{
$this->assertTrue($this->decode->supportsDecoding(JsonEncoder::FORMAT));
$this->assertFalse($this->decode->supportsDecoding('foobar'));
}
/**
* @dataProvider decodeProvider
*/
public function testDecode($toDecode, $expected, $context)
{
$this->assertEquals(
$expected,
$this->decode->decode($toDecode, JsonEncoder::FORMAT, $context)
);
}
public function decodeProvider()
{
$stdClass = new \stdClass();
$stdClass->foo = 'bar';
$assoc = ['foo' => 'bar'];
return [
['{"foo": "bar"}', $stdClass, []],
['{"foo": "bar"}', $assoc, ['json_decode_associative' => true]],
];
}
/**
* @requires function json_last_error_msg
* @dataProvider decodeProviderException
*/
public function testDecodeWithException($value)
{
$this->expectException('Symfony\Component\Serializer\Exception\UnexpectedValueException');
$this->decode->decode($value, JsonEncoder::FORMAT);
}
public function decodeProviderException()
{
return [
["{'foo': 'bar'}"],
['kaboom!'],
];
}
}

View File

@@ -0,0 +1,60 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Serializer\Tests\Encoder;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Serializer\Encoder\JsonEncode;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
class JsonEncodeTest extends TestCase
{
private $encoder;
protected function setUp()
{
$this->encode = new JsonEncode();
}
public function testSupportsEncoding()
{
$this->assertTrue($this->encode->supportsEncoding(JsonEncoder::FORMAT));
$this->assertFalse($this->encode->supportsEncoding('foobar'));
}
/**
* @dataProvider encodeProvider
*/
public function testEncode($toEncode, $expected, $context)
{
$this->assertEquals(
$expected,
$this->encode->encode($toEncode, JsonEncoder::FORMAT, $context)
);
}
public function encodeProvider()
{
return [
[[], '[]', []],
[[], '{}', ['json_encode_options' => \JSON_FORCE_OBJECT]],
];
}
/**
* @requires function json_last_error_msg
*/
public function testEncodeWithError()
{
$this->expectException('Symfony\Component\Serializer\Exception\UnexpectedValueException');
$this->encode->encode("\xB1\x31", JsonEncoder::FORMAT);
}
}

View File

@@ -0,0 +1,119 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Serializer\Tests\Encoder;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\CustomNormalizer;
use Symfony\Component\Serializer\Serializer;
class JsonEncoderTest extends TestCase
{
private $encoder;
private $serializer;
protected function setUp()
{
$this->encoder = new JsonEncoder();
$this->serializer = new Serializer([new CustomNormalizer()], ['json' => new JsonEncoder()]);
}
public function testEncodeScalar()
{
$obj = new \stdClass();
$obj->foo = 'foo';
$expected = '{"foo":"foo"}';
$this->assertEquals($expected, $this->encoder->encode($obj, 'json'));
}
public function testComplexObject()
{
$obj = $this->getObject();
$expected = $this->getJsonSource();
$this->assertEquals($expected, $this->encoder->encode($obj, 'json'));
}
public function testOptions()
{
$context = ['json_encode_options' => \JSON_NUMERIC_CHECK];
$arr = [];
$arr['foo'] = '3';
$expected = '{"foo":3}';
$this->assertEquals($expected, $this->serializer->serialize($arr, 'json', $context));
$arr = [];
$arr['foo'] = '3';
$expected = '{"foo":"3"}';
$this->assertEquals($expected, $this->serializer->serialize($arr, 'json'), 'Context should not be persistent');
}
public function testEncodeNotUtf8WithoutPartialOnError()
{
$this->expectException('Symfony\Component\Serializer\Exception\UnexpectedValueException');
$arr = [
'utf8' => 'Hello World!',
'notUtf8' => "\xb0\xd0\xb5\xd0",
];
$this->encoder->encode($arr, 'json');
}
public function testEncodeNotUtf8WithPartialOnError()
{
$context = ['json_encode_options' => \JSON_PARTIAL_OUTPUT_ON_ERROR];
$arr = [
'utf8' => 'Hello World!',
'notUtf8' => "\xb0\xd0\xb5\xd0",
];
$result = $this->encoder->encode($arr, 'json', $context);
$jsonLastError = json_last_error();
$this->assertSame(\JSON_ERROR_UTF8, $jsonLastError);
$this->assertEquals('{"utf8":"Hello World!","notUtf8":null}', $result);
$this->assertEquals('0', $this->serializer->serialize(\NAN, 'json', $context));
}
public function testDecodeFalseString()
{
$result = $this->encoder->decode('false', 'json');
$this->assertSame(\JSON_ERROR_NONE, json_last_error());
$this->assertFalse($result);
}
protected function getJsonSource()
{
return '{"foo":"foo","bar":["a","b"],"baz":{"key":"val","key2":"val","A B":"bar","item":[{"title":"title1"},{"title":"title2"}],"Barry":{"FooBar":{"Baz":"Ed","@id":1}}},"qux":"1"}';
}
protected function getObject()
{
$obj = new \stdClass();
$obj->foo = 'foo';
$obj->bar = ['a', 'b'];
$obj->baz = ['key' => 'val', 'key2' => 'val', 'A B' => 'bar', 'item' => [['title' => 'title1'], ['title' => 'title2']], 'Barry' => ['FooBar' => ['Baz' => 'Ed', '@id' => 1]]];
$obj->qux = '1';
return $obj;
}
}

View File

@@ -0,0 +1,768 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Serializer\Tests\Encoder;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Exception\NotEncodableValueException;
use Symfony\Component\Serializer\Normalizer\CustomNormalizer;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Tests\Fixtures\Dummy;
use Symfony\Component\Serializer\Tests\Fixtures\NormalizableTraversableDummy;
use Symfony\Component\Serializer\Tests\Fixtures\ScalarDummy;
class XmlEncoderTest extends TestCase
{
/**
* @var XmlEncoder
*/
private $encoder;
private $exampleDateTimeString = '2017-02-19T15:16:08+0300';
protected function setUp()
{
$this->encoder = new XmlEncoder();
$serializer = new Serializer([new CustomNormalizer()], ['xml' => new XmlEncoder()]);
$this->encoder->setSerializer($serializer);
}
public function testEncodeScalar()
{
$obj = new ScalarDummy();
$obj->xmlFoo = 'foo';
$expected = '<?xml version="1.0"?>'."\n".
'<response>foo</response>'."\n";
$this->assertEquals($expected, $this->encoder->encode($obj, 'xml'));
}
public function testSetRootNodeName()
{
$obj = new ScalarDummy();
$obj->xmlFoo = 'foo';
$this->encoder->setRootNodeName('test');
$expected = '<?xml version="1.0"?>'."\n".
'<test>foo</test>'."\n";
$this->assertEquals($expected, $this->encoder->encode($obj, 'xml'));
}
public function testDocTypeIsNotAllowed()
{
$this->expectException('Symfony\Component\Serializer\Exception\UnexpectedValueException');
$this->expectExceptionMessage('Document types are not allowed.');
$this->encoder->decode('<?xml version="1.0"?><!DOCTYPE foo><foo></foo>', 'foo');
}
public function testAttributes()
{
$obj = new ScalarDummy();
$obj->xmlFoo = [
'foo-bar' => [
'@id' => 1,
'@name' => 'Bar',
],
'Foo' => [
'Bar' => 'Test',
'@Type' => 'test',
],
'föo_bär' => 'a',
'Bar' => [1, 2, 3],
'a' => 'b',
];
$expected = '<?xml version="1.0"?>'."\n".
'<response>'.
'<foo-bar id="1" name="Bar"/>'.
'<Foo Type="test"><Bar>Test</Bar></Foo>'.
'<föo_bär>a</föo_bär>'.
'<Bar>1</Bar>'.
'<Bar>2</Bar>'.
'<Bar>3</Bar>'.
'<a>b</a>'.
'</response>'."\n";
$this->assertEquals($expected, $this->encoder->encode($obj, 'xml'));
}
public function testElementNameValid()
{
$obj = new ScalarDummy();
$obj->xmlFoo = [
'foo-bar' => 'a',
'foo_bar' => 'a',
'föo_bär' => 'a',
];
$expected = '<?xml version="1.0"?>'."\n".
'<response>'.
'<foo-bar>a</foo-bar>'.
'<foo_bar>a</foo_bar>'.
'<föo_bär>a</föo_bär>'.
'</response>'."\n";
$this->assertEquals($expected, $this->encoder->encode($obj, 'xml'));
}
public function testEncodeSimpleXML()
{
$xml = simplexml_load_string('<firstname>Peter</firstname>');
$array = ['person' => $xml];
$expected = '<?xml version="1.0"?>'."\n".
'<response><person><firstname>Peter</firstname></person></response>'."\n";
$this->assertEquals($expected, $this->encoder->encode($array, 'xml'));
}
public function testEncodeXmlAttributes()
{
$xml = simplexml_load_string('<firstname>Peter</firstname>');
$array = ['person' => $xml];
$expected = '<?xml version="1.1" encoding="utf-8" standalone="yes"?>'."\n".
'<response><person><firstname>Peter</firstname></person></response>'."\n";
$context = [
'xml_version' => '1.1',
'xml_encoding' => 'utf-8',
'xml_standalone' => true,
];
$this->assertSame($expected, $this->encoder->encode($array, 'xml', $context));
}
public function testEncodeRemovingEmptyTags()
{
$array = ['person' => ['firstname' => 'Peter', 'lastname' => null]];
$expected = '<?xml version="1.0"?>'."\n".
'<response><person><firstname>Peter</firstname></person></response>'."\n";
$context = ['remove_empty_tags' => true];
$this->assertSame($expected, $this->encoder->encode($array, 'xml', $context));
}
public function testEncodeNotRemovingEmptyTags()
{
$array = ['person' => ['firstname' => 'Peter', 'lastname' => null]];
$expected = '<?xml version="1.0"?>'."\n".
'<response><person><firstname>Peter</firstname><lastname/></person></response>'."\n";
$this->assertSame($expected, $this->encoder->encode($array, 'xml'));
}
public function testContext()
{
$array = ['person' => ['name' => 'George Abitbol']];
$expected = <<<'XML'
<?xml version="1.0"?>
<response>
<person>
<name>George Abitbol</name>
</person>
</response>
XML;
$context = [
'xml_format_output' => true,
];
$this->assertSame($expected, $this->encoder->encode($array, 'xml', $context));
}
public function testEncodeScalarRootAttributes()
{
$array = [
'#' => 'Paul',
'@eye-color' => 'brown',
];
$expected = '<?xml version="1.0"?>'."\n".
'<response eye-color="brown">Paul</response>'."\n";
$this->assertEquals($expected, $this->encoder->encode($array, 'xml'));
}
public function testEncodeRootAttributes()
{
$array = [
'firstname' => 'Paul',
'@eye-color' => 'brown',
];
$expected = '<?xml version="1.0"?>'."\n".
'<response eye-color="brown"><firstname>Paul</firstname></response>'."\n";
$this->assertEquals($expected, $this->encoder->encode($array, 'xml'));
}
public function testEncodeCdataWrapping()
{
$array = [
'firstname' => 'Paul <or Me>',
];
$expected = '<?xml version="1.0"?>'."\n".
'<response><firstname><![CDATA[Paul <or Me>]]></firstname></response>'."\n";
$this->assertEquals($expected, $this->encoder->encode($array, 'xml'));
}
public function testEncodeScalarWithAttribute()
{
$array = [
'person' => ['@eye-color' => 'brown', '#' => 'Peter'],
];
$expected = '<?xml version="1.0"?>'."\n".
'<response><person eye-color="brown">Peter</person></response>'."\n";
$this->assertEquals($expected, $this->encoder->encode($array, 'xml'));
}
public function testDecodeScalar()
{
$source = '<?xml version="1.0"?>'."\n".
'<response>foo</response>'."\n";
$this->assertEquals('foo', $this->encoder->decode($source, 'xml'));
}
public function testDecodeBigDigitAttributes()
{
$source = <<<XML
<?xml version="1.0"?>
<document index="182077241760011681341821060401202210011000045913000000017100">Name</document>
XML;
$this->assertSame(['@index' => 182077241760011681341821060401202210011000045913000000017100, '#' => 'Name'], $this->encoder->decode($source, 'xml'));
}
public function testDecodeNegativeIntAttribute()
{
$source = <<<XML
<?xml version="1.0"?>
<document index="-1234">Name</document>
XML;
$this->assertSame(['@index' => -1234, '#' => 'Name'], $this->encoder->decode($source, 'xml'));
}
public function testDecodeFloatAttribute()
{
$source = <<<XML
<?xml version="1.0"?>
<document index="12.11">Name</document>
XML;
$this->assertSame(['@index' => 12.11, '#' => 'Name'], $this->encoder->decode($source, 'xml'));
}
public function testDecodeNegativeFloatAttribute()
{
$source = <<<XML
<?xml version="1.0"?>
<document index="-12.11">Name</document>
XML;
$this->assertSame(['@index' => -12.11, '#' => 'Name'], $this->encoder->decode($source, 'xml'));
}
public function testDecodeFloatAttributeWithZeroWholeNumber()
{
$source = <<<XML
<?xml version="1.0"?>
<document index="0.123">Name</document>
XML;
$this->assertSame(['@index' => 0.123, '#' => 'Name'], $this->encoder->decode($source, 'xml'));
}
public function testNoTypeCastAttribute()
{
$source = <<<XML
<?xml version="1.0"?>
<document a="018" b="-12.11">
<node a="018" b="-12.11"/>
</document>
XML;
$data = $this->encoder->decode($source, 'xml', ['xml_type_cast_attributes' => false]);
$expected = [
'@a' => '018',
'@b' => '-12.11',
'node' => [
'@a' => '018',
'@b' => '-12.11',
'#' => '',
],
];
$this->assertSame($expected, $data);
}
public function testDoesNotTypeCastStringsStartingWith0()
{
$source = <<<XML
<?xml version="1.0"?>
<document a="018"></document>
XML;
$data = $this->encoder->decode($source, 'xml');
$this->assertSame('018', $data['@a']);
}
public function testEncode()
{
$source = $this->getXmlSource();
$obj = $this->getObject();
$this->assertEquals($source, $this->encoder->encode($obj, 'xml'));
}
public function testEncodeWithNamespace()
{
$source = $this->getNamespacedXmlSource();
$array = $this->getNamespacedArray();
$this->assertEquals($source, $this->encoder->encode($array, 'xml'));
}
public function testEncodeSerializerXmlRootNodeNameOption()
{
$options = ['xml_root_node_name' => 'test'];
$this->encoder = new XmlEncoder();
$serializer = new Serializer([], ['xml' => new XmlEncoder()]);
$this->encoder->setSerializer($serializer);
$array = [
'person' => ['@eye-color' => 'brown', '#' => 'Peter'],
];
$expected = '<?xml version="1.0"?>'."\n".
'<test><person eye-color="brown">Peter</person></test>'."\n";
$this->assertEquals($expected, $serializer->serialize($array, 'xml', $options));
}
public function testEncodeTraversableWhenNormalizable()
{
$this->encoder = new XmlEncoder();
$serializer = new Serializer([new CustomNormalizer()], ['xml' => new XmlEncoder()]);
$this->encoder->setSerializer($serializer);
$expected = <<<'XML'
<?xml version="1.0"?>
<response><foo>normalizedFoo</foo><bar>normalizedBar</bar></response>
XML;
$this->assertEquals($expected, $serializer->serialize(new NormalizableTraversableDummy(), 'xml'));
}
public function testDecode()
{
$source = $this->getXmlSource();
$obj = $this->getObject();
$this->assertEquals(get_object_vars($obj), $this->encoder->decode($source, 'xml'));
}
public function testDecodeCdataWrapping()
{
$expected = [
'firstname' => 'Paul <or Me>',
];
$xml = '<?xml version="1.0"?>'."\n".
'<response><firstname><![CDATA[Paul <or Me>]]></firstname></response>'."\n";
$this->assertEquals($expected, $this->encoder->decode($xml, 'xml'));
}
public function testDecodeCdataWrappingAndWhitespace()
{
$expected = [
'firstname' => 'Paul <or Me>',
];
$xml = '<?xml version="1.0"?>'."\n".
'<response><firstname>'."\n".
'<![CDATA[Paul <or Me>]]></firstname></response>'."\n";
$this->assertEquals($expected, $this->encoder->decode($xml, 'xml'));
}
public function testDecodeWithNamespace()
{
$source = $this->getNamespacedXmlSource();
$array = $this->getNamespacedArray();
$this->assertEquals($array, $this->encoder->decode($source, 'xml'));
}
public function testDecodeScalarWithAttribute()
{
$source = '<?xml version="1.0"?>'."\n".
'<response><person eye-color="brown">Peter</person></response>'."\n";
$expected = [
'person' => ['@eye-color' => 'brown', '#' => 'Peter'],
];
$this->assertEquals($expected, $this->encoder->decode($source, 'xml'));
}
public function testDecodeScalarRootAttributes()
{
$source = '<?xml version="1.0"?>'."\n".
'<person eye-color="brown">Peter</person>'."\n";
$expected = [
'#' => 'Peter',
'@eye-color' => 'brown',
];
$this->assertEquals($expected, $this->encoder->decode($source, 'xml'));
}
public function testDecodeRootAttributes()
{
$source = '<?xml version="1.0"?>'."\n".
'<person eye-color="brown"><firstname>Peter</firstname><lastname>Mac Calloway</lastname></person>'."\n";
$expected = [
'firstname' => 'Peter',
'lastname' => 'Mac Calloway',
'@eye-color' => 'brown',
];
$this->assertEquals($expected, $this->encoder->decode($source, 'xml'));
}
public function testDecodeArray()
{
$source = '<?xml version="1.0"?>'."\n".
'<response>'.
'<people>'.
'<person><firstname>Benjamin</firstname><lastname>Alexandre</lastname></person>'.
'<person><firstname>Damien</firstname><lastname>Clay</lastname></person>'.
'</people>'.
'</response>'."\n";
$expected = [
'people' => ['person' => [
['firstname' => 'Benjamin', 'lastname' => 'Alexandre'],
['firstname' => 'Damien', 'lastname' => 'Clay'],
]],
];
$this->assertEquals($expected, $this->encoder->decode($source, 'xml'));
}
public function testDecodeXMLWithProcessInstruction()
{
$source = <<<'XML'
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="/xsl/xmlverbatimwrapper.xsl"?>
<?display table-view?>
<?sort alpha-ascending?>
<response>
<foo>foo</foo>
<?textinfo whitespace is allowed ?>
<bar>a</bar>
<bar>b</bar>
<baz>
<key>val</key>
<key2>val</key2>
<item key="A B">bar</item>
<item>
<title>title1</title>
</item>
<?item ignore-title ?>
<item>
<title>title2</title>
</item>
<Barry>
<FooBar id="1">
<Baz>Ed</Baz>
</FooBar>
</Barry>
</baz>
<qux>1</qux>
</response>
<?instruction <value> ?>
XML;
$obj = $this->getObject();
$this->assertEquals(get_object_vars($obj), $this->encoder->decode($source, 'xml'));
}
public function testDecodeIgnoreWhiteSpace()
{
$source = <<<'XML'
<?xml version="1.0"?>
<people>
<person>
<firstname>Benjamin</firstname>
<lastname>Alexandre</lastname>
</person>
<person>
<firstname>Damien</firstname>
<lastname>Clay</lastname>
</person>
</people>
XML;
$expected = ['person' => [
['firstname' => 'Benjamin', 'lastname' => 'Alexandre'],
['firstname' => 'Damien', 'lastname' => 'Clay'],
]];
$this->assertEquals($expected, $this->encoder->decode($source, 'xml'));
}
public function testDecodeWithoutItemHash()
{
$obj = new ScalarDummy();
$obj->xmlFoo = [
'foo-bar' => [
'@key' => 'value',
'item' => ['@key' => 'key', 'key-val' => 'val'],
],
'Foo' => [
'Bar' => 'Test',
'@Type' => 'test',
],
'föo_bär' => 'a',
'Bar' => [1, 2, 3],
'a' => 'b',
];
$expected = [
'foo-bar' => [
'@key' => 'value',
'key' => ['@key' => 'key', 'key-val' => 'val'],
],
'Foo' => [
'Bar' => 'Test',
'@Type' => 'test',
],
'föo_bär' => 'a',
'Bar' => [1, 2, 3],
'a' => 'b',
];
$xml = $this->encoder->encode($obj, 'xml');
$this->assertEquals($expected, $this->encoder->decode($xml, 'xml'));
}
public function testDecodeInvalidXml()
{
$this->expectException('Symfony\Component\Serializer\Exception\UnexpectedValueException');
$this->encoder->decode('<?xml version="1.0"?><invalid><xml>', 'xml');
}
public function testPreventsComplexExternalEntities()
{
$this->expectException('Symfony\Component\Serializer\Exception\UnexpectedValueException');
$this->encoder->decode('<?xml version="1.0"?><!DOCTYPE scan[<!ENTITY test SYSTEM "php://filter/read=convert.base64-encode/resource=XmlEncoderTest.php">]><scan>&test;</scan>', 'xml');
}
public function testDecodeEmptyXml()
{
$this->expectException('Symfony\Component\Serializer\Exception\UnexpectedValueException');
$this->expectExceptionMessage('Invalid XML data, it can not be empty.');
$this->encoder->decode(' ', 'xml');
}
protected function getXmlSource()
{
return '<?xml version="1.0"?>'."\n".
'<response>'.
'<foo>foo</foo>'.
'<bar>a</bar><bar>b</bar>'.
'<baz><key>val</key><key2>val</key2><item key="A B">bar</item>'.
'<item><title>title1</title></item><item><title>title2</title></item>'.
'<Barry><FooBar id="1"><Baz>Ed</Baz></FooBar></Barry></baz>'.
'<qux>1</qux>'.
'</response>'."\n";
}
protected function getNamespacedXmlSource()
{
return '<?xml version="1.0"?>'."\n".
'<response xmlns="http://www.w3.org/2005/Atom" xmlns:app="http://www.w3.org/2007/app" xmlns:media="http://search.yahoo.com/mrss/" xmlns:gd="http://schemas.google.com/g/2005" xmlns:yt="http://gdata.youtube.com/schemas/2007">'.
'<qux>1</qux>'.
'<app:foo>foo</app:foo>'.
'<yt:bar>a</yt:bar><yt:bar>b</yt:bar>'.
'<media:baz><media:key>val</media:key><media:key2>val</media:key2><item key="A B">bar</item>'.
'<item><title>title1</title></item><item><title>title2</title></item>'.
'<Barry size="large"><FooBar gd:id="1"><Baz>Ed</Baz></FooBar></Barry></media:baz>'.
'</response>'."\n";
}
protected function getNamespacedArray()
{
return [
'@xmlns' => 'http://www.w3.org/2005/Atom',
'@xmlns:app' => 'http://www.w3.org/2007/app',
'@xmlns:media' => 'http://search.yahoo.com/mrss/',
'@xmlns:gd' => 'http://schemas.google.com/g/2005',
'@xmlns:yt' => 'http://gdata.youtube.com/schemas/2007',
'qux' => '1',
'app:foo' => 'foo',
'yt:bar' => ['a', 'b'],
'media:baz' => [
'media:key' => 'val',
'media:key2' => 'val',
'A B' => 'bar',
'item' => [
[
'title' => 'title1',
],
[
'title' => 'title2',
],
],
'Barry' => [
'@size' => 'large',
'FooBar' => [
'Baz' => 'Ed',
'@gd:id' => 1,
],
],
],
];
}
protected function getObject()
{
$obj = new Dummy();
$obj->foo = 'foo';
$obj->bar = ['a', 'b'];
$obj->baz = ['key' => 'val', 'key2' => 'val', 'A B' => 'bar', 'item' => [['title' => 'title1'], ['title' => 'title2']], 'Barry' => ['FooBar' => ['Baz' => 'Ed', '@id' => 1]]];
$obj->qux = '1';
return $obj;
}
public function testEncodeXmlWithBoolValue()
{
$expectedXml = <<<'XML'
<?xml version="1.0"?>
<response><foo>1</foo><bar>0</bar></response>
XML;
$actualXml = $this->encoder->encode(['foo' => true, 'bar' => false], 'xml');
$this->assertEquals($expectedXml, $actualXml);
}
public function testEncodeXmlWithDomNodeValue()
{
$expectedXml = <<<'XML'
<?xml version="1.0"?>
<response><foo>bar</foo><bar>foo &amp; bar</bar></response>
XML;
$document = new \DOMDocument();
$actualXml = $this->encoder->encode(['foo' => $document->createTextNode('bar'), 'bar' => $document->createTextNode('foo & bar')], 'xml');
$this->assertEquals($expectedXml, $actualXml);
}
public function testEncodeXmlWithDateTimeObjectValue()
{
$xmlEncoder = $this->createXmlEncoderWithDateTimeNormalizer();
$actualXml = $xmlEncoder->encode(['dateTime' => new \DateTime($this->exampleDateTimeString)], 'xml');
$this->assertEquals($this->createXmlWithDateTime(), $actualXml);
}
public function testEncodeXmlWithDateTimeObjectField()
{
$xmlEncoder = $this->createXmlEncoderWithDateTimeNormalizer();
$actualXml = $xmlEncoder->encode(['foo' => ['@dateTime' => new \DateTime($this->exampleDateTimeString)]], 'xml');
$this->assertEquals($this->createXmlWithDateTimeField(), $actualXml);
}
public function testNotEncodableValueExceptionMessageForAResource()
{
$this->expectException(NotEncodableValueException::class);
$this->expectExceptionMessage('An unexpected value could not be serialized: stream resource');
(new XmlEncoder())->encode(tmpfile(), 'xml');
}
/**
* @return XmlEncoder
*/
private function createXmlEncoderWithDateTimeNormalizer()
{
$encoder = new XmlEncoder();
$serializer = new Serializer([$this->createMockDateTimeNormalizer()], ['xml' => new XmlEncoder()]);
$encoder->setSerializer($serializer);
return $encoder;
}
/**
* @return MockObject|NormalizerInterface
*/
private function createMockDateTimeNormalizer()
{
$mock = $this->getMockBuilder('\Symfony\Component\Serializer\Normalizer\CustomNormalizer')->getMock();
$mock
->expects($this->once())
->method('normalize')
->with(new \DateTime($this->exampleDateTimeString), 'xml', [])
->willReturn($this->exampleDateTimeString);
$mock
->expects($this->once())
->method('supportsNormalization')
->with(new \DateTime($this->exampleDateTimeString), 'xml')
->willReturn(true);
return $mock;
}
/**
* @return string
*/
private function createXmlWithDateTime()
{
return sprintf('<?xml version="1.0"?>
<response><dateTime>%s</dateTime></response>
', $this->exampleDateTimeString);
}
/**
* @return string
*/
private function createXmlWithDateTimeField()
{
return sprintf('<?xml version="1.0"?>
<response><foo dateTime="%s"/></response>
', $this->exampleDateTimeString);
}
}

View File

@@ -0,0 +1,71 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Serializer\Tests\Encoder;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Serializer\Encoder\YamlEncoder;
use Symfony\Component\Yaml\Dumper;
use Symfony\Component\Yaml\Parser;
use Symfony\Component\Yaml\Yaml;
/**
* @author Kévin Dunglas <dunglas@gmail.com>
*/
class YamlEncoderTest extends TestCase
{
public function testEncode()
{
$encoder = new YamlEncoder();
$this->assertEquals('foo', $encoder->encode('foo', 'yaml'));
$this->assertEquals('{ foo: 1 }', $encoder->encode(['foo' => 1], 'yaml'));
}
public function testSupportsEncoding()
{
$encoder = new YamlEncoder();
$this->assertTrue($encoder->supportsEncoding('yaml'));
$this->assertFalse($encoder->supportsEncoding('json'));
}
public function testDecode()
{
$encoder = new YamlEncoder();
$this->assertEquals('foo', $encoder->decode('foo', 'yaml'));
$this->assertEquals(['foo' => 1], $encoder->decode('{ foo: 1 }', 'yaml'));
}
public function testSupportsDecoding()
{
$encoder = new YamlEncoder();
$this->assertTrue($encoder->supportsDecoding('yaml'));
$this->assertFalse($encoder->supportsDecoding('json'));
}
public function testContext()
{
$encoder = new YamlEncoder(new Dumper(), new Parser(), ['yaml_inline' => 1, 'yaml_indent' => 4, 'yaml_flags' => Yaml::DUMP_OBJECT | Yaml::PARSE_OBJECT]);
$obj = new \stdClass();
$obj->bar = 2;
$legacyTag = " foo: !php/object:O:8:\"stdClass\":1:{s:3:\"bar\";i:2;}\n";
$spacedTag = " foo: !php/object 'O:8:\"stdClass\":1:{s:3:\"bar\";i:2;}'\n";
$this->assertThat($encoder->encode(['foo' => $obj], 'yaml'), $this->logicalOr($this->equalTo($legacyTag), $this->equalTo($spacedTag)));
$this->assertEquals(' { foo: null }', $encoder->encode(['foo' => $obj], 'yaml', ['yaml_inline' => 0, 'yaml_indent' => 2, 'yaml_flags' => 0]));
$this->assertEquals(['foo' => $obj], $encoder->decode("foo: !php/object 'O:8:\"stdClass\":1:{s:3:\"bar\";i:2;}'", 'yaml'));
$this->assertEquals(['foo' => null], $encoder->decode("foo: !php/object 'O:8:\"stdClass\":1:{s:3:\"bar\";i:2;}'", 'yaml', ['yaml_flags' => 0]));
}
}