Inline.php 31 KB

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