Inline.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  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. class Inline
  19. {
  20. const REGEX_QUOTED_STRING = '(?:"([^"\\\\]*+(?:\\\\.[^"\\\\]*+)*+)"|\'([^\']*+(?:\'\'[^\']*+)*+)\')';
  21. private static $exceptionOnInvalidType = false;
  22. private static $objectSupport = false;
  23. private static $objectForMap = false;
  24. /**
  25. * Converts a YAML string to a PHP value.
  26. *
  27. * @param string $value A YAML string
  28. * @param bool $exceptionOnInvalidType True if an exception must be thrown on invalid types (a PHP resource or object), false otherwise
  29. * @param bool $objectSupport True if object support is enabled, false otherwise
  30. * @param bool $objectForMap True if maps should return a stdClass instead of array()
  31. * @param array $references Mapping of variable names to values
  32. *
  33. * @return mixed A PHP value
  34. *
  35. * @throws ParseException
  36. */
  37. public static function parse($value, $exceptionOnInvalidType = false, $objectSupport = false, $objectForMap = false, $references = array())
  38. {
  39. self::$exceptionOnInvalidType = $exceptionOnInvalidType;
  40. self::$objectSupport = $objectSupport;
  41. self::$objectForMap = $objectForMap;
  42. $value = trim($value);
  43. if ('' === $value) {
  44. return '';
  45. }
  46. if (2 /* MB_OVERLOAD_STRING */ & (int) ini_get('mbstring.func_overload')) {
  47. $mbEncoding = mb_internal_encoding();
  48. mb_internal_encoding('ASCII');
  49. }
  50. $i = 0;
  51. switch ($value[0]) {
  52. case '[':
  53. $result = self::parseSequence($value, $i, $references);
  54. ++$i;
  55. break;
  56. case '{':
  57. $result = self::parseMapping($value, $i, $references);
  58. ++$i;
  59. break;
  60. default:
  61. $result = self::parseScalar($value, null, array('"', "'"), $i, true, $references);
  62. }
  63. // some comments are allowed at the end
  64. if (preg_replace('/\s+#.*$/A', '', substr($value, $i))) {
  65. throw new ParseException(sprintf('Unexpected characters near "%s".', substr($value, $i)));
  66. }
  67. if (isset($mbEncoding)) {
  68. mb_internal_encoding($mbEncoding);
  69. }
  70. return $result;
  71. }
  72. /**
  73. * Dumps a given PHP variable to a YAML string.
  74. *
  75. * @param mixed $value The PHP variable to convert
  76. * @param bool $exceptionOnInvalidType True if an exception must be thrown on invalid types (a PHP resource or object), false otherwise
  77. * @param bool $objectSupport True if object support is enabled, false otherwise
  78. *
  79. * @return string The YAML string representing the PHP value
  80. *
  81. * @throws DumpException When trying to dump PHP resource
  82. */
  83. public static function dump($value, $exceptionOnInvalidType = false, $objectSupport = false)
  84. {
  85. switch (true) {
  86. case is_resource($value):
  87. if ($exceptionOnInvalidType) {
  88. throw new DumpException(sprintf('Unable to dump PHP resources in a YAML file ("%s").', get_resource_type($value)));
  89. }
  90. return 'null';
  91. case is_object($value):
  92. if ($objectSupport) {
  93. return '!php/object:'.serialize($value);
  94. }
  95. if ($exceptionOnInvalidType) {
  96. throw new DumpException('Object support when dumping a YAML file has been disabled.');
  97. }
  98. return 'null';
  99. case is_array($value):
  100. return self::dumpArray($value, $exceptionOnInvalidType, $objectSupport);
  101. case null === $value:
  102. return 'null';
  103. case true === $value:
  104. return 'true';
  105. case false === $value:
  106. return 'false';
  107. case ctype_digit($value):
  108. return is_string($value) ? "'$value'" : (int) $value;
  109. case is_numeric($value):
  110. $locale = setlocale(LC_NUMERIC, 0);
  111. if (false !== $locale) {
  112. setlocale(LC_NUMERIC, 'C');
  113. }
  114. if (is_float($value)) {
  115. $repr = (string) $value;
  116. if (is_infinite($value)) {
  117. $repr = str_ireplace('INF', '.Inf', $repr);
  118. } elseif (floor($value) == $value && $repr == $value) {
  119. // Preserve float data type since storing a whole number will result in integer value.
  120. $repr = '!!float '.$repr;
  121. }
  122. } else {
  123. $repr = is_string($value) ? "'$value'" : (string) $value;
  124. }
  125. if (false !== $locale) {
  126. setlocale(LC_NUMERIC, $locale);
  127. }
  128. return $repr;
  129. case '' == $value:
  130. return "''";
  131. case Escaper::requiresDoubleQuoting($value):
  132. return Escaper::escapeWithDoubleQuotes($value);
  133. case Escaper::requiresSingleQuoting($value):
  134. case Parser::preg_match(self::getHexRegex(), $value):
  135. case Parser::preg_match(self::getTimestampRegex(), $value):
  136. return Escaper::escapeWithSingleQuotes($value);
  137. default:
  138. return $value;
  139. }
  140. }
  141. /**
  142. * Check if given array is hash or just normal indexed array.
  143. *
  144. * @internal
  145. *
  146. * @param array $value The PHP array to check
  147. *
  148. * @return bool true if value is hash array, false otherwise
  149. */
  150. public static function isHash(array $value)
  151. {
  152. $expectedKey = 0;
  153. foreach ($value as $key => $val) {
  154. if ($key !== $expectedKey++) {
  155. return true;
  156. }
  157. }
  158. return false;
  159. }
  160. /**
  161. * Dumps a PHP array to a YAML string.
  162. *
  163. * @param array $value The PHP array to dump
  164. * @param bool $exceptionOnInvalidType True if an exception must be thrown on invalid types (a PHP resource or object), false otherwise
  165. * @param bool $objectSupport True if object support is enabled, false otherwise
  166. *
  167. * @return string The YAML string representing the PHP array
  168. */
  169. private static function dumpArray($value, $exceptionOnInvalidType, $objectSupport)
  170. {
  171. // array
  172. if ($value && !self::isHash($value)) {
  173. $output = array();
  174. foreach ($value as $val) {
  175. $output[] = self::dump($val, $exceptionOnInvalidType, $objectSupport);
  176. }
  177. return sprintf('[%s]', implode(', ', $output));
  178. }
  179. // hash
  180. $output = array();
  181. foreach ($value as $key => $val) {
  182. $output[] = sprintf('%s: %s', self::dump($key, $exceptionOnInvalidType, $objectSupport), self::dump($val, $exceptionOnInvalidType, $objectSupport));
  183. }
  184. return sprintf('{ %s }', implode(', ', $output));
  185. }
  186. /**
  187. * Parses a YAML scalar.
  188. *
  189. * @param string $scalar
  190. * @param string[] $delimiters
  191. * @param string[] $stringDelimiters
  192. * @param int &$i
  193. * @param bool $evaluate
  194. * @param array $references
  195. *
  196. * @return string
  197. *
  198. * @throws ParseException When malformed inline YAML string is parsed
  199. *
  200. * @internal
  201. */
  202. public static function parseScalar($scalar, $delimiters = null, $stringDelimiters = array('"', "'"), &$i = 0, $evaluate = true, $references = array())
  203. {
  204. if (in_array($scalar[$i], $stringDelimiters)) {
  205. // quoted scalar
  206. $output = self::parseQuotedScalar($scalar, $i);
  207. if (null !== $delimiters) {
  208. $tmp = ltrim(substr($scalar, $i), ' ');
  209. if ('' === $tmp) {
  210. throw new ParseException(sprintf('Unexpected end of line, expected one of "%s".', implode($delimiters)));
  211. }
  212. if (!in_array($tmp[0], $delimiters)) {
  213. throw new ParseException(sprintf('Unexpected characters (%s).', substr($scalar, $i)));
  214. }
  215. }
  216. } else {
  217. // "normal" string
  218. if (!$delimiters) {
  219. $output = substr($scalar, $i);
  220. $i += strlen($output);
  221. // remove comments
  222. if (Parser::preg_match('/[ \t]+#/', $output, $match, PREG_OFFSET_CAPTURE)) {
  223. $output = substr($output, 0, $match[0][1]);
  224. }
  225. } elseif (Parser::preg_match('/^(.+?)('.implode('|', $delimiters).')/', substr($scalar, $i), $match)) {
  226. $output = $match[1];
  227. $i += strlen($output);
  228. } else {
  229. throw new ParseException(sprintf('Malformed inline YAML string: %s.', $scalar));
  230. }
  231. // a non-quoted string cannot start with @ or ` (reserved) nor with a scalar indicator (| or >)
  232. if ($output && ('@' === $output[0] || '`' === $output[0] || '|' === $output[0] || '>' === $output[0])) {
  233. @trigger_error(sprintf('Not quoting the scalar "%s" starting with "%s" is deprecated since Symfony 2.8 and will throw a ParseException in 3.0.', $output, $output[0]), E_USER_DEPRECATED);
  234. // to be thrown in 3.0
  235. // throw new ParseException(sprintf('The reserved indicator "%s" cannot start a plain scalar; you need to quote the scalar.', $output[0]));
  236. }
  237. if ($evaluate) {
  238. $output = self::evaluateScalar($output, $references);
  239. }
  240. }
  241. return $output;
  242. }
  243. /**
  244. * Parses a YAML quoted scalar.
  245. *
  246. * @param string $scalar
  247. * @param int &$i
  248. *
  249. * @return string
  250. *
  251. * @throws ParseException When malformed inline YAML string is parsed
  252. */
  253. private static function parseQuotedScalar($scalar, &$i)
  254. {
  255. if (!Parser::preg_match('/'.self::REGEX_QUOTED_STRING.'/Au', substr($scalar, $i), $match)) {
  256. throw new ParseException(sprintf('Malformed inline YAML string: %s.', substr($scalar, $i)));
  257. }
  258. $output = substr($match[0], 1, strlen($match[0]) - 2);
  259. $unescaper = new Unescaper();
  260. if ('"' == $scalar[$i]) {
  261. $output = $unescaper->unescapeDoubleQuotedString($output);
  262. } else {
  263. $output = $unescaper->unescapeSingleQuotedString($output);
  264. }
  265. $i += strlen($match[0]);
  266. return $output;
  267. }
  268. /**
  269. * Parses a YAML sequence.
  270. *
  271. * @param string $sequence
  272. * @param int &$i
  273. * @param array $references
  274. *
  275. * @return array
  276. *
  277. * @throws ParseException When malformed inline YAML string is parsed
  278. */
  279. private static function parseSequence($sequence, &$i = 0, $references = array())
  280. {
  281. $output = array();
  282. $len = strlen($sequence);
  283. ++$i;
  284. // [foo, bar, ...]
  285. while ($i < $len) {
  286. switch ($sequence[$i]) {
  287. case '[':
  288. // nested sequence
  289. $output[] = self::parseSequence($sequence, $i, $references);
  290. break;
  291. case '{':
  292. // nested mapping
  293. $output[] = self::parseMapping($sequence, $i, $references);
  294. break;
  295. case ']':
  296. return $output;
  297. case ',':
  298. case ' ':
  299. break;
  300. default:
  301. $isQuoted = in_array($sequence[$i], array('"', "'"));
  302. $value = self::parseScalar($sequence, array(',', ']'), array('"', "'"), $i, true, $references);
  303. // the value can be an array if a reference has been resolved to an array var
  304. if (!is_array($value) && !$isQuoted && false !== strpos($value, ': ')) {
  305. // embedded mapping?
  306. try {
  307. $pos = 0;
  308. $value = self::parseMapping('{'.$value.'}', $pos, $references);
  309. } catch (\InvalidArgumentException $e) {
  310. // no, it's not
  311. }
  312. }
  313. $output[] = $value;
  314. --$i;
  315. }
  316. ++$i;
  317. }
  318. throw new ParseException(sprintf('Malformed inline YAML string: %s.', $sequence));
  319. }
  320. /**
  321. * Parses a YAML mapping.
  322. *
  323. * @param string $mapping
  324. * @param int &$i
  325. * @param array $references
  326. *
  327. * @return array|\stdClass
  328. *
  329. * @throws ParseException When malformed inline YAML string is parsed
  330. */
  331. private static function parseMapping($mapping, &$i = 0, $references = array())
  332. {
  333. $output = array();
  334. $len = strlen($mapping);
  335. ++$i;
  336. $allowOverwrite = false;
  337. // {foo: bar, bar:foo, ...}
  338. while ($i < $len) {
  339. switch ($mapping[$i]) {
  340. case ' ':
  341. case ',':
  342. ++$i;
  343. continue 2;
  344. case '}':
  345. if (self::$objectForMap) {
  346. return (object) $output;
  347. }
  348. return $output;
  349. }
  350. // key
  351. $key = self::parseScalar($mapping, array(':', ' '), array('"', "'"), $i, false);
  352. if ('<<' === $key) {
  353. $allowOverwrite = true;
  354. }
  355. // value
  356. $done = false;
  357. while ($i < $len) {
  358. switch ($mapping[$i]) {
  359. case '[':
  360. // nested sequence
  361. $value = self::parseSequence($mapping, $i, $references);
  362. // Spec: Keys MUST be unique; first one wins.
  363. // Parser cannot abort this mapping earlier, since lines
  364. // are processed sequentially.
  365. // But overwriting is allowed when a merge node is used in current block.
  366. if ('<<' === $key) {
  367. foreach ($value as $parsedValue) {
  368. $output += $parsedValue;
  369. }
  370. } elseif ($allowOverwrite || !isset($output[$key])) {
  371. $output[$key] = $value;
  372. }
  373. $done = true;
  374. break;
  375. case '{':
  376. // nested mapping
  377. $value = self::parseMapping($mapping, $i, $references);
  378. // Spec: Keys MUST be unique; first one wins.
  379. // Parser cannot abort this mapping earlier, since lines
  380. // are processed sequentially.
  381. // But overwriting is allowed when a merge node is used in current block.
  382. if ('<<' === $key) {
  383. $output += $value;
  384. } elseif ($allowOverwrite || !isset($output[$key])) {
  385. $output[$key] = $value;
  386. }
  387. $done = true;
  388. break;
  389. case ':':
  390. case ' ':
  391. break;
  392. default:
  393. $value = self::parseScalar($mapping, array(',', '}'), array('"', "'"), $i, true, $references);
  394. // Spec: Keys MUST be unique; first one wins.
  395. // Parser cannot abort this mapping earlier, since lines
  396. // are processed sequentially.
  397. // But overwriting is allowed when a merge node is used in current block.
  398. if ('<<' === $key) {
  399. $output += $value;
  400. } elseif ($allowOverwrite || !isset($output[$key])) {
  401. $output[$key] = $value;
  402. }
  403. $done = true;
  404. --$i;
  405. }
  406. ++$i;
  407. if ($done) {
  408. continue 2;
  409. }
  410. }
  411. }
  412. throw new ParseException(sprintf('Malformed inline YAML string: %s.', $mapping));
  413. }
  414. /**
  415. * Evaluates scalars and replaces magic values.
  416. *
  417. * @param string $scalar
  418. * @param array $references
  419. *
  420. * @return mixed The evaluated YAML string
  421. *
  422. * @throws ParseException when object parsing support was disabled and the parser detected a PHP object or when a reference could not be resolved
  423. */
  424. private static function evaluateScalar($scalar, $references = array())
  425. {
  426. $scalar = trim($scalar);
  427. $scalarLower = strtolower($scalar);
  428. if (0 === strpos($scalar, '*')) {
  429. if (false !== $pos = strpos($scalar, '#')) {
  430. $value = substr($scalar, 1, $pos - 2);
  431. } else {
  432. $value = substr($scalar, 1);
  433. }
  434. // an unquoted *
  435. if (false === $value || '' === $value) {
  436. throw new ParseException('A reference must contain at least one character.');
  437. }
  438. if (!array_key_exists($value, $references)) {
  439. throw new ParseException(sprintf('Reference "%s" does not exist.', $value));
  440. }
  441. return $references[$value];
  442. }
  443. switch (true) {
  444. case 'null' === $scalarLower:
  445. case '' === $scalar:
  446. case '~' === $scalar:
  447. return;
  448. case 'true' === $scalarLower:
  449. return true;
  450. case 'false' === $scalarLower:
  451. return false;
  452. // Optimise for returning strings.
  453. case '+' === $scalar[0] || '-' === $scalar[0] || '.' === $scalar[0] || '!' === $scalar[0] || is_numeric($scalar[0]):
  454. switch (true) {
  455. case 0 === strpos($scalar, '!str'):
  456. return (string) substr($scalar, 5);
  457. case 0 === strpos($scalar, '! '):
  458. return (int) self::parseScalar(substr($scalar, 2));
  459. case 0 === strpos($scalar, '!php/object:'):
  460. if (self::$objectSupport) {
  461. return unserialize(substr($scalar, 12));
  462. }
  463. if (self::$exceptionOnInvalidType) {
  464. throw new ParseException('Object support when parsing a YAML file has been disabled.');
  465. }
  466. return;
  467. case 0 === strpos($scalar, '!!php/object:'):
  468. if (self::$objectSupport) {
  469. return unserialize(substr($scalar, 13));
  470. }
  471. if (self::$exceptionOnInvalidType) {
  472. throw new ParseException('Object support when parsing a YAML file has been disabled.');
  473. }
  474. return;
  475. case 0 === strpos($scalar, '!!float '):
  476. return (float) substr($scalar, 8);
  477. case ctype_digit($scalar):
  478. $raw = $scalar;
  479. $cast = (int) $scalar;
  480. return '0' == $scalar[0] ? octdec($scalar) : (((string) $raw == (string) $cast) ? $cast : $raw);
  481. case '-' === $scalar[0] && ctype_digit(substr($scalar, 1)):
  482. $raw = $scalar;
  483. $cast = (int) $scalar;
  484. return '0' == $scalar[1] ? octdec($scalar) : (((string) $raw === (string) $cast) ? $cast : $raw);
  485. case is_numeric($scalar):
  486. case Parser::preg_match(self::getHexRegex(), $scalar):
  487. return '0x' === $scalar[0].$scalar[1] ? hexdec($scalar) : (float) $scalar;
  488. case '.inf' === $scalarLower:
  489. case '.nan' === $scalarLower:
  490. return -log(0);
  491. case '-.inf' === $scalarLower:
  492. return log(0);
  493. case Parser::preg_match('/^(-|\+)?[0-9,]+(\.[0-9]+)?$/', $scalar):
  494. return (float) str_replace(',', '', $scalar);
  495. case Parser::preg_match(self::getTimestampRegex(), $scalar):
  496. $timeZone = date_default_timezone_get();
  497. date_default_timezone_set('UTC');
  498. $time = strtotime($scalar);
  499. date_default_timezone_set($timeZone);
  500. return $time;
  501. }
  502. // no break
  503. default:
  504. return (string) $scalar;
  505. }
  506. }
  507. /**
  508. * Gets a regex that matches a YAML date.
  509. *
  510. * @return string The regular expression
  511. *
  512. * @see http://www.yaml.org/spec/1.2/spec.html#id2761573
  513. */
  514. private static function getTimestampRegex()
  515. {
  516. return <<<EOF
  517. ~^
  518. (?P<year>[0-9][0-9][0-9][0-9])
  519. -(?P<month>[0-9][0-9]?)
  520. -(?P<day>[0-9][0-9]?)
  521. (?:(?:[Tt]|[ \t]+)
  522. (?P<hour>[0-9][0-9]?)
  523. :(?P<minute>[0-9][0-9])
  524. :(?P<second>[0-9][0-9])
  525. (?:\.(?P<fraction>[0-9]*))?
  526. (?:[ \t]*(?P<tz>Z|(?P<tz_sign>[-+])(?P<tz_hour>[0-9][0-9]?)
  527. (?::(?P<tz_minute>[0-9][0-9]))?))?)?
  528. $~x
  529. EOF;
  530. }
  531. /**
  532. * Gets a regex that matches a YAML number in hexadecimal notation.
  533. *
  534. * @return string
  535. */
  536. private static function getHexRegex()
  537. {
  538. return '~^0x[0-9a-f]++$~i';
  539. }
  540. }