vendor/symfony/yaml/Inline.php line 314

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