Inline.php 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901
  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;
  11. use Symfony\Component\Yaml\Exception\DumpException;
  12. use Symfony\Component\Yaml\Exception\ParseException;
  13. use Symfony\Component\Yaml\Tag\TaggedValue;
  14. /**
  15. * Inline implements a YAML parser/dumper for the YAML inline syntax.
  16. *
  17. * @author Fabien Potencier <fabien@symfony.com>
  18. *
  19. * @internal
  20. */
  21. class Inline
  22. {
  23. const REGEX_QUOTED_STRING = '(?:"([^"\\\\]*+(?:\\\\.[^"\\\\]*+)*+)"|\'([^\']*+(?:\'\'[^\']*+)*+)\')';
  24. public static $parsedLineNumber = -1;
  25. public static $parsedFilename;
  26. private static $exceptionOnInvalidType = false;
  27. private static $objectSupport = false;
  28. private static $objectForMap = false;
  29. private static $constantSupport = false;
  30. /**
  31. * @param int $flags
  32. * @param int|null $parsedLineNumber
  33. * @param string|null $parsedFilename
  34. */
  35. public static function initialize($flags, $parsedLineNumber = null, $parsedFilename = null)
  36. {
  37. self::$exceptionOnInvalidType = (bool) (Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE & $flags);
  38. self::$objectSupport = (bool) (Yaml::PARSE_OBJECT & $flags);
  39. self::$objectForMap = (bool) (Yaml::PARSE_OBJECT_FOR_MAP & $flags);
  40. self::$constantSupport = (bool) (Yaml::PARSE_CONSTANT & $flags);
  41. self::$parsedFilename = $parsedFilename;
  42. if (null !== $parsedLineNumber) {
  43. self::$parsedLineNumber = $parsedLineNumber;
  44. }
  45. }
  46. /**
  47. * Converts a YAML string to a PHP value.
  48. *
  49. * @param string $value A YAML string
  50. * @param int $flags A bit field of PARSE_* constants to customize the YAML parser behavior
  51. * @param array $references Mapping of variable names to values
  52. *
  53. * @return mixed A PHP value
  54. *
  55. * @throws ParseException
  56. */
  57. public static function parse($value, $flags = 0, $references = array())
  58. {
  59. if (\is_bool($flags)) {
  60. @trigger_error('Passing a boolean flag to toggle exception handling is deprecated since Symfony 3.1 and will be removed in 4.0. Use the Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE flag instead.', E_USER_DEPRECATED);
  61. if ($flags) {
  62. $flags = Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE;
  63. } else {
  64. $flags = 0;
  65. }
  66. }
  67. if (\func_num_args() >= 3 && !\is_array($references)) {
  68. @trigger_error('Passing a boolean flag to toggle object support is deprecated since Symfony 3.1 and will be removed in 4.0. Use the Yaml::PARSE_OBJECT flag instead.', E_USER_DEPRECATED);
  69. if ($references) {
  70. $flags |= Yaml::PARSE_OBJECT;
  71. }
  72. if (\func_num_args() >= 4) {
  73. @trigger_error('Passing a boolean flag to toggle object for map support is deprecated since Symfony 3.1 and will be removed in 4.0. Use the Yaml::PARSE_OBJECT_FOR_MAP flag instead.', E_USER_DEPRECATED);
  74. if (func_get_arg(3)) {
  75. $flags |= Yaml::PARSE_OBJECT_FOR_MAP;
  76. }
  77. }
  78. if (\func_num_args() >= 5) {
  79. $references = func_get_arg(4);
  80. } else {
  81. $references = array();
  82. }
  83. }
  84. self::initialize($flags);
  85. $value = trim($value);
  86. if ('' === $value) {
  87. return '';
  88. }
  89. if (2 /* MB_OVERLOAD_STRING */ & (int) ini_get('mbstring.func_overload')) {
  90. $mbEncoding = mb_internal_encoding();
  91. mb_internal_encoding('ASCII');
  92. }
  93. $i = 0;
  94. $tag = self::parseTag($value, $i, $flags);
  95. switch ($value[$i]) {
  96. case '[':
  97. $result = self::parseSequence($value, $flags, $i, $references);
  98. ++$i;
  99. break;
  100. case '{':
  101. $result = self::parseMapping($value, $flags, $i, $references);
  102. ++$i;
  103. break;
  104. default:
  105. $result = self::parseScalar($value, $flags, null, $i, null === $tag, $references);
  106. }
  107. if (null !== $tag) {
  108. return new TaggedValue($tag, $result);
  109. }
  110. // some comments are allowed at the end
  111. if (preg_replace('/\s+#.*$/A', '', substr($value, $i))) {
  112. throw new ParseException(sprintf('Unexpected characters near "%s".', substr($value, $i)), self::$parsedLineNumber + 1, $value, self::$parsedFilename);
  113. }
  114. if (isset($mbEncoding)) {
  115. mb_internal_encoding($mbEncoding);
  116. }
  117. return $result;
  118. }
  119. /**
  120. * Dumps a given PHP variable to a YAML string.
  121. *
  122. * @param mixed $value The PHP variable to convert
  123. * @param int $flags A bit field of Yaml::DUMP_* constants to customize the dumped YAML string
  124. *
  125. * @return string The YAML string representing the PHP value
  126. *
  127. * @throws DumpException When trying to dump PHP resource
  128. */
  129. public static function dump($value, $flags = 0)
  130. {
  131. if (\is_bool($flags)) {
  132. @trigger_error('Passing a boolean flag to toggle exception handling is deprecated since Symfony 3.1 and will be removed in 4.0. Use the Yaml::DUMP_EXCEPTION_ON_INVALID_TYPE flag instead.', E_USER_DEPRECATED);
  133. if ($flags) {
  134. $flags = Yaml::DUMP_EXCEPTION_ON_INVALID_TYPE;
  135. } else {
  136. $flags = 0;
  137. }
  138. }
  139. if (\func_num_args() >= 3) {
  140. @trigger_error('Passing a boolean flag to toggle object support is deprecated since Symfony 3.1 and will be removed in 4.0. Use the Yaml::DUMP_OBJECT flag instead.', E_USER_DEPRECATED);
  141. if (func_get_arg(2)) {
  142. $flags |= Yaml::DUMP_OBJECT;
  143. }
  144. }
  145. switch (true) {
  146. case \is_resource($value):
  147. if (Yaml::DUMP_EXCEPTION_ON_INVALID_TYPE & $flags) {
  148. throw new DumpException(sprintf('Unable to dump PHP resources in a YAML file ("%s").', get_resource_type($value)));
  149. }
  150. return 'null';
  151. case $value instanceof \DateTimeInterface:
  152. return $value->format('c');
  153. case \is_object($value):
  154. if ($value instanceof TaggedValue) {
  155. return '!'.$value->getTag().' '.self::dump($value->getValue(), $flags);
  156. }
  157. if (Yaml::DUMP_OBJECT & $flags) {
  158. return '!php/object '.self::dump(serialize($value));
  159. }
  160. if (Yaml::DUMP_OBJECT_AS_MAP & $flags && ($value instanceof \stdClass || $value instanceof \ArrayObject)) {
  161. return self::dumpArray($value, $flags & ~Yaml::DUMP_EMPTY_ARRAY_AS_SEQUENCE);
  162. }
  163. if (Yaml::DUMP_EXCEPTION_ON_INVALID_TYPE & $flags) {
  164. throw new DumpException('Object support when dumping a YAML file has been disabled.');
  165. }
  166. return 'null';
  167. case \is_array($value):
  168. return self::dumpArray($value, $flags);
  169. case null === $value:
  170. return 'null';
  171. case true === $value:
  172. return 'true';
  173. case false === $value:
  174. return 'false';
  175. case ctype_digit($value):
  176. return \is_string($value) ? "'$value'" : (int) $value;
  177. case is_numeric($value):
  178. $locale = setlocale(LC_NUMERIC, 0);
  179. if (false !== $locale) {
  180. setlocale(LC_NUMERIC, 'C');
  181. }
  182. if (\is_float($value)) {
  183. $repr = (string) $value;
  184. if (is_infinite($value)) {
  185. $repr = str_ireplace('INF', '.Inf', $repr);
  186. } elseif (floor($value) == $value && $repr == $value) {
  187. // Preserve float data type since storing a whole number will result in integer value.
  188. $repr = '!!float '.$repr;
  189. }
  190. } else {
  191. $repr = \is_string($value) ? "'$value'" : (string) $value;
  192. }
  193. if (false !== $locale) {
  194. setlocale(LC_NUMERIC, $locale);
  195. }
  196. return $repr;
  197. case '' == $value:
  198. return "''";
  199. case self::isBinaryString($value):
  200. return '!!binary '.base64_encode($value);
  201. case Escaper::requiresDoubleQuoting($value):
  202. return Escaper::escapeWithDoubleQuotes($value);
  203. case Escaper::requiresSingleQuoting($value):
  204. case Parser::preg_match('{^[0-9]+[_0-9]*$}', $value):
  205. case Parser::preg_match(self::getHexRegex(), $value):
  206. case Parser::preg_match(self::getTimestampRegex(), $value):
  207. return Escaper::escapeWithSingleQuotes($value);
  208. default:
  209. return $value;
  210. }
  211. }
  212. /**
  213. * Check if given array is hash or just normal indexed array.
  214. *
  215. * @internal
  216. *
  217. * @param array|\ArrayObject|\stdClass $value The PHP array or array-like object to check
  218. *
  219. * @return bool true if value is hash array, false otherwise
  220. */
  221. public static function isHash($value)
  222. {
  223. if ($value instanceof \stdClass || $value instanceof \ArrayObject) {
  224. return true;
  225. }
  226. $expectedKey = 0;
  227. foreach ($value as $key => $val) {
  228. if ($key !== $expectedKey++) {
  229. return true;
  230. }
  231. }
  232. return false;
  233. }
  234. /**
  235. * Dumps a PHP array to a YAML string.
  236. *
  237. * @param array $value The PHP array to dump
  238. * @param int $flags A bit field of Yaml::DUMP_* constants to customize the dumped YAML string
  239. *
  240. * @return string The YAML string representing the PHP array
  241. */
  242. private static function dumpArray($value, $flags)
  243. {
  244. // array
  245. if (($value || Yaml::DUMP_EMPTY_ARRAY_AS_SEQUENCE & $flags) && !self::isHash($value)) {
  246. $output = array();
  247. foreach ($value as $val) {
  248. $output[] = self::dump($val, $flags);
  249. }
  250. return sprintf('[%s]', implode(', ', $output));
  251. }
  252. // hash
  253. $output = array();
  254. foreach ($value as $key => $val) {
  255. $output[] = sprintf('%s: %s', self::dump($key, $flags), self::dump($val, $flags));
  256. }
  257. return sprintf('{ %s }', implode(', ', $output));
  258. }
  259. /**
  260. * Parses a YAML scalar.
  261. *
  262. * @param string $scalar
  263. * @param int $flags
  264. * @param string[] $delimiters
  265. * @param int &$i
  266. * @param bool $evaluate
  267. * @param array $references
  268. *
  269. * @return string
  270. *
  271. * @throws ParseException When malformed inline YAML string is parsed
  272. *
  273. * @internal
  274. */
  275. public static function parseScalar($scalar, $flags = 0, $delimiters = null, &$i = 0, $evaluate = true, $references = array(), $legacyOmittedKeySupport = false)
  276. {
  277. if (\in_array($scalar[$i], array('"', "'"))) {
  278. // quoted scalar
  279. $output = self::parseQuotedScalar($scalar, $i);
  280. if (null !== $delimiters) {
  281. $tmp = ltrim(substr($scalar, $i), ' ');
  282. if ('' === $tmp) {
  283. throw new ParseException(sprintf('Unexpected end of line, expected one of "%s".', implode('', $delimiters)), self::$parsedLineNumber + 1, $scalar, self::$parsedFilename);
  284. }
  285. if (!\in_array($tmp[0], $delimiters)) {
  286. throw new ParseException(sprintf('Unexpected characters (%s).', substr($scalar, $i)), self::$parsedLineNumber + 1, $scalar, self::$parsedFilename);
  287. }
  288. }
  289. } else {
  290. // "normal" string
  291. if (!$delimiters) {
  292. $output = substr($scalar, $i);
  293. $i += \strlen($output);
  294. // remove comments
  295. if (Parser::preg_match('/[ \t]+#/', $output, $match, PREG_OFFSET_CAPTURE)) {
  296. $output = substr($output, 0, $match[0][1]);
  297. }
  298. } elseif (Parser::preg_match('/^(.'.($legacyOmittedKeySupport ? '+' : '*').'?)('.implode('|', $delimiters).')/', substr($scalar, $i), $match)) {
  299. $output = $match[1];
  300. $i += \strlen($output);
  301. } else {
  302. throw new ParseException(sprintf('Malformed inline YAML string: %s.', $scalar), self::$parsedLineNumber + 1, null, self::$parsedFilename);
  303. }
  304. // a non-quoted string cannot start with @ or ` (reserved) nor with a scalar indicator (| or >)
  305. if ($output && ('@' === $output[0] || '`' === $output[0] || '|' === $output[0] || '>' === $output[0])) {
  306. throw new ParseException(sprintf('The reserved indicator "%s" cannot start a plain scalar; you need to quote the scalar.', $output[0]), self::$parsedLineNumber + 1, $output, self::$parsedFilename);
  307. }
  308. if ($output && '%' === $output[0]) {
  309. @trigger_error(self::getDeprecationMessage(sprintf('Not quoting the scalar "%s" starting with the "%%" indicator character is deprecated since Symfony 3.1 and will throw a ParseException in 4.0.', $output)), E_USER_DEPRECATED);
  310. }
  311. if ($evaluate) {
  312. $output = self::evaluateScalar($output, $flags, $references);
  313. }
  314. }
  315. return $output;
  316. }
  317. /**
  318. * Parses a YAML quoted scalar.
  319. *
  320. * @param string $scalar
  321. * @param int &$i
  322. *
  323. * @return string
  324. *
  325. * @throws ParseException When malformed inline YAML string is parsed
  326. */
  327. private static function parseQuotedScalar($scalar, &$i)
  328. {
  329. if (!Parser::preg_match('/'.self::REGEX_QUOTED_STRING.'/Au', substr($scalar, $i), $match)) {
  330. throw new ParseException(sprintf('Malformed inline YAML string: %s.', substr($scalar, $i)), self::$parsedLineNumber + 1, $scalar, self::$parsedFilename);
  331. }
  332. $output = substr($match[0], 1, \strlen($match[0]) - 2);
  333. $unescaper = new Unescaper();
  334. if ('"' == $scalar[$i]) {
  335. $output = $unescaper->unescapeDoubleQuotedString($output);
  336. } else {
  337. $output = $unescaper->unescapeSingleQuotedString($output);
  338. }
  339. $i += \strlen($match[0]);
  340. return $output;
  341. }
  342. /**
  343. * Parses a YAML sequence.
  344. *
  345. * @param string $sequence
  346. * @param int $flags
  347. * @param int &$i
  348. * @param array $references
  349. *
  350. * @return array
  351. *
  352. * @throws ParseException When malformed inline YAML string is parsed
  353. */
  354. private static function parseSequence($sequence, $flags, &$i = 0, $references = array())
  355. {
  356. $output = array();
  357. $len = \strlen($sequence);
  358. ++$i;
  359. // [foo, bar, ...]
  360. while ($i < $len) {
  361. if (']' === $sequence[$i]) {
  362. return $output;
  363. }
  364. if (',' === $sequence[$i] || ' ' === $sequence[$i]) {
  365. ++$i;
  366. continue;
  367. }
  368. $tag = self::parseTag($sequence, $i, $flags);
  369. switch ($sequence[$i]) {
  370. case '[':
  371. // nested sequence
  372. $value = self::parseSequence($sequence, $flags, $i, $references);
  373. break;
  374. case '{':
  375. // nested mapping
  376. $value = self::parseMapping($sequence, $flags, $i, $references);
  377. break;
  378. default:
  379. $isQuoted = \in_array($sequence[$i], array('"', "'"));
  380. $value = self::parseScalar($sequence, $flags, array(',', ']'), $i, null === $tag, $references);
  381. // the value can be an array if a reference has been resolved to an array var
  382. if (\is_string($value) && !$isQuoted && false !== strpos($value, ': ')) {
  383. // embedded mapping?
  384. try {
  385. $pos = 0;
  386. $value = self::parseMapping('{'.$value.'}', $flags, $pos, $references);
  387. } catch (\InvalidArgumentException $e) {
  388. // no, it's not
  389. }
  390. }
  391. --$i;
  392. }
  393. if (null !== $tag) {
  394. $value = new TaggedValue($tag, $value);
  395. }
  396. $output[] = $value;
  397. ++$i;
  398. }
  399. throw new ParseException(sprintf('Malformed inline YAML string: %s.', $sequence), self::$parsedLineNumber + 1, null, self::$parsedFilename);
  400. }
  401. /**
  402. * Parses a YAML mapping.
  403. *
  404. * @param string $mapping
  405. * @param int $flags
  406. * @param int &$i
  407. * @param array $references
  408. *
  409. * @return array|\stdClass
  410. *
  411. * @throws ParseException When malformed inline YAML string is parsed
  412. */
  413. private static function parseMapping($mapping, $flags, &$i = 0, $references = array())
  414. {
  415. $output = array();
  416. $len = \strlen($mapping);
  417. ++$i;
  418. $allowOverwrite = false;
  419. // {foo: bar, bar:foo, ...}
  420. while ($i < $len) {
  421. switch ($mapping[$i]) {
  422. case ' ':
  423. case ',':
  424. ++$i;
  425. continue 2;
  426. case '}':
  427. if (self::$objectForMap) {
  428. return (object) $output;
  429. }
  430. return $output;
  431. }
  432. // key
  433. $isKeyQuoted = \in_array($mapping[$i], array('"', "'"), true);
  434. $key = self::parseScalar($mapping, $flags, array(':', ' '), $i, false, array(), true);
  435. if (':' !== $key && false === $i = strpos($mapping, ':', $i)) {
  436. break;
  437. }
  438. if (':' === $key) {
  439. @trigger_error(self::getDeprecationMessage('Omitting the key of a mapping is deprecated and will throw a ParseException in 4.0.'), E_USER_DEPRECATED);
  440. }
  441. if (!$isKeyQuoted) {
  442. $evaluatedKey = self::evaluateScalar($key, $flags, $references);
  443. if ('' !== $key && $evaluatedKey !== $key && !\is_string($evaluatedKey) && !\is_int($evaluatedKey)) {
  444. @trigger_error(self::getDeprecationMessage('Implicit casting of incompatible mapping keys to strings is deprecated since Symfony 3.3 and will throw \Symfony\Component\Yaml\Exception\ParseException in 4.0. Quote your evaluable mapping keys instead.'), E_USER_DEPRECATED);
  445. }
  446. }
  447. if (':' !== $key && !$isKeyQuoted && (!isset($mapping[$i + 1]) || !\in_array($mapping[$i + 1], array(' ', ',', '[', ']', '{', '}'), true))) {
  448. @trigger_error(self::getDeprecationMessage('Using a colon after an unquoted mapping key that is not followed by an indication character (i.e. " ", ",", "[", "]", "{", "}") is deprecated since Symfony 3.2 and will throw a ParseException in 4.0.'), E_USER_DEPRECATED);
  449. }
  450. if ('<<' === $key) {
  451. $allowOverwrite = true;
  452. }
  453. while ($i < $len) {
  454. if (':' === $mapping[$i] || ' ' === $mapping[$i]) {
  455. ++$i;
  456. continue;
  457. }
  458. $tag = self::parseTag($mapping, $i, $flags);
  459. switch ($mapping[$i]) {
  460. case '[':
  461. // nested sequence
  462. $value = self::parseSequence($mapping, $flags, $i, $references);
  463. // Spec: Keys MUST be unique; first one wins.
  464. // Parser cannot abort this mapping earlier, since lines
  465. // are processed sequentially.
  466. // But overwriting is allowed when a merge node is used in current block.
  467. if ('<<' === $key) {
  468. foreach ($value as $parsedValue) {
  469. $output += $parsedValue;
  470. }
  471. } elseif ($allowOverwrite || !isset($output[$key])) {
  472. if (null !== $tag) {
  473. $output[$key] = new TaggedValue($tag, $value);
  474. } else {
  475. $output[$key] = $value;
  476. }
  477. } elseif (isset($output[$key])) {
  478. @trigger_error(self::getDeprecationMessage(sprintf('Duplicate key "%s" detected whilst parsing YAML. Silent handling of duplicate mapping keys in YAML is deprecated since Symfony 3.2 and will throw \Symfony\Component\Yaml\Exception\ParseException in 4.0.', $key)), E_USER_DEPRECATED);
  479. }
  480. break;
  481. case '{':
  482. // nested mapping
  483. $value = self::parseMapping($mapping, $flags, $i, $references);
  484. // Spec: Keys MUST be unique; first one wins.
  485. // Parser cannot abort this mapping earlier, since lines
  486. // are processed sequentially.
  487. // But overwriting is allowed when a merge node is used in current block.
  488. if ('<<' === $key) {
  489. $output += $value;
  490. } elseif ($allowOverwrite || !isset($output[$key])) {
  491. if (null !== $tag) {
  492. $output[$key] = new TaggedValue($tag, $value);
  493. } else {
  494. $output[$key] = $value;
  495. }
  496. } elseif (isset($output[$key])) {
  497. @trigger_error(self::getDeprecationMessage(sprintf('Duplicate key "%s" detected whilst parsing YAML. Silent handling of duplicate mapping keys in YAML is deprecated since Symfony 3.2 and will throw \Symfony\Component\Yaml\Exception\ParseException in 4.0.', $key)), E_USER_DEPRECATED);
  498. }
  499. break;
  500. default:
  501. $value = self::parseScalar($mapping, $flags, array(',', '}'), $i, null === $tag, $references);
  502. // Spec: Keys MUST be unique; first one wins.
  503. // Parser cannot abort this mapping earlier, since lines
  504. // are processed sequentially.
  505. // But overwriting is allowed when a merge node is used in current block.
  506. if ('<<' === $key) {
  507. $output += $value;
  508. } elseif ($allowOverwrite || !isset($output[$key])) {
  509. if (null !== $tag) {
  510. $output[$key] = new TaggedValue($tag, $value);
  511. } else {
  512. $output[$key] = $value;
  513. }
  514. } elseif (isset($output[$key])) {
  515. @trigger_error(self::getDeprecationMessage(sprintf('Duplicate key "%s" detected whilst parsing YAML. Silent handling of duplicate mapping keys in YAML is deprecated since Symfony 3.2 and will throw \Symfony\Component\Yaml\Exception\ParseException in 4.0.', $key)), E_USER_DEPRECATED);
  516. }
  517. --$i;
  518. }
  519. ++$i;
  520. continue 2;
  521. }
  522. }
  523. throw new ParseException(sprintf('Malformed inline YAML string: %s.', $mapping), self::$parsedLineNumber + 1, null, self::$parsedFilename);
  524. }
  525. /**
  526. * Evaluates scalars and replaces magic values.
  527. *
  528. * @param string $scalar
  529. * @param int $flags
  530. * @param array $references
  531. *
  532. * @return mixed The evaluated YAML string
  533. *
  534. * @throws ParseException when object parsing support was disabled and the parser detected a PHP object or when a reference could not be resolved
  535. */
  536. private static function evaluateScalar($scalar, $flags, $references = array())
  537. {
  538. $scalar = trim($scalar);
  539. $scalarLower = strtolower($scalar);
  540. if (0 === strpos($scalar, '*')) {
  541. if (false !== $pos = strpos($scalar, '#')) {
  542. $value = substr($scalar, 1, $pos - 2);
  543. } else {
  544. $value = substr($scalar, 1);
  545. }
  546. // an unquoted *
  547. if (false === $value || '' === $value) {
  548. throw new ParseException('A reference must contain at least one character.', self::$parsedLineNumber + 1, $value, self::$parsedFilename);
  549. }
  550. if (!array_key_exists($value, $references)) {
  551. throw new ParseException(sprintf('Reference "%s" does not exist.', $value), self::$parsedLineNumber + 1, $value, self::$parsedFilename);
  552. }
  553. return $references[$value];
  554. }
  555. switch (true) {
  556. case 'null' === $scalarLower:
  557. case '' === $scalar:
  558. case '~' === $scalar:
  559. return;
  560. case 'true' === $scalarLower:
  561. return true;
  562. case 'false' === $scalarLower:
  563. return false;
  564. case '!' === $scalar[0]:
  565. switch (true) {
  566. case 0 === strpos($scalar, '!str'):
  567. @trigger_error(self::getDeprecationMessage('Support for the !str tag is deprecated since Symfony 3.4. Use the !!str tag instead.'), E_USER_DEPRECATED);
  568. return (string) substr($scalar, 5);
  569. case 0 === strpos($scalar, '!!str '):
  570. return (string) substr($scalar, 6);
  571. case 0 === strpos($scalar, '! '):
  572. @trigger_error(self::getDeprecationMessage('Using the non-specific tag "!" is deprecated since Symfony 3.4 as its behavior will change in 4.0. It will force non-evaluating your values in 4.0. Use plain integers or !!float instead.'), E_USER_DEPRECATED);
  573. return (int) self::parseScalar(substr($scalar, 2), $flags);
  574. case 0 === strpos($scalar, '!php/object:'):
  575. if (self::$objectSupport) {
  576. @trigger_error(self::getDeprecationMessage('The !php/object: tag to indicate dumped PHP objects is deprecated since Symfony 3.4 and will be removed in 4.0. Use the !php/object (without the colon) tag instead.'), E_USER_DEPRECATED);
  577. return unserialize(substr($scalar, 12));
  578. }
  579. if (self::$exceptionOnInvalidType) {
  580. throw new ParseException('Object support when parsing a YAML file has been disabled.', self::$parsedLineNumber + 1, $scalar, self::$parsedFilename);
  581. }
  582. return;
  583. case 0 === strpos($scalar, '!!php/object:'):
  584. if (self::$objectSupport) {
  585. @trigger_error(self::getDeprecationMessage('The !!php/object: tag to indicate dumped PHP objects is deprecated since Symfony 3.1 and will be removed in 4.0. Use the !php/object (without the colon) tag instead.'), E_USER_DEPRECATED);
  586. return unserialize(substr($scalar, 13));
  587. }
  588. if (self::$exceptionOnInvalidType) {
  589. throw new ParseException('Object support when parsing a YAML file has been disabled.', self::$parsedLineNumber + 1, $scalar, self::$parsedFilename);
  590. }
  591. return;
  592. case 0 === strpos($scalar, '!php/object'):
  593. if (self::$objectSupport) {
  594. return unserialize(self::parseScalar(substr($scalar, 12)));
  595. }
  596. if (self::$exceptionOnInvalidType) {
  597. throw new ParseException('Object support when parsing a YAML file has been disabled.', self::$parsedLineNumber + 1, $scalar, self::$parsedFilename);
  598. }
  599. return;
  600. case 0 === strpos($scalar, '!php/const:'):
  601. if (self::$constantSupport) {
  602. @trigger_error(self::getDeprecationMessage('The !php/const: tag to indicate dumped PHP constants is deprecated since Symfony 3.4 and will be removed in 4.0. Use the !php/const (without the colon) tag instead.'), E_USER_DEPRECATED);
  603. if (\defined($const = substr($scalar, 11))) {
  604. return \constant($const);
  605. }
  606. throw new ParseException(sprintf('The constant "%s" is not defined.', $const), self::$parsedLineNumber + 1, $scalar, self::$parsedFilename);
  607. }
  608. if (self::$exceptionOnInvalidType) {
  609. throw new ParseException(sprintf('The string "%s" could not be parsed as a constant. Have you forgotten to pass the "Yaml::PARSE_CONSTANT" flag to the parser?', $scalar), self::$parsedLineNumber + 1, $scalar, self::$parsedFilename);
  610. }
  611. return;
  612. case 0 === strpos($scalar, '!php/const'):
  613. if (self::$constantSupport) {
  614. $i = 0;
  615. if (\defined($const = self::parseScalar(substr($scalar, 11), 0, null, $i, false))) {
  616. return \constant($const);
  617. }
  618. throw new ParseException(sprintf('The constant "%s" is not defined.', $const), self::$parsedLineNumber + 1, $scalar, self::$parsedFilename);
  619. }
  620. if (self::$exceptionOnInvalidType) {
  621. throw new ParseException(sprintf('The string "%s" could not be parsed as a constant. Have you forgotten to pass the "Yaml::PARSE_CONSTANT" flag to the parser?', $scalar), self::$parsedLineNumber + 1, $scalar, self::$parsedFilename);
  622. }
  623. return;
  624. case 0 === strpos($scalar, '!!float '):
  625. return (float) substr($scalar, 8);
  626. case 0 === strpos($scalar, '!!binary '):
  627. return self::evaluateBinaryScalar(substr($scalar, 9));
  628. default:
  629. @trigger_error(self::getDeprecationMessage(sprintf('Using the unquoted scalar value "%s" is deprecated since Symfony 3.3 and will be considered as a tagged value in 4.0. You must quote it.', $scalar)), E_USER_DEPRECATED);
  630. }
  631. // Optimize for returning strings.
  632. // no break
  633. case '+' === $scalar[0] || '-' === $scalar[0] || '.' === $scalar[0] || is_numeric($scalar[0]):
  634. switch (true) {
  635. case Parser::preg_match('{^[+-]?[0-9][0-9_]*$}', $scalar):
  636. $scalar = str_replace('_', '', (string) $scalar);
  637. // omitting the break / return as integers are handled in the next case
  638. // no break
  639. case ctype_digit($scalar):
  640. $raw = $scalar;
  641. $cast = (int) $scalar;
  642. return '0' == $scalar[0] ? octdec($scalar) : (((string) $raw == (string) $cast) ? $cast : $raw);
  643. case '-' === $scalar[0] && ctype_digit(substr($scalar, 1)):
  644. $raw = $scalar;
  645. $cast = (int) $scalar;
  646. return '0' == $scalar[1] ? octdec($scalar) : (((string) $raw === (string) $cast) ? $cast : $raw);
  647. case is_numeric($scalar):
  648. case Parser::preg_match(self::getHexRegex(), $scalar):
  649. $scalar = str_replace('_', '', $scalar);
  650. return '0x' === $scalar[0].$scalar[1] ? hexdec($scalar) : (float) $scalar;
  651. case '.inf' === $scalarLower:
  652. case '.nan' === $scalarLower:
  653. return -log(0);
  654. case '-.inf' === $scalarLower:
  655. return log(0);
  656. case Parser::preg_match('/^(-|\+)?[0-9][0-9,]*(\.[0-9_]+)?$/', $scalar):
  657. case Parser::preg_match('/^(-|\+)?[0-9][0-9_]*(\.[0-9_]+)?$/', $scalar):
  658. if (false !== strpos($scalar, ',')) {
  659. @trigger_error(self::getDeprecationMessage('Using the comma as a group separator for floats is deprecated since Symfony 3.2 and will be removed in 4.0.'), E_USER_DEPRECATED);
  660. }
  661. return (float) str_replace(array(',', '_'), '', $scalar);
  662. case Parser::preg_match(self::getTimestampRegex(), $scalar):
  663. if (Yaml::PARSE_DATETIME & $flags) {
  664. // When no timezone is provided in the parsed date, YAML spec says we must assume UTC.
  665. return new \DateTime($scalar, new \DateTimeZone('UTC'));
  666. }
  667. $timeZone = date_default_timezone_get();
  668. date_default_timezone_set('UTC');
  669. $time = strtotime($scalar);
  670. date_default_timezone_set($timeZone);
  671. return $time;
  672. }
  673. }
  674. return (string) $scalar;
  675. }
  676. /**
  677. * @param string $value
  678. * @param int &$i
  679. * @param int $flags
  680. *
  681. * @return string|null
  682. */
  683. private static function parseTag($value, &$i, $flags)
  684. {
  685. if ('!' !== $value[$i]) {
  686. return;
  687. }
  688. $tagLength = strcspn($value, " \t\n", $i + 1);
  689. $tag = substr($value, $i + 1, $tagLength);
  690. $nextOffset = $i + $tagLength + 1;
  691. $nextOffset += strspn($value, ' ', $nextOffset);
  692. // Is followed by a scalar
  693. if ((!isset($value[$nextOffset]) || !\in_array($value[$nextOffset], array('[', '{'), true)) && 'tagged' !== $tag) {
  694. // Manage non-whitelisted scalars in {@link self::evaluateScalar()}
  695. return;
  696. }
  697. // Built-in tags
  698. if ($tag && '!' === $tag[0]) {
  699. throw new ParseException(sprintf('The built-in tag "!%s" is not implemented.', $tag), self::$parsedLineNumber + 1, $value, self::$parsedFilename);
  700. }
  701. if (Yaml::PARSE_CUSTOM_TAGS & $flags) {
  702. $i = $nextOffset;
  703. return $tag;
  704. }
  705. throw new ParseException(sprintf('Tags support is not enabled. Enable the `Yaml::PARSE_CUSTOM_TAGS` flag to use "!%s".', $tag), self::$parsedLineNumber + 1, $value, self::$parsedFilename);
  706. }
  707. /**
  708. * @param string $scalar
  709. *
  710. * @return string
  711. *
  712. * @internal
  713. */
  714. public static function evaluateBinaryScalar($scalar)
  715. {
  716. $parsedBinaryData = self::parseScalar(preg_replace('/\s/', '', $scalar));
  717. if (0 !== (\strlen($parsedBinaryData) % 4)) {
  718. throw new ParseException(sprintf('The normalized base64 encoded data (data without whitespace characters) length must be a multiple of four (%d bytes given).', \strlen($parsedBinaryData)), self::$parsedLineNumber + 1, $scalar, self::$parsedFilename);
  719. }
  720. if (!Parser::preg_match('#^[A-Z0-9+/]+={0,2}$#i', $parsedBinaryData)) {
  721. throw new ParseException(sprintf('The base64 encoded data (%s) contains invalid characters.', $parsedBinaryData), self::$parsedLineNumber + 1, $scalar, self::$parsedFilename);
  722. }
  723. return base64_decode($parsedBinaryData, true);
  724. }
  725. private static function isBinaryString($value)
  726. {
  727. return !preg_match('//u', $value) || preg_match('/[^\x00\x07-\x0d\x1B\x20-\xff]/', $value);
  728. }
  729. /**
  730. * Gets a regex that matches a YAML date.
  731. *
  732. * @return string The regular expression
  733. *
  734. * @see http://www.yaml.org/spec/1.2/spec.html#id2761573
  735. */
  736. private static function getTimestampRegex()
  737. {
  738. return <<<EOF
  739. ~^
  740. (?P<year>[0-9][0-9][0-9][0-9])
  741. -(?P<month>[0-9][0-9]?)
  742. -(?P<day>[0-9][0-9]?)
  743. (?:(?:[Tt]|[ \t]+)
  744. (?P<hour>[0-9][0-9]?)
  745. :(?P<minute>[0-9][0-9])
  746. :(?P<second>[0-9][0-9])
  747. (?:\.(?P<fraction>[0-9]*))?
  748. (?:[ \t]*(?P<tz>Z|(?P<tz_sign>[-+])(?P<tz_hour>[0-9][0-9]?)
  749. (?::(?P<tz_minute>[0-9][0-9]))?))?)?
  750. $~x
  751. EOF;
  752. }
  753. /**
  754. * Gets a regex that matches a YAML number in hexadecimal notation.
  755. *
  756. * @return string
  757. */
  758. private static function getHexRegex()
  759. {
  760. return '~^0x[0-9a-f_]++$~i';
  761. }
  762. private static function getDeprecationMessage($message)
  763. {
  764. $message = rtrim($message, '.');
  765. if (null !== self::$parsedFilename) {
  766. $message .= ' in '.self::$parsedFilename;
  767. }
  768. if (-1 !== self::$parsedLineNumber) {
  769. $message .= ' on line '.(self::$parsedLineNumber + 1);
  770. }
  771. return $message.'.';
  772. }
  773. }