Inline.php 29 KB

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