Inline.php 29 KB

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