Inline.php 37 KB

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