InlineTest.php 33 KB

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