InlineTest.php 29 KB

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