InlineTest.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760
  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 array(
  48. array('!php/const Symfony\Component\Yaml\Yaml::PARSE_CONSTANT', Yaml::PARSE_CONSTANT),
  49. array('!php/const PHP_INT_MAX', PHP_INT_MAX),
  50. array('[!php/const PHP_INT_MAX]', array(PHP_INT_MAX)),
  51. array('{ foo: !php/const PHP_INT_MAX }', array('foo' => PHP_INT_MAX)),
  52. array('!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 = array('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, array('var' => 'var-value')));
  174. }
  175. public function getDataForParseReferences()
  176. {
  177. return array(
  178. 'scalar' => array('*var', 'var-value'),
  179. 'list' => array('[ *var ]', array('var-value')),
  180. 'list-in-list' => array('[[ *var ]]', array(array('var-value'))),
  181. 'map-in-list' => array('[ { key: *var } ]', array(array('key' => 'var-value'))),
  182. 'embedded-mapping-in-list' => array('[ key: *var ]', array(array('key' => 'var-value'))),
  183. 'map' => array('{ key: *var }', array('key' => 'var-value')),
  184. 'list-in-map' => array('{ key: [*var] }', array('key' => array('var-value'))),
  185. 'map-in-map' => array('{ foo: { bar: *var } }', array('foo' => array('bar' => 'var-value'))),
  186. );
  187. }
  188. public function testParseMapReferenceInSequence()
  189. {
  190. $foo = array(
  191. 'a' => 'Steve',
  192. 'b' => 'Clark',
  193. 'c' => 'Brian',
  194. );
  195. $this->assertSame(array($foo), Inline::parse('[*foo]', 0, array('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 array(array('@'), array('`'));
  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 array(array('|'), array('>'), array('%'));
  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 array(
  257. array(array(), false),
  258. array(array(1, 2, 3), false),
  259. array(array(2 => 1, 1 => 2, 0 => 3), true),
  260. array(array('foo' => 1, 'bar' => 2), true),
  261. );
  262. }
  263. public function getTestsForParse()
  264. {
  265. return array(
  266. array('', ''),
  267. array('null', null),
  268. array('false', false),
  269. array('true', true),
  270. array('12', 12),
  271. array('-12', -12),
  272. array('1_2', 12),
  273. array('_12', '_12'),
  274. array('12_', 12),
  275. array('"quoted string"', 'quoted string'),
  276. array("'quoted string'", 'quoted string'),
  277. array('12.30e+02', 12.30e+02),
  278. array('123.45_67', 123.4567),
  279. array('0x4D2', 0x4D2),
  280. array('0x_4_D_2_', 0x4D2),
  281. array('02333', 02333),
  282. array('0_2_3_3_3', 02333),
  283. array('.Inf', -log(0)),
  284. array('-.Inf', log(0)),
  285. array("'686e444'", '686e444'),
  286. array('686e444', 646e444),
  287. array('123456789123456789123456789123456789', '123456789123456789123456789123456789'),
  288. array('"foo\r\nbar"', "foo\r\nbar"),
  289. array("'foo#bar'", 'foo#bar'),
  290. array("'foo # bar'", 'foo # bar'),
  291. array("'#cfcfcf'", '#cfcfcf'),
  292. array('::form_base.html.twig', '::form_base.html.twig'),
  293. // Pre-YAML-1.2 booleans
  294. array("'y'", 'y'),
  295. array("'n'", 'n'),
  296. array("'yes'", 'yes'),
  297. array("'no'", 'no'),
  298. array("'on'", 'on'),
  299. array("'off'", 'off'),
  300. array('2007-10-30', gmmktime(0, 0, 0, 10, 30, 2007)),
  301. array('2007-10-30T02:59:43Z', gmmktime(2, 59, 43, 10, 30, 2007)),
  302. array('2007-10-30 02:59:43 Z', gmmktime(2, 59, 43, 10, 30, 2007)),
  303. array('1960-10-30 02:59:43 Z', gmmktime(2, 59, 43, 10, 30, 1960)),
  304. array('1730-10-30T02:59:43Z', gmmktime(2, 59, 43, 10, 30, 1730)),
  305. array('"a \\"string\\" with \'quoted strings inside\'"', 'a "string" with \'quoted strings inside\''),
  306. array("'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. array('[foo, http://urls.are/no/mappings, false, null, 12]', array('foo', 'http://urls.are/no/mappings', false, null, 12)),
  310. array('[ foo , bar , false , null , 12 ]', array('foo', 'bar', false, null, 12)),
  311. array('[\'foo,bar\', \'foo bar\']', array('foo,bar', 'foo bar')),
  312. // mappings
  313. array('{foo: bar,bar: foo,"false": false, "null": null,integer: 12}', array('foo' => 'bar', 'bar' => 'foo', 'false' => false, 'null' => null, 'integer' => 12)),
  314. array('{ foo : bar, bar : foo, "false" : false, "null" : null, integer : 12 }', array('foo' => 'bar', 'bar' => 'foo', 'false' => false, 'null' => null, 'integer' => 12)),
  315. array('{foo: \'bar\', bar: \'foo: bar\'}', array('foo' => 'bar', 'bar' => 'foo: bar')),
  316. array('{\'foo\': \'bar\', "bar": \'foo: bar\'}', array('foo' => 'bar', 'bar' => 'foo: bar')),
  317. array('{\'foo\'\'\': \'bar\', "bar\"": \'foo: bar\'}', array('foo\'' => 'bar', 'bar"' => 'foo: bar')),
  318. array('{\'foo: \': \'bar\', "bar: ": \'foo: bar\'}', array('foo: ' => 'bar', 'bar: ' => 'foo: bar')),
  319. array('{"foo:bar": "baz"}', array('foo:bar' => 'baz')),
  320. array('{"foo":"bar"}', array('foo' => 'bar')),
  321. // nested sequences and mappings
  322. array('[foo, [bar, foo]]', array('foo', array('bar', 'foo'))),
  323. array('[foo, {bar: foo}]', array('foo', array('bar' => 'foo'))),
  324. array('{ foo: {bar: foo} }', array('foo' => array('bar' => 'foo'))),
  325. array('{ foo: [bar, foo] }', array('foo' => array('bar', 'foo'))),
  326. array('{ foo:{bar: foo} }', array('foo' => array('bar' => 'foo'))),
  327. array('{ foo:[bar, foo] }', array('foo' => array('bar', 'foo'))),
  328. array('[ foo, [ bar, foo ] ]', array('foo', array('bar', 'foo'))),
  329. array('[{ foo: {bar: foo} }]', array(array('foo' => array('bar' => 'foo')))),
  330. array('[foo, [bar, [foo, [bar, foo]], foo]]', array('foo', array('bar', array('foo', array('bar', 'foo')), 'foo'))),
  331. array('[foo, {bar: foo, foo: [foo, {bar: foo}]}, [foo, {bar: foo}]]', array('foo', array('bar' => 'foo', 'foo' => array('foo', array('bar' => 'foo'))), array('foo', array('bar' => 'foo')))),
  332. array('[foo, bar: { foo: bar }]', array('foo', '1' => array('bar' => array('foo' => 'bar')))),
  333. array('[foo, \'@foo.baz\', { \'%foo%\': \'foo is %foo%\', bar: \'%foo%\' }, true, \'@service_container\']', array('foo', '@foo.baz', array('%foo%' => 'foo is %foo%', 'bar' => '%foo%'), true, '@service_container')),
  334. );
  335. }
  336. public function getTestsForParseWithMapObjects()
  337. {
  338. return array(
  339. array('', ''),
  340. array('null', null),
  341. array('false', false),
  342. array('true', true),
  343. array('12', 12),
  344. array('-12', -12),
  345. array('"quoted string"', 'quoted string'),
  346. array("'quoted string'", 'quoted string'),
  347. array('12.30e+02', 12.30e+02),
  348. array('0x4D2', 0x4D2),
  349. array('02333', 02333),
  350. array('.Inf', -log(0)),
  351. array('-.Inf', log(0)),
  352. array("'686e444'", '686e444'),
  353. array('686e444', 646e444),
  354. array('123456789123456789123456789123456789', '123456789123456789123456789123456789'),
  355. array('"foo\r\nbar"', "foo\r\nbar"),
  356. array("'foo#bar'", 'foo#bar'),
  357. array("'foo # bar'", 'foo # bar'),
  358. array("'#cfcfcf'", '#cfcfcf'),
  359. array('::form_base.html.twig', '::form_base.html.twig'),
  360. array('2007-10-30', gmmktime(0, 0, 0, 10, 30, 2007)),
  361. array('2007-10-30T02:59:43Z', gmmktime(2, 59, 43, 10, 30, 2007)),
  362. array('2007-10-30 02:59:43 Z', gmmktime(2, 59, 43, 10, 30, 2007)),
  363. array('1960-10-30 02:59:43 Z', gmmktime(2, 59, 43, 10, 30, 1960)),
  364. array('1730-10-30T02:59:43Z', gmmktime(2, 59, 43, 10, 30, 1730)),
  365. array('"a \\"string\\" with \'quoted strings inside\'"', 'a "string" with \'quoted strings inside\''),
  366. array("'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. array('[foo, http://urls.are/no/mappings, false, null, 12]', array('foo', 'http://urls.are/no/mappings', false, null, 12)),
  370. array('[ foo , bar , false , null , 12 ]', array('foo', 'bar', false, null, 12)),
  371. array('[\'foo,bar\', \'foo bar\']', array('foo,bar', 'foo bar')),
  372. // mappings
  373. array('{foo: bar,bar: foo,"false": false,"null": null,integer: 12}', (object) array('foo' => 'bar', 'bar' => 'foo', 'false' => false, 'null' => null, 'integer' => 12), Yaml::PARSE_OBJECT_FOR_MAP),
  374. array('{ foo : bar, bar : foo, "false" : false, "null" : null, integer : 12 }', (object) array('foo' => 'bar', 'bar' => 'foo', 'false' => false, 'null' => null, 'integer' => 12), Yaml::PARSE_OBJECT_FOR_MAP),
  375. array('{foo: \'bar\', bar: \'foo: bar\'}', (object) array('foo' => 'bar', 'bar' => 'foo: bar')),
  376. array('{\'foo\': \'bar\', "bar": \'foo: bar\'}', (object) array('foo' => 'bar', 'bar' => 'foo: bar')),
  377. array('{\'foo\'\'\': \'bar\', "bar\"": \'foo: bar\'}', (object) array('foo\'' => 'bar', 'bar"' => 'foo: bar')),
  378. array('{\'foo: \': \'bar\', "bar: ": \'foo: bar\'}', (object) array('foo: ' => 'bar', 'bar: ' => 'foo: bar')),
  379. array('{"foo:bar": "baz"}', (object) array('foo:bar' => 'baz')),
  380. array('{"foo":"bar"}', (object) array('foo' => 'bar')),
  381. // nested sequences and mappings
  382. array('[foo, [bar, foo]]', array('foo', array('bar', 'foo'))),
  383. array('[foo, {bar: foo}]', array('foo', (object) array('bar' => 'foo'))),
  384. array('{ foo: {bar: foo} }', (object) array('foo' => (object) array('bar' => 'foo'))),
  385. array('{ foo: [bar, foo] }', (object) array('foo' => array('bar', 'foo'))),
  386. array('[ foo, [ bar, foo ] ]', array('foo', array('bar', 'foo'))),
  387. array('[{ foo: {bar: foo} }]', array((object) array('foo' => (object) array('bar' => 'foo')))),
  388. array('[foo, [bar, [foo, [bar, foo]], foo]]', array('foo', array('bar', array('foo', array('bar', 'foo')), 'foo'))),
  389. array('[foo, {bar: foo, foo: [foo, {bar: foo}]}, [foo, {bar: foo}]]', array('foo', (object) array('bar' => 'foo', 'foo' => array('foo', (object) array('bar' => 'foo'))), array('foo', (object) array('bar' => 'foo')))),
  390. array('[foo, bar: { foo: bar }]', array('foo', '1' => (object) array('bar' => (object) array('foo' => 'bar')))),
  391. array('[foo, \'@foo.baz\', { \'%foo%\': \'foo is %foo%\', bar: \'%foo%\' }, true, \'@service_container\']', array('foo', '@foo.baz', (object) array('%foo%' => 'foo is %foo%', 'bar' => '%foo%'), true, '@service_container')),
  392. array('{}', new \stdClass()),
  393. array('{ foo : bar, bar : {} }', (object) array('foo' => 'bar', 'bar' => new \stdClass())),
  394. array('{ foo : [], bar : {} }', (object) array('foo' => array(), 'bar' => new \stdClass())),
  395. array('{foo: \'bar\', bar: {} }', (object) array('foo' => 'bar', 'bar' => new \stdClass())),
  396. array('{\'foo\': \'bar\', "bar": {}}', (object) array('foo' => 'bar', 'bar' => new \stdClass())),
  397. array('{\'foo\': \'bar\', "bar": \'{}\'}', (object) array('foo' => 'bar', 'bar' => '{}')),
  398. array('[foo, [{}, {}]]', array('foo', array(new \stdClass(), new \stdClass()))),
  399. array('[foo, [[], {}]]', array('foo', array(array(), new \stdClass()))),
  400. array('[foo, [[{}, {}], {}]]', array('foo', array(array(new \stdClass(), new \stdClass()), new \stdClass()))),
  401. array('[foo, {bar: {}}]', array('foo', '1' => (object) array('bar' => new \stdClass()))),
  402. );
  403. }
  404. public function getTestsForDump()
  405. {
  406. return array(
  407. array('null', null),
  408. array('false', false),
  409. array('true', true),
  410. array('12', 12),
  411. array("'1_2'", '1_2'),
  412. array('_12', '_12'),
  413. array("'12_'", '12_'),
  414. array("'quoted string'", 'quoted string'),
  415. array('!!float 1230', 12.30e+02),
  416. array('1234', 0x4D2),
  417. array('1243', 02333),
  418. array("'0x_4_D_2_'", '0x_4_D_2_'),
  419. array("'0_2_3_3_3'", '0_2_3_3_3'),
  420. array('.Inf', -log(0)),
  421. array('-.Inf', log(0)),
  422. array("'686e444'", '686e444'),
  423. array('"foo\r\nbar"', "foo\r\nbar"),
  424. array("'foo#bar'", 'foo#bar'),
  425. array("'foo # bar'", 'foo # bar'),
  426. array("'#cfcfcf'", '#cfcfcf'),
  427. array("'a \"string\" with ''quoted strings inside'''", 'a "string" with \'quoted strings inside\''),
  428. array("'-dash'", '-dash'),
  429. array("'-'", '-'),
  430. // Pre-YAML-1.2 booleans
  431. array("'y'", 'y'),
  432. array("'n'", 'n'),
  433. array("'yes'", 'yes'),
  434. array("'no'", 'no'),
  435. array("'on'", 'on'),
  436. array("'off'", 'off'),
  437. // sequences
  438. array('[foo, bar, false, null, 12]', array('foo', 'bar', false, null, 12)),
  439. array('[\'foo,bar\', \'foo bar\']', array('foo,bar', 'foo bar')),
  440. // mappings
  441. array('{ foo: bar, bar: foo, \'false\': false, \'null\': null, integer: 12 }', array('foo' => 'bar', 'bar' => 'foo', 'false' => false, 'null' => null, 'integer' => 12)),
  442. array('{ foo: bar, bar: \'foo: bar\' }', array('foo' => 'bar', 'bar' => 'foo: bar')),
  443. // nested sequences and mappings
  444. array('[foo, [bar, foo]]', array('foo', array('bar', 'foo'))),
  445. array('[foo, [bar, [foo, [bar, foo]], foo]]', array('foo', array('bar', array('foo', array('bar', 'foo')), 'foo'))),
  446. array('{ foo: { bar: foo } }', array('foo' => array('bar' => 'foo'))),
  447. array('[foo, { bar: foo }]', array('foo', array('bar' => 'foo'))),
  448. array('[foo, { bar: foo, foo: [foo, { bar: foo }] }, [foo, { bar: foo }]]', array('foo', array('bar' => 'foo', 'foo' => array('foo', array('bar' => 'foo'))), array('foo', array('bar' => 'foo')))),
  449. array('[foo, \'@foo.baz\', { \'%foo%\': \'foo is %foo%\', bar: \'%foo%\' }, true, \'@service_container\']', array('foo', '@foo.baz', array('%foo%' => 'foo is %foo%', 'bar' => '%foo%'), true, '@service_container')),
  450. array('{ foo: { bar: { 1: 2, baz: 3 } } }', array('foo' => array('bar' => array(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 array(
  476. 'canonical' => array('2001-12-15T02:59:43.1Z', 2001, 12, 15, 2, 59, 43.1, '+0000'),
  477. 'ISO-8601' => array('2001-12-15t21:59:43.10-05:00', 2001, 12, 16, 2, 59, 43.1, '-0500'),
  478. 'spaced' => array('2001-12-15 21:59:43.10 -5', 2001, 12, 16, 2, 59, 43.1, '-0500'),
  479. 'date' => array('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 = array('nested' => array($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 = array();
  505. $dateTime = new \DateTime('2001-12-15 21:59:43', new \DateTimeZone('UTC'));
  506. $tests['date-time-utc'] = array($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'] = array($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 array(
  521. 'enclosed with double quotes' => array('!!binary "SGVsbG8gd29ybGQ="'),
  522. 'enclosed with single quotes' => array("!!binary 'SGVsbG8gd29ybGQ='"),
  523. 'containing spaces' => array('!!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 array(
  542. 'length not a multiple of four' => array('!!binary "SGVsbG8d29ybGQ="', '/The normalized base64 encoded data \(data without whitespace characters\) length must be a multiple of four \(\d+ bytes given\)/'),
  543. 'invalid characters' => array('!!binary "SGVsbG8#d29ybGQ="', '/The base64 encoded data \(.*\) contains invalid characters/'),
  544. 'too many equals characters' => array('!!binary "SGVsbG8gd29yb==="', '/The base64 encoded data \(.*\) contains invalid characters/'),
  545. 'misplaced equals character' => array('!!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(array('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 array(
  581. 'null before closing curly brace' => array('{foo:}', array('foo' => null)),
  582. 'null before comma' => array('{foo:, bar: baz}', array('foo' => null, 'bar' => 'baz')),
  583. );
  584. }
  585. public function testTheEmptyStringIsAValidMappingKey()
  586. {
  587. $this->assertSame(array('' => '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 array(
  602. 'boolean-true' => array('{true: "foo"}', array('true' => 'foo')),
  603. 'boolean-false' => array('{false: "foo"}', array('false' => 'foo')),
  604. 'null' => array('{null: "foo"}', array('null' => 'foo')),
  605. 'float' => array('{0.25: "foo"}', array('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. }