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