InlineTest.php 29 KB

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