Inline.php 35 KB

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