菜谱项目

InlineTest.php 31KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759
  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, $flags = 0)
  21. {
  22. $this->assertSame($value, Inline::parse($yaml, $flags), sprintf('::parse() converts an inline YAML to a PHP structure (%s)', $yaml));
  23. }
  24. /**
  25. * @dataProvider getTestsForParseWithMapObjects
  26. */
  27. public function testParseWithMapObjects($yaml, $value, $flags = Yaml::PARSE_OBJECT_FOR_MAP)
  28. {
  29. $actual = Inline::parse($yaml, $flags);
  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, $parseFlags = 0)
  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), $parseFlags), '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 after an unquoted mapping key that is not followed by an indication character (i.e. " ", ",", "[", "]", "{", "}") is deprecated since version 3.2 and will throw a ParseException in 4.0 on line 1.
  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 on line 1.
  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), Yaml::PARSE_KEYS_AS_STRINGS),
  339. array('{ foo : bar, bar : foo, false : false, null : null, integer : 12 }', array('foo' => 'bar', 'bar' => 'foo', 'false' => false, 'null' => null, 'integer' => 12), Yaml::PARSE_KEYS_AS_STRINGS),
  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. array('{"foo:bar": "baz"}', array('foo:bar' => 'baz')),
  345. array('{"foo":"bar"}', array('foo' => 'bar')),
  346. // nested sequences and mappings
  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('foo' => array('bar', 'foo'))),
  353. array('[ foo, [ bar, foo ] ]', array('foo', array('bar', 'foo'))),
  354. array('[{ foo: {bar: foo} }]', array(array('foo' => array('bar' => 'foo')))),
  355. array('[foo, [bar, [foo, [bar, foo]], foo]]', array('foo', array('bar', array('foo', array('bar', 'foo')), 'foo'))),
  356. 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')))),
  357. array('[foo, bar: { foo: bar }]', array('foo', '1' => array('bar' => array('foo' => 'bar')))),
  358. 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')),
  359. );
  360. }
  361. public function getTestsForParseWithMapObjects()
  362. {
  363. return array(
  364. array('', ''),
  365. array('null', null),
  366. array('false', false),
  367. array('true', true),
  368. array('12', 12),
  369. array('-12', -12),
  370. array('"quoted string"', 'quoted string'),
  371. array("'quoted string'", 'quoted string'),
  372. array('12.30e+02', 12.30e+02),
  373. array('0x4D2', 0x4D2),
  374. array('02333', 02333),
  375. array('.Inf', -log(0)),
  376. array('-.Inf', log(0)),
  377. array("'686e444'", '686e444'),
  378. array('686e444', 646e444),
  379. array('123456789123456789123456789123456789', '123456789123456789123456789123456789'),
  380. array('"foo\r\nbar"', "foo\r\nbar"),
  381. array("'foo#bar'", 'foo#bar'),
  382. array("'foo # bar'", 'foo # bar'),
  383. array("'#cfcfcf'", '#cfcfcf'),
  384. array('::form_base.html.twig', '::form_base.html.twig'),
  385. array('2007-10-30', gmmktime(0, 0, 0, 10, 30, 2007)),
  386. array('2007-10-30T02:59:43Z', gmmktime(2, 59, 43, 10, 30, 2007)),
  387. array('2007-10-30 02:59:43 Z', gmmktime(2, 59, 43, 10, 30, 2007)),
  388. array('1960-10-30 02:59:43 Z', gmmktime(2, 59, 43, 10, 30, 1960)),
  389. array('1730-10-30T02:59:43Z', gmmktime(2, 59, 43, 10, 30, 1730)),
  390. array('"a \\"string\\" with \'quoted strings inside\'"', 'a "string" with \'quoted strings inside\''),
  391. array("'a \"string\" with ''quoted strings inside'''", 'a "string" with \'quoted strings inside\''),
  392. // sequences
  393. // urls are no key value mapping. see #3609. Valid yaml "key: value" mappings require a space after the colon
  394. array('[foo, http://urls.are/no/mappings, false, null, 12]', array('foo', 'http://urls.are/no/mappings', false, null, 12)),
  395. array('[ foo , bar , false , null , 12 ]', array('foo', 'bar', false, null, 12)),
  396. array('[\'foo,bar\', \'foo bar\']', array('foo,bar', 'foo bar')),
  397. // mappings
  398. 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 | Yaml::PARSE_KEYS_AS_STRINGS),
  399. 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 | Yaml::PARSE_KEYS_AS_STRINGS),
  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. array('{\'foo\'\'\': \'bar\', "bar\"": \'foo: bar\'}', (object) array('foo\'' => 'bar', 'bar"' => 'foo: bar')),
  403. array('{\'foo: \': \'bar\', "bar: ": \'foo: bar\'}', (object) array('foo: ' => 'bar', 'bar: ' => 'foo: bar')),
  404. array('{"foo:bar": "baz"}', (object) array('foo:bar' => 'baz')),
  405. array('{"foo":"bar"}', (object) array('foo' => 'bar')),
  406. // nested sequences and mappings
  407. array('[foo, [bar, foo]]', array('foo', array('bar', 'foo'))),
  408. array('[foo, {bar: foo}]', array('foo', (object) array('bar' => 'foo'))),
  409. array('{ foo: {bar: foo} }', (object) array('foo' => (object) array('bar' => 'foo'))),
  410. array('{ foo: [bar, foo] }', (object) array('foo' => array('bar', 'foo'))),
  411. array('[ foo, [ bar, foo ] ]', array('foo', array('bar', 'foo'))),
  412. array('[{ foo: {bar: foo} }]', array((object) array('foo' => (object) array('bar' => 'foo')))),
  413. array('[foo, [bar, [foo, [bar, foo]], foo]]', array('foo', array('bar', array('foo', array('bar', 'foo')), 'foo'))),
  414. 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')))),
  415. array('[foo, bar: { foo: bar }]', array('foo', '1' => (object) array('bar' => (object) array('foo' => 'bar')))),
  416. 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')),
  417. array('{}', new \stdClass()),
  418. array('{ foo : bar, bar : {} }', (object) array('foo' => 'bar', 'bar' => new \stdClass())),
  419. array('{ foo : [], bar : {} }', (object) array('foo' => array(), 'bar' => new \stdClass())),
  420. array('{foo: \'bar\', bar: {} }', (object) array('foo' => 'bar', 'bar' => new \stdClass())),
  421. array('{\'foo\': \'bar\', "bar": {}}', (object) array('foo' => 'bar', 'bar' => new \stdClass())),
  422. array('{\'foo\': \'bar\', "bar": \'{}\'}', (object) array('foo' => 'bar', 'bar' => '{}')),
  423. array('[foo, [{}, {}]]', array('foo', array(new \stdClass(), new \stdClass()))),
  424. array('[foo, [[], {}]]', array('foo', array(array(), new \stdClass()))),
  425. array('[foo, [[{}, {}], {}]]', array('foo', array(array(new \stdClass(), new \stdClass()), new \stdClass()))),
  426. array('[foo, {bar: {}}]', array('foo', '1' => (object) array('bar' => new \stdClass()))),
  427. );
  428. }
  429. public function getTestsForDump()
  430. {
  431. return array(
  432. array('null', null),
  433. array('false', false),
  434. array('true', true),
  435. array('12', 12),
  436. array("'1_2'", '1_2'),
  437. array('_12', '_12'),
  438. array("'12_'", '12_'),
  439. array("'quoted string'", 'quoted string'),
  440. array('!!float 1230', 12.30e+02),
  441. array('1234', 0x4D2),
  442. array('1243', 02333),
  443. array("'0x_4_D_2_'", '0x_4_D_2_'),
  444. array("'0_2_3_3_3'", '0_2_3_3_3'),
  445. array('.Inf', -log(0)),
  446. array('-.Inf', log(0)),
  447. array("'686e444'", '686e444'),
  448. array('"foo\r\nbar"', "foo\r\nbar"),
  449. array("'foo#bar'", 'foo#bar'),
  450. array("'foo # bar'", 'foo # bar'),
  451. array("'#cfcfcf'", '#cfcfcf'),
  452. array("'a \"string\" with ''quoted strings inside'''", 'a "string" with \'quoted strings inside\''),
  453. array("'-dash'", '-dash'),
  454. array("'-'", '-'),
  455. // Pre-YAML-1.2 booleans
  456. array("'y'", 'y'),
  457. array("'n'", 'n'),
  458. array("'yes'", 'yes'),
  459. array("'no'", 'no'),
  460. array("'on'", 'on'),
  461. array("'off'", 'off'),
  462. // sequences
  463. array('[foo, bar, false, null, 12]', array('foo', 'bar', false, null, 12)),
  464. array('[\'foo,bar\', \'foo bar\']', array('foo,bar', 'foo bar')),
  465. // mappings
  466. array('{ foo: bar, bar: foo, \'false\': false, \'null\': null, integer: 12 }', array('foo' => 'bar', 'bar' => 'foo', 'false' => false, 'null' => null, 'integer' => 12), Yaml::PARSE_KEYS_AS_STRINGS),
  467. array('{ foo: bar, bar: \'foo: bar\' }', array('foo' => 'bar', 'bar' => 'foo: bar')),
  468. // nested sequences and mappings
  469. array('[foo, [bar, foo]]', array('foo', array('bar', 'foo'))),
  470. array('[foo, [bar, [foo, [bar, foo]], foo]]', array('foo', array('bar', array('foo', array('bar', 'foo')), 'foo'))),
  471. array('{ foo: { bar: foo } }', array('foo' => array('bar' => 'foo'))),
  472. array('[foo, { bar: foo }]', array('foo', array('bar' => 'foo'))),
  473. 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')))),
  474. 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')),
  475. array('{ foo: { bar: { 1: 2, baz: 3 } } }', array('foo' => array('bar' => array(1 => 2, 'baz' => 3))), Yaml::PARSE_KEYS_AS_STRINGS),
  476. );
  477. }
  478. /**
  479. * @dataProvider getTimestampTests
  480. */
  481. public function testParseTimestampAsUnixTimestampByDefault($yaml, $year, $month, $day, $hour, $minute, $second)
  482. {
  483. $this->assertSame(gmmktime($hour, $minute, $second, $month, $day, $year), Inline::parse($yaml));
  484. }
  485. /**
  486. * @dataProvider getTimestampTests
  487. */
  488. public function testParseTimestampAsDateTimeObject($yaml, $year, $month, $day, $hour, $minute, $second, $timezone)
  489. {
  490. $expected = new \DateTime($yaml);
  491. $expected->setTimeZone(new \DateTimeZone('UTC'));
  492. $expected->setDate($year, $month, $day);
  493. if (\PHP_VERSION_ID >= 70100) {
  494. $expected->setTime($hour, $minute, $second, 1000000 * ($second - (int) $second));
  495. } else {
  496. $expected->setTime($hour, $minute, $second);
  497. }
  498. $date = Inline::parse($yaml, Yaml::PARSE_DATETIME);
  499. $this->assertEquals($expected, $date);
  500. $this->assertSame($timezone, $date->format('O'));
  501. }
  502. public function getTimestampTests()
  503. {
  504. return array(
  505. 'canonical' => array('2001-12-15T02:59:43.1Z', 2001, 12, 15, 2, 59, 43.1, '+0000'),
  506. 'ISO-8601' => array('2001-12-15t21:59:43.10-05:00', 2001, 12, 16, 2, 59, 43.1, '-0500'),
  507. 'spaced' => array('2001-12-15 21:59:43.10 -5', 2001, 12, 16, 2, 59, 43.1, '-0500'),
  508. 'date' => array('2001-12-15', 2001, 12, 15, 0, 0, 0, '+0000'),
  509. );
  510. }
  511. /**
  512. * @dataProvider getTimestampTests
  513. */
  514. public function testParseNestedTimestampListAsDateTimeObject($yaml, $year, $month, $day, $hour, $minute, $second)
  515. {
  516. $expected = new \DateTime($yaml);
  517. $expected->setTimeZone(new \DateTimeZone('UTC'));
  518. $expected->setDate($year, $month, $day);
  519. if (\PHP_VERSION_ID >= 70100) {
  520. $expected->setTime($hour, $minute, $second, 1000000 * ($second - (int) $second));
  521. } else {
  522. $expected->setTime($hour, $minute, $second);
  523. }
  524. $expectedNested = array('nested' => array($expected));
  525. $yamlNested = "{nested: [$yaml]}";
  526. $this->assertEquals($expectedNested, Inline::parse($yamlNested, Yaml::PARSE_DATETIME));
  527. }
  528. /**
  529. * @dataProvider getDateTimeDumpTests
  530. */
  531. public function testDumpDateTime($dateTime, $expected)
  532. {
  533. $this->assertSame($expected, Inline::dump($dateTime));
  534. }
  535. public function getDateTimeDumpTests()
  536. {
  537. $tests = array();
  538. $dateTime = new \DateTime('2001-12-15 21:59:43', new \DateTimeZone('UTC'));
  539. $tests['date-time-utc'] = array($dateTime, '2001-12-15T21:59:43+00:00');
  540. $dateTime = new \DateTimeImmutable('2001-07-15 21:59:43', new \DateTimeZone('Europe/Berlin'));
  541. $tests['immutable-date-time-europe-berlin'] = array($dateTime, '2001-07-15T21:59:43+02:00');
  542. return $tests;
  543. }
  544. /**
  545. * @dataProvider getBinaryData
  546. */
  547. public function testParseBinaryData($data)
  548. {
  549. $this->assertSame('Hello world', Inline::parse($data));
  550. }
  551. public function getBinaryData()
  552. {
  553. return array(
  554. 'enclosed with double quotes' => array('!!binary "SGVsbG8gd29ybGQ="'),
  555. 'enclosed with single quotes' => array("!!binary 'SGVsbG8gd29ybGQ='"),
  556. 'containing spaces' => array('!!binary "SGVs bG8gd 29ybGQ="'),
  557. );
  558. }
  559. /**
  560. * @dataProvider getInvalidBinaryData
  561. * @expectedException \Symfony\Component\Yaml\Exception\ParseException
  562. */
  563. public function testParseInvalidBinaryData($data, $expectedMessage)
  564. {
  565. if (method_exists($this, 'expectException')) {
  566. $this->expectExceptionMessageRegExp($expectedMessage);
  567. } else {
  568. $this->setExpectedExceptionRegExp(ParseException::class, $expectedMessage);
  569. }
  570. Inline::parse($data);
  571. }
  572. public function getInvalidBinaryData()
  573. {
  574. return array(
  575. '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\)/'),
  576. 'invalid characters' => array('!!binary "SGVsbG8#d29ybGQ="', '/The base64 encoded data \(.*\) contains invalid characters/'),
  577. 'too many equals characters' => array('!!binary "SGVsbG8gd29yb==="', '/The base64 encoded data \(.*\) contains invalid characters/'),
  578. 'misplaced equals character' => array('!!binary "SGVsbG8gd29ybG=Q"', '/The base64 encoded data \(.*\) contains invalid characters/'),
  579. );
  580. }
  581. /**
  582. * @expectedException \Symfony\Component\Yaml\Exception\ParseException
  583. * @expectedExceptionMessage Malformed inline YAML string: {this, is not, supported}.
  584. */
  585. public function testNotSupportedMissingValue()
  586. {
  587. Inline::parse('{this, is not, supported}');
  588. }
  589. public function testVeryLongQuotedStrings()
  590. {
  591. $longStringWithQuotes = str_repeat("x\r\n\\\"x\"x", 1000);
  592. $yamlString = Inline::dump(array('longStringWithQuotes' => $longStringWithQuotes));
  593. $arrayFromYaml = Inline::parse($yamlString);
  594. $this->assertEquals($longStringWithQuotes, $arrayFromYaml['longStringWithQuotes']);
  595. }
  596. /**
  597. * @group legacy
  598. * @expectedDeprecation Omitting the key of a mapping is deprecated and will throw a ParseException in 4.0 on line 1.
  599. */
  600. public function testOmittedMappingKeyIsParsedAsColon()
  601. {
  602. $this->assertSame(array(':' => 'foo'), Inline::parse('{: foo}'));
  603. }
  604. /**
  605. * @dataProvider getTestsForNullValues
  606. */
  607. public function testParseMissingMappingValueAsNull($yaml, $expected)
  608. {
  609. $this->assertSame($expected, Inline::parse($yaml));
  610. }
  611. public function getTestsForNullValues()
  612. {
  613. return array(
  614. 'null before closing curly brace' => array('{foo:}', array('foo' => null)),
  615. 'null before comma' => array('{foo:, bar: baz}', array('foo' => null, 'bar' => 'baz')),
  616. );
  617. }
  618. public function testTheEmptyStringIsAValidMappingKey()
  619. {
  620. $this->assertSame(array('' => 'foo'), Inline::parse('{ "": foo }'));
  621. }
  622. /**
  623. * @group legacy
  624. * @expectedDeprecation Implicit casting of incompatible mapping keys to strings is deprecated since version 3.3 and will throw \Symfony\Component\Yaml\Exception\ParseException in 4.0. Quote your evaluable mapping keys instead on line 1.
  625. * @dataProvider getNotPhpCompatibleMappingKeyData
  626. */
  627. public function testImplicitStringCastingOfMappingKeysIsDeprecated($yaml, $expected)
  628. {
  629. $this->assertSame($expected, Inline::parse($yaml));
  630. }
  631. /**
  632. * @dataProvider getNotPhpCompatibleMappingKeyData
  633. */
  634. public function testExplicitStringCastingOfMappingKeys($yaml, $expected)
  635. {
  636. $this->assertSame($expected, Inline::parse($yaml, Yaml::PARSE_KEYS_AS_STRINGS));
  637. }
  638. public function getNotPhpCompatibleMappingKeyData()
  639. {
  640. return array(
  641. 'boolean-true' => array('{true: "foo"}', array('true' => 'foo')),
  642. 'boolean-false' => array('{false: "foo"}', array('false' => 'foo')),
  643. 'null' => array('{null: "foo"}', array('null' => 'foo')),
  644. 'float' => array('{0.25: "foo"}', array('0.25' => 'foo')),
  645. );
  646. }
  647. }