InlineTest.php 31 KB

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