Pull merge.
[yaffs-website] / vendor / symfony / yaml / Tests / InlineTest.php
1 <?php
2
3 /*
4  * This file is part of the Symfony package.
5  *
6  * (c) Fabien Potencier <fabien@symfony.com>
7  *
8  * For the full copyright and license information, please view the LICENSE
9  * file that was distributed with this source code.
10  */
11
12 namespace Symfony\Component\Yaml\Tests;
13
14 use PHPUnit\Framework\TestCase;
15 use Symfony\Component\Yaml\Exception\ParseException;
16 use Symfony\Component\Yaml\Inline;
17 use Symfony\Component\Yaml\Yaml;
18
19 class InlineTest extends TestCase
20 {
21     protected function setUp()
22     {
23         Inline::initialize(0, 0);
24     }
25
26     /**
27      * @dataProvider getTestsForParse
28      */
29     public function testParse($yaml, $value, $flags = 0)
30     {
31         $this->assertSame($value, Inline::parse($yaml, $flags), sprintf('::parse() converts an inline YAML to a PHP structure (%s)', $yaml));
32     }
33
34     /**
35      * @dataProvider getTestsForParseWithMapObjects
36      */
37     public function testParseWithMapObjects($yaml, $value, $flags = Yaml::PARSE_OBJECT_FOR_MAP)
38     {
39         $actual = Inline::parse($yaml, $flags);
40
41         $this->assertSame(serialize($value), serialize($actual));
42     }
43
44     /**
45      * @dataProvider getTestsForParsePhpConstants
46      */
47     public function testParsePhpConstants($yaml, $value)
48     {
49         $actual = Inline::parse($yaml, Yaml::PARSE_CONSTANT);
50
51         $this->assertSame($value, $actual);
52     }
53
54     public function getTestsForParsePhpConstants()
55     {
56         return array(
57             array('!php/const Symfony\Component\Yaml\Yaml::PARSE_CONSTANT', Yaml::PARSE_CONSTANT),
58             array('!php/const PHP_INT_MAX', PHP_INT_MAX),
59             array('[!php/const PHP_INT_MAX]', array(PHP_INT_MAX)),
60             array('{ foo: !php/const PHP_INT_MAX }', array('foo' => PHP_INT_MAX)),
61             array('!php/const NULL', null),
62         );
63     }
64
65     /**
66      * @expectedException \Symfony\Component\Yaml\Exception\ParseException
67      * @expectedExceptionMessage The constant "WRONG_CONSTANT" is not defined
68      */
69     public function testParsePhpConstantThrowsExceptionWhenUndefined()
70     {
71         Inline::parse('!php/const WRONG_CONSTANT', Yaml::PARSE_CONSTANT);
72     }
73
74     /**
75      * @expectedException \Symfony\Component\Yaml\Exception\ParseException
76      * @expectedExceptionMessageRegExp #The string "!php/const PHP_INT_MAX" could not be parsed as a constant.*#
77      */
78     public function testParsePhpConstantThrowsExceptionOnInvalidType()
79     {
80         Inline::parse('!php/const PHP_INT_MAX', Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE);
81     }
82
83     /**
84      * @group legacy
85      * @expectedDeprecation The !php/const: tag to indicate dumped PHP constants is deprecated since Symfony 3.4 and will be removed in 4.0. Use the !php/const (without the colon) tag instead on line 1.
86      * @dataProvider getTestsForParseLegacyPhpConstants
87      */
88     public function testDeprecatedConstantTag($yaml, $expectedValue)
89     {
90         $this->assertSame($expectedValue, Inline::parse($yaml, Yaml::PARSE_CONSTANT));
91     }
92
93     public function getTestsForParseLegacyPhpConstants()
94     {
95         return array(
96             array('!php/const:Symfony\Component\Yaml\Yaml::PARSE_CONSTANT', Yaml::PARSE_CONSTANT),
97             array('!php/const:PHP_INT_MAX', PHP_INT_MAX),
98             array('[!php/const:PHP_INT_MAX]', array(PHP_INT_MAX)),
99             array('{ foo: !php/const:PHP_INT_MAX }', array('foo' => PHP_INT_MAX)),
100             array('!php/const:NULL', null),
101         );
102     }
103
104     /**
105      * @group legacy
106      * @dataProvider getTestsForParseWithMapObjects
107      */
108     public function testParseWithMapObjectsPassingTrue($yaml, $value)
109     {
110         $actual = Inline::parse($yaml, false, false, true);
111
112         $this->assertSame(serialize($value), serialize($actual));
113     }
114
115     /**
116      * @dataProvider getTestsForDump
117      */
118     public function testDump($yaml, $value, $parseFlags = 0)
119     {
120         $this->assertEquals($yaml, Inline::dump($value), sprintf('::dump() converts a PHP structure to an inline YAML (%s)', $yaml));
121
122         $this->assertSame($value, Inline::parse(Inline::dump($value), $parseFlags), 'check consistency');
123     }
124
125     public function testDumpNumericValueWithLocale()
126     {
127         $locale = setlocale(LC_NUMERIC, 0);
128         if (false === $locale) {
129             $this->markTestSkipped('Your platform does not support locales.');
130         }
131
132         try {
133             $requiredLocales = array('fr_FR.UTF-8', 'fr_FR.UTF8', 'fr_FR.utf-8', 'fr_FR.utf8', 'French_France.1252');
134             if (false === setlocale(LC_NUMERIC, $requiredLocales)) {
135                 $this->markTestSkipped('Could not set any of required locales: '.implode(', ', $requiredLocales));
136             }
137
138             $this->assertEquals('1.2', Inline::dump(1.2));
139             $this->assertContains('fr', strtolower(setlocale(LC_NUMERIC, 0)));
140         } finally {
141             setlocale(LC_NUMERIC, $locale);
142         }
143     }
144
145     public function testHashStringsResemblingExponentialNumericsShouldNotBeChangedToINF()
146     {
147         $value = '686e444';
148
149         $this->assertSame($value, Inline::parse(Inline::dump($value)));
150     }
151
152     /**
153      * @expectedException        \Symfony\Component\Yaml\Exception\ParseException
154      * @expectedExceptionMessage Found unknown escape character "\V".
155      */
156     public function testParseScalarWithNonEscapedBlackslashShouldThrowException()
157     {
158         Inline::parse('"Foo\Var"');
159     }
160
161     /**
162      * @expectedException \Symfony\Component\Yaml\Exception\ParseException
163      */
164     public function testParseScalarWithNonEscapedBlackslashAtTheEndShouldThrowException()
165     {
166         Inline::parse('"Foo\\"');
167     }
168
169     /**
170      * @expectedException \Symfony\Component\Yaml\Exception\ParseException
171      */
172     public function testParseScalarWithIncorrectlyQuotedStringShouldThrowException()
173     {
174         $value = "'don't do somthin' like that'";
175         Inline::parse($value);
176     }
177
178     /**
179      * @expectedException \Symfony\Component\Yaml\Exception\ParseException
180      */
181     public function testParseScalarWithIncorrectlyDoubleQuotedStringShouldThrowException()
182     {
183         $value = '"don"t do somthin" like that"';
184         Inline::parse($value);
185     }
186
187     /**
188      * @expectedException \Symfony\Component\Yaml\Exception\ParseException
189      */
190     public function testParseInvalidMappingKeyShouldThrowException()
191     {
192         $value = '{ "foo " bar": "bar" }';
193         Inline::parse($value);
194     }
195
196     /**
197      * @group legacy
198      * @expectedDeprecation Using a colon after an unquoted mapping key that is not followed by an indication character (i.e. " ", ",", "[", "]", "{", "}") is deprecated since Symfony 3.2 and will throw a ParseException in 4.0 on line 1.
199      * throws \Symfony\Component\Yaml\Exception\ParseException in 4.0
200      */
201     public function testParseMappingKeyWithColonNotFollowedBySpace()
202     {
203         Inline::parse('{1:""}');
204     }
205
206     /**
207      * @expectedException \Symfony\Component\Yaml\Exception\ParseException
208      */
209     public function testParseInvalidMappingShouldThrowException()
210     {
211         Inline::parse('[foo] bar');
212     }
213
214     /**
215      * @expectedException \Symfony\Component\Yaml\Exception\ParseException
216      */
217     public function testParseInvalidSequenceShouldThrowException()
218     {
219         Inline::parse('{ foo: bar } bar');
220     }
221
222     public function testParseScalarWithCorrectlyQuotedStringShouldReturnString()
223     {
224         $value = "'don''t do somthin'' like that'";
225         $expect = "don't do somthin' like that";
226
227         $this->assertSame($expect, Inline::parseScalar($value));
228     }
229
230     /**
231      * @dataProvider getDataForParseReferences
232      */
233     public function testParseReferences($yaml, $expected)
234     {
235         $this->assertSame($expected, Inline::parse($yaml, 0, array('var' => 'var-value')));
236     }
237
238     /**
239      * @group legacy
240      * @dataProvider getDataForParseReferences
241      */
242     public function testParseReferencesAsFifthArgument($yaml, $expected)
243     {
244         $this->assertSame($expected, Inline::parse($yaml, false, false, false, array('var' => 'var-value')));
245     }
246
247     public function getDataForParseReferences()
248     {
249         return array(
250             'scalar' => array('*var', 'var-value'),
251             'list' => array('[ *var ]', array('var-value')),
252             'list-in-list' => array('[[ *var ]]', array(array('var-value'))),
253             'map-in-list' => array('[ { key: *var } ]', array(array('key' => 'var-value'))),
254             'embedded-mapping-in-list' => array('[ key: *var ]', array(array('key' => 'var-value'))),
255             'map' => array('{ key: *var }', array('key' => 'var-value')),
256             'list-in-map' => array('{ key: [*var] }', array('key' => array('var-value'))),
257             'map-in-map' => array('{ foo: { bar: *var } }', array('foo' => array('bar' => 'var-value'))),
258         );
259     }
260
261     public function testParseMapReferenceInSequence()
262     {
263         $foo = array(
264             'a' => 'Steve',
265             'b' => 'Clark',
266             'c' => 'Brian',
267         );
268         $this->assertSame(array($foo), Inline::parse('[*foo]', 0, array('foo' => $foo)));
269     }
270
271     /**
272      * @group legacy
273      */
274     public function testParseMapReferenceInSequenceAsFifthArgument()
275     {
276         $foo = array(
277             'a' => 'Steve',
278             'b' => 'Clark',
279             'c' => 'Brian',
280         );
281         $this->assertSame(array($foo), Inline::parse('[*foo]', false, false, false, array('foo' => $foo)));
282     }
283
284     /**
285      * @expectedException \Symfony\Component\Yaml\Exception\ParseException
286      * @expectedExceptionMessage A reference must contain at least one character at line 1.
287      */
288     public function testParseUnquotedAsterisk()
289     {
290         Inline::parse('{ foo: * }');
291     }
292
293     /**
294      * @expectedException \Symfony\Component\Yaml\Exception\ParseException
295      * @expectedExceptionMessage A reference must contain at least one character at line 1.
296      */
297     public function testParseUnquotedAsteriskFollowedByAComment()
298     {
299         Inline::parse('{ foo: * #foo }');
300     }
301
302     /**
303      * @dataProvider getReservedIndicators
304      */
305     public function testParseUnquotedScalarStartingWithReservedIndicator($indicator)
306     {
307         if (method_exists($this, 'expectExceptionMessage')) {
308             $this->expectException(ParseException::class);
309             $this->expectExceptionMessage(sprintf('cannot start a plain scalar; you need to quote the scalar at line 1 (near "%sfoo ").', $indicator));
310         } else {
311             $this->setExpectedException(ParseException::class, sprintf('cannot start a plain scalar; you need to quote the scalar at line 1 (near "%sfoo ").', $indicator));
312         }
313
314         Inline::parse(sprintf('{ foo: %sfoo }', $indicator));
315     }
316
317     public function getReservedIndicators()
318     {
319         return array(array('@'), array('`'));
320     }
321
322     /**
323      * @dataProvider getScalarIndicators
324      */
325     public function testParseUnquotedScalarStartingWithScalarIndicator($indicator)
326     {
327         if (method_exists($this, 'expectExceptionMessage')) {
328             $this->expectException(ParseException::class);
329             $this->expectExceptionMessage(sprintf('cannot start a plain scalar; you need to quote the scalar at line 1 (near "%sfoo ").', $indicator));
330         } else {
331             $this->setExpectedException(ParseException::class, sprintf('cannot start a plain scalar; you need to quote the scalar at line 1 (near "%sfoo ").', $indicator));
332         }
333
334         Inline::parse(sprintf('{ foo: %sfoo }', $indicator));
335     }
336
337     public function getScalarIndicators()
338     {
339         return array(array('|'), array('>'));
340     }
341
342     /**
343      * @group legacy
344      * @expectedDeprecation Not quoting the scalar "%bar " starting with the "%" indicator character is deprecated since Symfony 3.1 and will throw a ParseException in 4.0 on line 1.
345      * throws \Symfony\Component\Yaml\Exception\ParseException in 4.0
346      */
347     public function testParseUnquotedScalarStartingWithPercentCharacter()
348     {
349         Inline::parse('{ foo: %bar }');
350     }
351
352     /**
353      * @dataProvider getDataForIsHash
354      */
355     public function testIsHash($array, $expected)
356     {
357         $this->assertSame($expected, Inline::isHash($array));
358     }
359
360     public function getDataForIsHash()
361     {
362         return array(
363             array(array(), false),
364             array(array(1, 2, 3), false),
365             array(array(2 => 1, 1 => 2, 0 => 3), true),
366             array(array('foo' => 1, 'bar' => 2), true),
367         );
368     }
369
370     public function getTestsForParse()
371     {
372         return array(
373             array('', ''),
374             array('null', null),
375             array('false', false),
376             array('true', true),
377             array('12', 12),
378             array('-12', -12),
379             array('1_2', 12),
380             array('_12', '_12'),
381             array('12_', 12),
382             array('"quoted string"', 'quoted string'),
383             array("'quoted string'", 'quoted string'),
384             array('12.30e+02', 12.30e+02),
385             array('123.45_67', 123.4567),
386             array('0x4D2', 0x4D2),
387             array('0x_4_D_2_', 0x4D2),
388             array('02333', 02333),
389             array('0_2_3_3_3', 02333),
390             array('.Inf', -log(0)),
391             array('-.Inf', log(0)),
392             array("'686e444'", '686e444'),
393             array('686e444', 646e444),
394             array('123456789123456789123456789123456789', '123456789123456789123456789123456789'),
395             array('"foo\r\nbar"', "foo\r\nbar"),
396             array("'foo#bar'", 'foo#bar'),
397             array("'foo # bar'", 'foo # bar'),
398             array("'#cfcfcf'", '#cfcfcf'),
399             array('::form_base.html.twig', '::form_base.html.twig'),
400
401             // Pre-YAML-1.2 booleans
402             array("'y'", 'y'),
403             array("'n'", 'n'),
404             array("'yes'", 'yes'),
405             array("'no'", 'no'),
406             array("'on'", 'on'),
407             array("'off'", 'off'),
408
409             array('2007-10-30', gmmktime(0, 0, 0, 10, 30, 2007)),
410             array('2007-10-30T02:59:43Z', gmmktime(2, 59, 43, 10, 30, 2007)),
411             array('2007-10-30 02:59:43 Z', gmmktime(2, 59, 43, 10, 30, 2007)),
412             array('1960-10-30 02:59:43 Z', gmmktime(2, 59, 43, 10, 30, 1960)),
413             array('1730-10-30T02:59:43Z', gmmktime(2, 59, 43, 10, 30, 1730)),
414
415             array('"a \\"string\\" with \'quoted strings inside\'"', 'a "string" with \'quoted strings inside\''),
416             array("'a \"string\" with ''quoted strings inside'''", 'a "string" with \'quoted strings inside\''),
417
418             // sequences
419             // urls are no key value mapping. see #3609. Valid yaml "key: value" mappings require a space after the colon
420             array('[foo, http://urls.are/no/mappings, false, null, 12]', array('foo', 'http://urls.are/no/mappings', false, null, 12)),
421             array('[  foo  ,   bar , false  ,  null     ,  12  ]', array('foo', 'bar', false, null, 12)),
422             array('[\'foo,bar\', \'foo bar\']', array('foo,bar', 'foo bar')),
423
424             // mappings
425             array('{foo: bar,bar: foo,"false": false, "null": null,integer: 12}', array('foo' => 'bar', 'bar' => 'foo', 'false' => false, 'null' => null, 'integer' => 12)),
426             array('{ foo  : bar, bar : foo, "false"  :   false,  "null"  :   null,  integer :  12  }', array('foo' => 'bar', 'bar' => 'foo', 'false' => false, 'null' => null, 'integer' => 12)),
427             array('{foo: \'bar\', bar: \'foo: bar\'}', array('foo' => 'bar', 'bar' => 'foo: bar')),
428             array('{\'foo\': \'bar\', "bar": \'foo: bar\'}', array('foo' => 'bar', 'bar' => 'foo: bar')),
429             array('{\'foo\'\'\': \'bar\', "bar\"": \'foo: bar\'}', array('foo\'' => 'bar', 'bar"' => 'foo: bar')),
430             array('{\'foo: \': \'bar\', "bar: ": \'foo: bar\'}', array('foo: ' => 'bar', 'bar: ' => 'foo: bar')),
431             array('{"foo:bar": "baz"}', array('foo:bar' => 'baz')),
432             array('{"foo":"bar"}', array('foo' => 'bar')),
433
434             // nested sequences and mappings
435             array('[foo, [bar, foo]]', array('foo', array('bar', 'foo'))),
436             array('[foo, {bar: foo}]', array('foo', array('bar' => 'foo'))),
437             array('{ foo: {bar: foo} }', array('foo' => array('bar' => 'foo'))),
438             array('{ foo: [bar, foo] }', array('foo' => array('bar', 'foo'))),
439             array('{ foo:{bar: foo} }', array('foo' => array('bar' => 'foo'))),
440             array('{ foo:[bar, foo] }', array('foo' => array('bar', 'foo'))),
441
442             array('[  foo, [  bar, foo  ]  ]', array('foo', array('bar', 'foo'))),
443
444             array('[{ foo: {bar: foo} }]', array(array('foo' => array('bar' => 'foo')))),
445
446             array('[foo, [bar, [foo, [bar, foo]], foo]]', array('foo', array('bar', array('foo', array('bar', 'foo')), 'foo'))),
447
448             array('[foo, {bar: foo, foo: [foo, {bar: foo}]}, [foo, {bar: foo}]]', array('foo', array('bar' => 'foo', 'foo' => array('foo', array('bar' => 'foo'))), array('foo', array('bar' => 'foo')))),
449
450             array('[foo, bar: { foo: bar }]', array('foo', '1' => array('bar' => array('foo' => 'bar')))),
451             array('[foo, \'@foo.baz\', { \'%foo%\': \'foo is %foo%\', bar: \'%foo%\' }, true, \'@service_container\']', array('foo', '@foo.baz', array('%foo%' => 'foo is %foo%', 'bar' => '%foo%'), true, '@service_container')),
452         );
453     }
454
455     public function getTestsForParseWithMapObjects()
456     {
457         return array(
458             array('', ''),
459             array('null', null),
460             array('false', false),
461             array('true', true),
462             array('12', 12),
463             array('-12', -12),
464             array('"quoted string"', 'quoted string'),
465             array("'quoted string'", 'quoted string'),
466             array('12.30e+02', 12.30e+02),
467             array('0x4D2', 0x4D2),
468             array('02333', 02333),
469             array('.Inf', -log(0)),
470             array('-.Inf', log(0)),
471             array("'686e444'", '686e444'),
472             array('686e444', 646e444),
473             array('123456789123456789123456789123456789', '123456789123456789123456789123456789'),
474             array('"foo\r\nbar"', "foo\r\nbar"),
475             array("'foo#bar'", 'foo#bar'),
476             array("'foo # bar'", 'foo # bar'),
477             array("'#cfcfcf'", '#cfcfcf'),
478             array('::form_base.html.twig', '::form_base.html.twig'),
479
480             array('2007-10-30', gmmktime(0, 0, 0, 10, 30, 2007)),
481             array('2007-10-30T02:59:43Z', gmmktime(2, 59, 43, 10, 30, 2007)),
482             array('2007-10-30 02:59:43 Z', gmmktime(2, 59, 43, 10, 30, 2007)),
483             array('1960-10-30 02:59:43 Z', gmmktime(2, 59, 43, 10, 30, 1960)),
484             array('1730-10-30T02:59:43Z', gmmktime(2, 59, 43, 10, 30, 1730)),
485
486             array('"a \\"string\\" with \'quoted strings inside\'"', 'a "string" with \'quoted strings inside\''),
487             array("'a \"string\" with ''quoted strings inside'''", 'a "string" with \'quoted strings inside\''),
488
489             // sequences
490             // urls are no key value mapping. see #3609. Valid yaml "key: value" mappings require a space after the colon
491             array('[foo, http://urls.are/no/mappings, false, null, 12]', array('foo', 'http://urls.are/no/mappings', false, null, 12)),
492             array('[  foo  ,   bar , false  ,  null     ,  12  ]', array('foo', 'bar', false, null, 12)),
493             array('[\'foo,bar\', \'foo bar\']', array('foo,bar', 'foo bar')),
494
495             // mappings
496             array('{foo: bar,bar: foo,"false": false,"null": null,integer: 12}', (object) array('foo' => 'bar', 'bar' => 'foo', 'false' => false, 'null' => null, 'integer' => 12), Yaml::PARSE_OBJECT_FOR_MAP),
497             array('{ foo  : bar, bar : foo,  "false"  :   false,  "null"  :   null,  integer :  12  }', (object) array('foo' => 'bar', 'bar' => 'foo', 'false' => false, 'null' => null, 'integer' => 12), Yaml::PARSE_OBJECT_FOR_MAP),
498             array('{foo: \'bar\', bar: \'foo: bar\'}', (object) array('foo' => 'bar', 'bar' => 'foo: bar')),
499             array('{\'foo\': \'bar\', "bar": \'foo: bar\'}', (object) array('foo' => 'bar', 'bar' => 'foo: bar')),
500             array('{\'foo\'\'\': \'bar\', "bar\"": \'foo: bar\'}', (object) array('foo\'' => 'bar', 'bar"' => 'foo: bar')),
501             array('{\'foo: \': \'bar\', "bar: ": \'foo: bar\'}', (object) array('foo: ' => 'bar', 'bar: ' => 'foo: bar')),
502             array('{"foo:bar": "baz"}', (object) array('foo:bar' => 'baz')),
503             array('{"foo":"bar"}', (object) array('foo' => 'bar')),
504
505             // nested sequences and mappings
506             array('[foo, [bar, foo]]', array('foo', array('bar', 'foo'))),
507             array('[foo, {bar: foo}]', array('foo', (object) array('bar' => 'foo'))),
508             array('{ foo: {bar: foo} }', (object) array('foo' => (object) array('bar' => 'foo'))),
509             array('{ foo: [bar, foo] }', (object) array('foo' => array('bar', 'foo'))),
510
511             array('[  foo, [  bar, foo  ]  ]', array('foo', array('bar', 'foo'))),
512
513             array('[{ foo: {bar: foo} }]', array((object) array('foo' => (object) array('bar' => 'foo')))),
514
515             array('[foo, [bar, [foo, [bar, foo]], foo]]', array('foo', array('bar', array('foo', array('bar', 'foo')), 'foo'))),
516
517             array('[foo, {bar: foo, foo: [foo, {bar: foo}]}, [foo, {bar: foo}]]', array('foo', (object) array('bar' => 'foo', 'foo' => array('foo', (object) array('bar' => 'foo'))), array('foo', (object) array('bar' => 'foo')))),
518
519             array('[foo, bar: { foo: bar }]', array('foo', '1' => (object) array('bar' => (object) array('foo' => 'bar')))),
520             array('[foo, \'@foo.baz\', { \'%foo%\': \'foo is %foo%\', bar: \'%foo%\' }, true, \'@service_container\']', array('foo', '@foo.baz', (object) array('%foo%' => 'foo is %foo%', 'bar' => '%foo%'), true, '@service_container')),
521
522             array('{}', new \stdClass()),
523             array('{ foo  : bar, bar : {}  }', (object) array('foo' => 'bar', 'bar' => new \stdClass())),
524             array('{ foo  : [], bar : {}  }', (object) array('foo' => array(), 'bar' => new \stdClass())),
525             array('{foo: \'bar\', bar: {} }', (object) array('foo' => 'bar', 'bar' => new \stdClass())),
526             array('{\'foo\': \'bar\', "bar": {}}', (object) array('foo' => 'bar', 'bar' => new \stdClass())),
527             array('{\'foo\': \'bar\', "bar": \'{}\'}', (object) array('foo' => 'bar', 'bar' => '{}')),
528
529             array('[foo, [{}, {}]]', array('foo', array(new \stdClass(), new \stdClass()))),
530             array('[foo, [[], {}]]', array('foo', array(array(), new \stdClass()))),
531             array('[foo, [[{}, {}], {}]]', array('foo', array(array(new \stdClass(), new \stdClass()), new \stdClass()))),
532             array('[foo, {bar: {}}]', array('foo', '1' => (object) array('bar' => new \stdClass()))),
533         );
534     }
535
536     public function getTestsForDump()
537     {
538         return array(
539             array('null', null),
540             array('false', false),
541             array('true', true),
542             array('12', 12),
543             array("'1_2'", '1_2'),
544             array('_12', '_12'),
545             array("'12_'", '12_'),
546             array("'quoted string'", 'quoted string'),
547             array('!!float 1230', 12.30e+02),
548             array('1234', 0x4D2),
549             array('1243', 02333),
550             array("'0x_4_D_2_'", '0x_4_D_2_'),
551             array("'0_2_3_3_3'", '0_2_3_3_3'),
552             array('.Inf', -log(0)),
553             array('-.Inf', log(0)),
554             array("'686e444'", '686e444'),
555             array('"foo\r\nbar"', "foo\r\nbar"),
556             array("'foo#bar'", 'foo#bar'),
557             array("'foo # bar'", 'foo # bar'),
558             array("'#cfcfcf'", '#cfcfcf'),
559
560             array("'a \"string\" with ''quoted strings inside'''", 'a "string" with \'quoted strings inside\''),
561
562             array("'-dash'", '-dash'),
563             array("'-'", '-'),
564
565             // Pre-YAML-1.2 booleans
566             array("'y'", 'y'),
567             array("'n'", 'n'),
568             array("'yes'", 'yes'),
569             array("'no'", 'no'),
570             array("'on'", 'on'),
571             array("'off'", 'off'),
572
573             // sequences
574             array('[foo, bar, false, null, 12]', array('foo', 'bar', false, null, 12)),
575             array('[\'foo,bar\', \'foo bar\']', array('foo,bar', 'foo bar')),
576
577             // mappings
578             array('{ foo: bar, bar: foo, \'false\': false, \'null\': null, integer: 12 }', array('foo' => 'bar', 'bar' => 'foo', 'false' => false, 'null' => null, 'integer' => 12)),
579             array('{ foo: bar, bar: \'foo: bar\' }', array('foo' => 'bar', 'bar' => 'foo: bar')),
580
581             // nested sequences and mappings
582             array('[foo, [bar, foo]]', array('foo', array('bar', 'foo'))),
583
584             array('[foo, [bar, [foo, [bar, foo]], foo]]', array('foo', array('bar', array('foo', array('bar', 'foo')), 'foo'))),
585
586             array('{ foo: { bar: foo } }', array('foo' => array('bar' => 'foo'))),
587
588             array('[foo, { bar: foo }]', array('foo', array('bar' => 'foo'))),
589
590             array('[foo, { bar: foo, foo: [foo, { bar: foo }] }, [foo, { bar: foo }]]', array('foo', array('bar' => 'foo', 'foo' => array('foo', array('bar' => 'foo'))), array('foo', array('bar' => 'foo')))),
591
592             array('[foo, \'@foo.baz\', { \'%foo%\': \'foo is %foo%\', bar: \'%foo%\' }, true, \'@service_container\']', array('foo', '@foo.baz', array('%foo%' => 'foo is %foo%', 'bar' => '%foo%'), true, '@service_container')),
593
594             array('{ foo: { bar: { 1: 2, baz: 3 } } }', array('foo' => array('bar' => array(1 => 2, 'baz' => 3)))),
595         );
596     }
597
598     /**
599      * @dataProvider getTimestampTests
600      */
601     public function testParseTimestampAsUnixTimestampByDefault($yaml, $year, $month, $day, $hour, $minute, $second)
602     {
603         $this->assertSame(gmmktime($hour, $minute, $second, $month, $day, $year), Inline::parse($yaml));
604     }
605
606     /**
607      * @dataProvider getTimestampTests
608      */
609     public function testParseTimestampAsDateTimeObject($yaml, $year, $month, $day, $hour, $minute, $second, $timezone)
610     {
611         $expected = new \DateTime($yaml);
612         $expected->setTimeZone(new \DateTimeZone('UTC'));
613         $expected->setDate($year, $month, $day);
614
615         if (\PHP_VERSION_ID >= 70100) {
616             $expected->setTime($hour, $minute, $second, 1000000 * ($second - (int) $second));
617         } else {
618             $expected->setTime($hour, $minute, $second);
619         }
620
621         $date = Inline::parse($yaml, Yaml::PARSE_DATETIME);
622         $this->assertEquals($expected, $date);
623         $this->assertSame($timezone, $date->format('O'));
624     }
625
626     public function getTimestampTests()
627     {
628         return array(
629             'canonical' => array('2001-12-15T02:59:43.1Z', 2001, 12, 15, 2, 59, 43.1, '+0000'),
630             'ISO-8601' => array('2001-12-15t21:59:43.10-05:00', 2001, 12, 16, 2, 59, 43.1, '-0500'),
631             'spaced' => array('2001-12-15 21:59:43.10 -5', 2001, 12, 16, 2, 59, 43.1, '-0500'),
632             'date' => array('2001-12-15', 2001, 12, 15, 0, 0, 0, '+0000'),
633         );
634     }
635
636     /**
637      * @dataProvider getTimestampTests
638      */
639     public function testParseNestedTimestampListAsDateTimeObject($yaml, $year, $month, $day, $hour, $minute, $second)
640     {
641         $expected = new \DateTime($yaml);
642         $expected->setTimeZone(new \DateTimeZone('UTC'));
643         $expected->setDate($year, $month, $day);
644         if (\PHP_VERSION_ID >= 70100) {
645             $expected->setTime($hour, $minute, $second, 1000000 * ($second - (int) $second));
646         } else {
647             $expected->setTime($hour, $minute, $second);
648         }
649
650         $expectedNested = array('nested' => array($expected));
651         $yamlNested = "{nested: [$yaml]}";
652
653         $this->assertEquals($expectedNested, Inline::parse($yamlNested, Yaml::PARSE_DATETIME));
654     }
655
656     /**
657      * @dataProvider getDateTimeDumpTests
658      */
659     public function testDumpDateTime($dateTime, $expected)
660     {
661         $this->assertSame($expected, Inline::dump($dateTime));
662     }
663
664     public function getDateTimeDumpTests()
665     {
666         $tests = array();
667
668         $dateTime = new \DateTime('2001-12-15 21:59:43', new \DateTimeZone('UTC'));
669         $tests['date-time-utc'] = array($dateTime, '2001-12-15T21:59:43+00:00');
670
671         $dateTime = new \DateTimeImmutable('2001-07-15 21:59:43', new \DateTimeZone('Europe/Berlin'));
672         $tests['immutable-date-time-europe-berlin'] = array($dateTime, '2001-07-15T21:59:43+02:00');
673
674         return $tests;
675     }
676
677     /**
678      * @dataProvider getBinaryData
679      */
680     public function testParseBinaryData($data)
681     {
682         $this->assertSame('Hello world', Inline::parse($data));
683     }
684
685     public function getBinaryData()
686     {
687         return array(
688             'enclosed with double quotes' => array('!!binary "SGVsbG8gd29ybGQ="'),
689             'enclosed with single quotes' => array("!!binary 'SGVsbG8gd29ybGQ='"),
690             'containing spaces' => array('!!binary  "SGVs bG8gd 29ybGQ="'),
691         );
692     }
693
694     /**
695      * @dataProvider getInvalidBinaryData
696      * @expectedException \Symfony\Component\Yaml\Exception\ParseException
697      */
698     public function testParseInvalidBinaryData($data, $expectedMessage)
699     {
700         if (method_exists($this, 'expectException')) {
701             $this->expectExceptionMessageRegExp($expectedMessage);
702         } else {
703             $this->setExpectedExceptionRegExp(ParseException::class, $expectedMessage);
704         }
705
706         Inline::parse($data);
707     }
708
709     public function getInvalidBinaryData()
710     {
711         return array(
712             'length not a multiple of four' => array('!!binary "SGVsbG8d29ybGQ="', '/The normalized base64 encoded data \(data without whitespace characters\) length must be a multiple of four \(\d+ bytes given\)/'),
713             'invalid characters' => array('!!binary "SGVsbG8#d29ybGQ="', '/The base64 encoded data \(.*\) contains invalid characters/'),
714             'too many equals characters' => array('!!binary "SGVsbG8gd29yb==="', '/The base64 encoded data \(.*\) contains invalid characters/'),
715             'misplaced equals character' => array('!!binary "SGVsbG8gd29ybG=Q"', '/The base64 encoded data \(.*\) contains invalid characters/'),
716         );
717     }
718
719     /**
720      * @expectedException \Symfony\Component\Yaml\Exception\ParseException
721      * @expectedExceptionMessage Malformed inline YAML string: {this, is not, supported} at line 1.
722      */
723     public function testNotSupportedMissingValue()
724     {
725         Inline::parse('{this, is not, supported}');
726     }
727
728     public function testVeryLongQuotedStrings()
729     {
730         $longStringWithQuotes = str_repeat("x\r\n\\\"x\"x", 1000);
731
732         $yamlString = Inline::dump(array('longStringWithQuotes' => $longStringWithQuotes));
733         $arrayFromYaml = Inline::parse($yamlString);
734
735         $this->assertEquals($longStringWithQuotes, $arrayFromYaml['longStringWithQuotes']);
736     }
737
738     /**
739      * @group legacy
740      * @expectedDeprecation Omitting the key of a mapping is deprecated and will throw a ParseException in 4.0 on line 1.
741      */
742     public function testOmittedMappingKeyIsParsedAsColon()
743     {
744         $this->assertSame(array(':' => 'foo'), Inline::parse('{: foo}'));
745     }
746
747     /**
748      * @dataProvider getTestsForNullValues
749      */
750     public function testParseMissingMappingValueAsNull($yaml, $expected)
751     {
752         $this->assertSame($expected, Inline::parse($yaml));
753     }
754
755     public function getTestsForNullValues()
756     {
757         return array(
758             'null before closing curly brace' => array('{foo:}', array('foo' => null)),
759             'null before comma' => array('{foo:, bar: baz}', array('foo' => null, 'bar' => 'baz')),
760         );
761     }
762
763     public function testTheEmptyStringIsAValidMappingKey()
764     {
765         $this->assertSame(array('' => 'foo'), Inline::parse('{ "": foo }'));
766     }
767
768     /**
769      * @group legacy
770      * @expectedDeprecation Implicit casting of incompatible mapping keys to strings is deprecated since Symfony 3.3 and will throw \Symfony\Component\Yaml\Exception\ParseException in 4.0. Quote your evaluable mapping keys instead on line 1.
771      * @dataProvider getNotPhpCompatibleMappingKeyData
772      */
773     public function testImplicitStringCastingOfMappingKeysIsDeprecated($yaml, $expected)
774     {
775         $this->assertSame($expected, Inline::parse($yaml));
776     }
777
778     /**
779      * @group legacy
780      * @expectedDeprecation Using the Yaml::PARSE_KEYS_AS_STRINGS flag is deprecated since Symfony 3.4 as it will be removed in 4.0. Quote your keys when they are evaluable instead.
781      * @expectedDeprecation Implicit casting of incompatible mapping keys to strings is deprecated since Symfony 3.3 and will throw \Symfony\Component\Yaml\Exception\ParseException in 4.0. Quote your evaluable mapping keys instead on line 1.
782      * @dataProvider getNotPhpCompatibleMappingKeyData
783      */
784     public function testExplicitStringCastingOfMappingKeys($yaml, $expected)
785     {
786         $this->assertSame($expected, Yaml::parse($yaml, Yaml::PARSE_KEYS_AS_STRINGS));
787     }
788
789     public function getNotPhpCompatibleMappingKeyData()
790     {
791         return array(
792             'boolean-true' => array('{true: "foo"}', array('true' => 'foo')),
793             'boolean-false' => array('{false: "foo"}', array('false' => 'foo')),
794             'null' => array('{null: "foo"}', array('null' => 'foo')),
795             'float' => array('{0.25: "foo"}', array('0.25' => 'foo')),
796         );
797     }
798
799     /**
800      * @group legacy
801      * @expectedDeprecation Support for the !str tag is deprecated since Symfony 3.4. Use the !!str tag instead on line 1.
802      */
803     public function testDeprecatedStrTag()
804     {
805         $this->assertSame(array('foo' => 'bar'), Inline::parse('{ foo: !str bar }'));
806     }
807
808     /**
809      * @expectedException \Symfony\Component\Yaml\Exception\ParseException
810      * @expectedExceptionMessage Unexpected end of line, expected one of ",}" at line 1 (near "{abc: 'def'").
811      */
812     public function testUnfinishedInlineMap()
813     {
814         Inline::parse("{abc: 'def'");
815     }
816 }