Inline.php 32 KB

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