Inline.php 32 KB

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