Inline.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728
  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. /**
  14. * Inline implements a YAML parser/dumper for the YAML inline syntax.
  15. *
  16. * @author Fabien Potencier <fabien@symfony.com>
  17. *
  18. * @internal
  19. */
  20. class Inline
  21. {
  22. const REGEX_QUOTED_STRING = '(?:"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"|\'([^\']*(?:\'\'[^\']*)*)\')';
  23. public static $parsedLineNumber;
  24. private static $exceptionOnInvalidType = false;
  25. private static $objectSupport = false;
  26. private static $objectForMap = false;
  27. private static $constantSupport = false;
  28. /**
  29. * Converts a YAML string to a PHP value.
  30. *
  31. * @param string $value A YAML string
  32. * @param int $flags A bit field of PARSE_* constants to customize the YAML parser behavior
  33. * @param array $references Mapping of variable names to values
  34. *
  35. * @return mixed A PHP value
  36. *
  37. * @throws ParseException
  38. */
  39. public static function parse($value, $flags = 0, $references = array())
  40. {
  41. if (is_bool($flags)) {
  42. @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);
  43. if ($flags) {
  44. $flags = Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE;
  45. } else {
  46. $flags = 0;
  47. }
  48. }
  49. if (func_num_args() >= 3 && !is_array($references)) {
  50. @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);
  51. if ($references) {
  52. $flags |= Yaml::PARSE_OBJECT;
  53. }
  54. if (func_num_args() >= 4) {
  55. @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);
  56. if (func_get_arg(3)) {
  57. $flags |= Yaml::PARSE_OBJECT_FOR_MAP;
  58. }
  59. }
  60. if (func_num_args() >= 5) {
  61. $references = func_get_arg(4);
  62. } else {
  63. $references = array();
  64. }
  65. }
  66. self::$exceptionOnInvalidType = (bool) (Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE & $flags);
  67. self::$objectSupport = (bool) (Yaml::PARSE_OBJECT & $flags);
  68. self::$objectForMap = (bool) (Yaml::PARSE_OBJECT_FOR_MAP & $flags);
  69. self::$constantSupport = (bool) (Yaml::PARSE_CONSTANT & $flags);
  70. $value = trim($value);
  71. if ('' === $value) {
  72. return '';
  73. }
  74. if (2 /* MB_OVERLOAD_STRING */ & (int) ini_get('mbstring.func_overload')) {
  75. $mbEncoding = mb_internal_encoding();
  76. mb_internal_encoding('ASCII');
  77. }
  78. $i = 0;
  79. switch ($value[0]) {
  80. case '[':
  81. $result = self::parseSequence($value, $flags, $i, $references);
  82. ++$i;
  83. break;
  84. case '{':
  85. $result = self::parseMapping($value, $flags, $i, $references);
  86. ++$i;
  87. break;
  88. default:
  89. $result = self::parseScalar($value, $flags, null, array('"', "'"), $i, true, $references);
  90. }
  91. // some comments are allowed at the end
  92. if (preg_replace('/\s+#.*$/A', '', substr($value, $i))) {
  93. throw new ParseException(sprintf('Unexpected characters near "%s".', substr($value, $i)));
  94. }
  95. if (isset($mbEncoding)) {
  96. mb_internal_encoding($mbEncoding);
  97. }
  98. return $result;
  99. }
  100. /**
  101. * Dumps a given PHP variable to a YAML string.
  102. *
  103. * @param mixed $value The PHP variable to convert
  104. * @param int $flags A bit field of Yaml::DUMP_* constants to customize the dumped YAML string
  105. *
  106. * @return string The YAML string representing the PHP value
  107. *
  108. * @throws DumpException When trying to dump PHP resource
  109. */
  110. public static function dump($value, $flags = 0)
  111. {
  112. if (is_bool($flags)) {
  113. @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);
  114. if ($flags) {
  115. $flags = Yaml::DUMP_EXCEPTION_ON_INVALID_TYPE;
  116. } else {
  117. $flags = 0;
  118. }
  119. }
  120. if (func_num_args() >= 3) {
  121. @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);
  122. if (func_get_arg(2)) {
  123. $flags |= Yaml::DUMP_OBJECT;
  124. }
  125. }
  126. switch (true) {
  127. case is_resource($value):
  128. if (Yaml::DUMP_EXCEPTION_ON_INVALID_TYPE & $flags) {
  129. throw new DumpException(sprintf('Unable to dump PHP resources in a YAML file ("%s").', get_resource_type($value)));
  130. }
  131. return 'null';
  132. case $value instanceof \DateTimeInterface:
  133. return $value->format('c');
  134. case is_object($value):
  135. if (Yaml::DUMP_OBJECT & $flags) {
  136. return '!php/object:'.serialize($value);
  137. }
  138. if (Yaml::DUMP_OBJECT_AS_MAP & $flags && ($value instanceof \stdClass || $value instanceof \ArrayObject)) {
  139. return self::dumpArray((array) $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 'null';
  145. case is_array($value):
  146. return self::dumpArray($value, $flags);
  147. case null === $value:
  148. return 'null';
  149. case true === $value:
  150. return 'true';
  151. case false === $value:
  152. return 'false';
  153. case ctype_digit($value):
  154. return is_string($value) ? "'$value'" : (int) $value;
  155. case is_numeric($value):
  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. $repr = '!!float '.$repr;
  167. }
  168. } else {
  169. $repr = is_string($value) ? "'$value'" : (string) $value;
  170. }
  171. if (false !== $locale) {
  172. setlocale(LC_NUMERIC, $locale);
  173. }
  174. return $repr;
  175. case '' == $value:
  176. return "''";
  177. case self::isBinaryString($value):
  178. return '!!binary '.base64_encode($value);
  179. case Escaper::requiresDoubleQuoting($value):
  180. return Escaper::escapeWithDoubleQuotes($value);
  181. case Escaper::requiresSingleQuoting($value):
  182. case preg_match('{^[0-9]+[_0-9]*$}', $value):
  183. case preg_match(self::getHexRegex(), $value):
  184. case preg_match(self::getTimestampRegex(), $value):
  185. return Escaper::escapeWithSingleQuotes($value);
  186. default:
  187. return $value;
  188. }
  189. }
  190. /**
  191. * Check if given array is hash or just normal indexed array.
  192. *
  193. * @internal
  194. *
  195. * @param array $value The PHP array to check
  196. *
  197. * @return bool true if value is hash array, false otherwise
  198. */
  199. public static function isHash(array $value)
  200. {
  201. $expectedKey = 0;
  202. foreach ($value as $key => $val) {
  203. if ($key !== $expectedKey++) {
  204. return true;
  205. }
  206. }
  207. return false;
  208. }
  209. /**
  210. * Dumps a PHP array to a YAML string.
  211. *
  212. * @param array $value The PHP array to dump
  213. * @param int $flags A bit field of Yaml::DUMP_* constants to customize the dumped YAML string
  214. *
  215. * @return string The YAML string representing the PHP array
  216. */
  217. private static function dumpArray($value, $flags)
  218. {
  219. // array
  220. if ($value && !self::isHash($value)) {
  221. $output = array();
  222. foreach ($value as $val) {
  223. $output[] = self::dump($val, $flags);
  224. }
  225. return sprintf('[%s]', implode(', ', $output));
  226. }
  227. // hash
  228. $output = array();
  229. foreach ($value as $key => $val) {
  230. $output[] = sprintf('%s: %s', self::dump($key, $flags), self::dump($val, $flags));
  231. }
  232. return sprintf('{ %s }', implode(', ', $output));
  233. }
  234. /**
  235. * Parses a YAML scalar.
  236. *
  237. * @param string $scalar
  238. * @param int $flags
  239. * @param string $delimiters
  240. * @param array $stringDelimiters
  241. * @param int &$i
  242. * @param bool $evaluate
  243. * @param array $references
  244. *
  245. * @return string
  246. *
  247. * @throws ParseException When malformed inline YAML string is parsed
  248. *
  249. * @internal
  250. */
  251. public static function parseScalar($scalar, $flags = 0, $delimiters = null, $stringDelimiters = array('"', "'"), &$i = 0, $evaluate = true, $references = array())
  252. {
  253. if (in_array($scalar[$i], $stringDelimiters)) {
  254. // quoted scalar
  255. $output = self::parseQuotedScalar($scalar, $i);
  256. if (null !== $delimiters) {
  257. $tmp = ltrim(substr($scalar, $i), ' ');
  258. if (!in_array($tmp[0], $delimiters)) {
  259. throw new ParseException(sprintf('Unexpected characters (%s).', substr($scalar, $i)));
  260. }
  261. }
  262. } else {
  263. // "normal" string
  264. if (!$delimiters) {
  265. $output = substr($scalar, $i);
  266. $i += strlen($output);
  267. // remove comments
  268. if (preg_match('/[ \t]+#/', $output, $match, PREG_OFFSET_CAPTURE)) {
  269. $output = substr($output, 0, $match[0][1]);
  270. }
  271. } elseif (preg_match('/^(.+?)('.implode('|', $delimiters).')/', substr($scalar, $i), $match)) {
  272. $output = $match[1];
  273. $i += strlen($output);
  274. } else {
  275. throw new ParseException(sprintf('Malformed inline YAML string: %s.', $scalar));
  276. }
  277. // a non-quoted string cannot start with @ or ` (reserved) nor with a scalar indicator (| or >)
  278. if ($output && ('@' === $output[0] || '`' === $output[0] || '|' === $output[0] || '>' === $output[0])) {
  279. throw new ParseException(sprintf('The reserved indicator "%s" cannot start a plain scalar; you need to quote the scalar.', $output[0]));
  280. }
  281. if ($output && '%' === $output[0]) {
  282. @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);
  283. }
  284. if ($evaluate) {
  285. $output = self::evaluateScalar($output, $flags, $references);
  286. }
  287. }
  288. return $output;
  289. }
  290. /**
  291. * Parses a YAML quoted scalar.
  292. *
  293. * @param string $scalar
  294. * @param int &$i
  295. *
  296. * @return string
  297. *
  298. * @throws ParseException When malformed inline YAML string is parsed
  299. */
  300. private static function parseQuotedScalar($scalar, &$i)
  301. {
  302. if (!preg_match('/'.self::REGEX_QUOTED_STRING.'/Au', substr($scalar, $i), $match)) {
  303. throw new ParseException(sprintf('Malformed inline YAML string: %s.', substr($scalar, $i)));
  304. }
  305. $output = substr($match[0], 1, strlen($match[0]) - 2);
  306. $unescaper = new Unescaper();
  307. if ('"' == $scalar[$i]) {
  308. $output = $unescaper->unescapeDoubleQuotedString($output);
  309. } else {
  310. $output = $unescaper->unescapeSingleQuotedString($output);
  311. }
  312. $i += strlen($match[0]);
  313. return $output;
  314. }
  315. /**
  316. * Parses a YAML sequence.
  317. *
  318. * @param string $sequence
  319. * @param int $flags
  320. * @param int &$i
  321. * @param array $references
  322. *
  323. * @return array
  324. *
  325. * @throws ParseException When malformed inline YAML string is parsed
  326. */
  327. private static function parseSequence($sequence, $flags, &$i = 0, $references = array())
  328. {
  329. $output = array();
  330. $len = strlen($sequence);
  331. ++$i;
  332. // [foo, bar, ...]
  333. while ($i < $len) {
  334. switch ($sequence[$i]) {
  335. case '[':
  336. // nested sequence
  337. $output[] = self::parseSequence($sequence, $flags, $i, $references);
  338. break;
  339. case '{':
  340. // nested mapping
  341. $output[] = self::parseMapping($sequence, $flags, $i, $references);
  342. break;
  343. case ']':
  344. return $output;
  345. case ',':
  346. case ' ':
  347. break;
  348. default:
  349. $isQuoted = in_array($sequence[$i], array('"', "'"));
  350. $value = self::parseScalar($sequence, $flags, array(',', ']'), array('"', "'"), $i, true, $references);
  351. // the value can be an array if a reference has been resolved to an array var
  352. if (is_string($value) && !$isQuoted && false !== strpos($value, ': ')) {
  353. // embedded mapping?
  354. try {
  355. $pos = 0;
  356. $value = self::parseMapping('{'.$value.'}', $flags, $pos, $references);
  357. } catch (\InvalidArgumentException $e) {
  358. // no, it's not
  359. }
  360. }
  361. $output[] = $value;
  362. --$i;
  363. }
  364. ++$i;
  365. }
  366. throw new ParseException(sprintf('Malformed inline YAML string: %s.', $sequence));
  367. }
  368. /**
  369. * Parses a YAML mapping.
  370. *
  371. * @param string $mapping
  372. * @param int $flags
  373. * @param int &$i
  374. * @param array $references
  375. *
  376. * @return array|\stdClass
  377. *
  378. * @throws ParseException When malformed inline YAML string is parsed
  379. */
  380. private static function parseMapping($mapping, $flags, &$i = 0, $references = array())
  381. {
  382. $output = array();
  383. $len = strlen($mapping);
  384. ++$i;
  385. // {foo: bar, bar:foo, ...}
  386. while ($i < $len) {
  387. switch ($mapping[$i]) {
  388. case ' ':
  389. case ',':
  390. ++$i;
  391. continue 2;
  392. case '}':
  393. if (self::$objectForMap) {
  394. return (object) $output;
  395. }
  396. return $output;
  397. }
  398. // key
  399. $key = self::parseScalar($mapping, $flags, array(':', ' '), array('"', "'"), $i, false);
  400. if (false === $i = strpos($mapping, ':', $i)) {
  401. break;
  402. }
  403. if (!isset($mapping[$i + 1]) || !in_array($mapping[$i + 1], array(' ', ',', '[', ']', '{', '}'), true)) {
  404. @trigger_error('Using a colon 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);
  405. }
  406. // value
  407. $done = false;
  408. while ($i < $len) {
  409. switch ($mapping[$i]) {
  410. case '[':
  411. // nested sequence
  412. $value = self::parseSequence($mapping, $flags, $i, $references);
  413. // Spec: Keys MUST be unique; first one wins.
  414. // Parser cannot abort this mapping earlier, since lines
  415. // are processed sequentially.
  416. if (!isset($output[$key])) {
  417. $output[$key] = $value;
  418. } else {
  419. @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);
  420. }
  421. $done = true;
  422. break;
  423. case '{':
  424. // nested mapping
  425. $value = self::parseMapping($mapping, $flags, $i, $references);
  426. // Spec: Keys MUST be unique; first one wins.
  427. // Parser cannot abort this mapping earlier, since lines
  428. // are processed sequentially.
  429. if (!isset($output[$key])) {
  430. $output[$key] = $value;
  431. } else {
  432. @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);
  433. }
  434. $done = true;
  435. break;
  436. case ':':
  437. case ' ':
  438. break;
  439. default:
  440. $value = self::parseScalar($mapping, $flags, array(',', '}'), array('"', "'"), $i, true, $references);
  441. // Spec: Keys MUST be unique; first one wins.
  442. // Parser cannot abort this mapping earlier, since lines
  443. // are processed sequentially.
  444. if (!isset($output[$key])) {
  445. $output[$key] = $value;
  446. } else {
  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. }
  449. $done = true;
  450. --$i;
  451. }
  452. ++$i;
  453. if ($done) {
  454. continue 2;
  455. }
  456. }
  457. }
  458. throw new ParseException(sprintf('Malformed inline YAML string: %s.', $mapping));
  459. }
  460. /**
  461. * Evaluates scalars and replaces magic values.
  462. *
  463. * @param string $scalar
  464. * @param int $flags
  465. * @param array $references
  466. *
  467. * @return string A 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($scalar, $flags, $references = array())
  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.');
  484. }
  485. if (!array_key_exists($value, $references)) {
  486. throw new ParseException(sprintf('Reference "%s" does not exist.', $value));
  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. // Optimise for returning strings.
  500. case $scalar[0] === '+' || $scalar[0] === '-' || $scalar[0] === '.' || $scalar[0] === '!' || is_numeric($scalar[0]):
  501. switch (true) {
  502. case 0 === strpos($scalar, '!str'):
  503. return (string) substr($scalar, 5);
  504. case 0 === strpos($scalar, '! '):
  505. return (int) self::parseScalar(substr($scalar, 2), $flags);
  506. case 0 === strpos($scalar, '!php/object:'):
  507. if (self::$objectSupport) {
  508. return unserialize(substr($scalar, 12));
  509. }
  510. if (self::$exceptionOnInvalidType) {
  511. throw new ParseException('Object support when parsing a YAML file has been disabled.');
  512. }
  513. return;
  514. case 0 === strpos($scalar, '!!php/object:'):
  515. if (self::$objectSupport) {
  516. @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);
  517. return unserialize(substr($scalar, 13));
  518. }
  519. if (self::$exceptionOnInvalidType) {
  520. throw new ParseException('Object support when parsing a YAML file has been disabled.');
  521. }
  522. return;
  523. case 0 === strpos($scalar, '!php/const:'):
  524. if (self::$constantSupport) {
  525. if (defined($const = substr($scalar, 11))) {
  526. return constant($const);
  527. }
  528. throw new ParseException(sprintf('The constant "%s" is not defined.', $const));
  529. }
  530. if (self::$exceptionOnInvalidType) {
  531. 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));
  532. }
  533. return;
  534. case 0 === strpos($scalar, '!!float '):
  535. return (float) substr($scalar, 8);
  536. case 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. case ctype_digit($scalar):
  540. $raw = $scalar;
  541. $cast = (int) $scalar;
  542. return '0' == $scalar[0] ? octdec($scalar) : (((string) $raw == (string) $cast) ? $cast : $raw);
  543. case '-' === $scalar[0] && ctype_digit(substr($scalar, 1)):
  544. $raw = $scalar;
  545. $cast = (int) $scalar;
  546. return '0' == $scalar[1] ? octdec($scalar) : (((string) $raw === (string) $cast) ? $cast : $raw);
  547. case is_numeric($scalar):
  548. case preg_match(self::getHexRegex(), $scalar):
  549. $scalar = str_replace('_', '', $scalar);
  550. return '0x' === $scalar[0].$scalar[1] ? hexdec($scalar) : (float) $scalar;
  551. case '.inf' === $scalarLower:
  552. case '.nan' === $scalarLower:
  553. return -log(0);
  554. case '-.inf' === $scalarLower:
  555. return log(0);
  556. case 0 === strpos($scalar, '!!binary '):
  557. return self::evaluateBinaryScalar(substr($scalar, 9));
  558. case preg_match('/^(-|\+)?[0-9][0-9,]*(\.[0-9_]+)?$/', $scalar):
  559. case preg_match('/^(-|\+)?[0-9][0-9_]*(\.[0-9_]+)?$/', $scalar):
  560. if (false !== strpos($scalar, ',')) {
  561. @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);
  562. }
  563. return (float) str_replace(array(',', '_'), '', $scalar);
  564. case preg_match(self::getTimestampRegex(), $scalar):
  565. if (Yaml::PARSE_DATETIME & $flags) {
  566. // When no timezone is provided in the parsed date, YAML spec says we must assume UTC.
  567. return new \DateTime($scalar, new \DateTimeZone('UTC'));
  568. }
  569. $timeZone = date_default_timezone_get();
  570. date_default_timezone_set('UTC');
  571. $time = strtotime($scalar);
  572. date_default_timezone_set($timeZone);
  573. return $time;
  574. }
  575. default:
  576. return (string) $scalar;
  577. }
  578. }
  579. /**
  580. * @param string $scalar
  581. *
  582. * @return string
  583. *
  584. * @internal
  585. */
  586. public static function evaluateBinaryScalar($scalar)
  587. {
  588. $parsedBinaryData = self::parseScalar(preg_replace('/\s/', '', $scalar));
  589. if (0 !== (strlen($parsedBinaryData) % 4)) {
  590. 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)));
  591. }
  592. if (!preg_match('#^[A-Z0-9+/]+={0,2}$#i', $parsedBinaryData)) {
  593. throw new ParseException(sprintf('The base64 encoded data (%s) contains invalid characters.', $parsedBinaryData));
  594. }
  595. return base64_decode($parsedBinaryData, true);
  596. }
  597. private static function isBinaryString($value)
  598. {
  599. return !preg_match('//u', $value) || preg_match('/[^\x09-\x0d\x20-\xff]/', $value);
  600. }
  601. /**
  602. * Gets a regex that matches a YAML date.
  603. *
  604. * @return string The regular expression
  605. *
  606. * @see http://www.yaml.org/spec/1.2/spec.html#id2761573
  607. */
  608. private static function getTimestampRegex()
  609. {
  610. return <<<EOF
  611. ~^
  612. (?P<year>[0-9][0-9][0-9][0-9])
  613. -(?P<month>[0-9][0-9]?)
  614. -(?P<day>[0-9][0-9]?)
  615. (?:(?:[Tt]|[ \t]+)
  616. (?P<hour>[0-9][0-9]?)
  617. :(?P<minute>[0-9][0-9])
  618. :(?P<second>[0-9][0-9])
  619. (?:\.(?P<fraction>[0-9]*))?
  620. (?:[ \t]*(?P<tz>Z|(?P<tz_sign>[-+])(?P<tz_hour>[0-9][0-9]?)
  621. (?::(?P<tz_minute>[0-9][0-9]))?))?)?
  622. $~x
  623. EOF;
  624. }
  625. /**
  626. * Gets a regex that matches a YAML number in hexadecimal notation.
  627. *
  628. * @return string
  629. */
  630. private static function getHexRegex()
  631. {
  632. return '~^0x[0-9a-f_]++$~i';
  633. }
  634. }