No Description

Inline.php 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  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 array.
  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 array A PHP array representing the YAML string
  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 (0 == strlen($value)) {
  44. return '';
  45. }
  46. if (function_exists('mb_internal_encoding') && ((int) ini_get('mbstring.func_overload')) & 2) {
  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 array
  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 = strval($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'" : strval($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 preg_match(self::getTimestampRegex(), $value):
  135. return Escaper::escapeWithSingleQuotes($value);
  136. default:
  137. return $value;
  138. }
  139. }
  140. /**
  141. * Dumps a PHP array to a YAML string.
  142. *
  143. * @param array $value The PHP array to dump
  144. * @param bool $exceptionOnInvalidType true if an exception must be thrown on invalid types (a PHP resource or object), false otherwise
  145. * @param bool $objectSupport true if object support is enabled, false otherwise
  146. *
  147. * @return string The YAML string representing the PHP array
  148. */
  149. private static function dumpArray($value, $exceptionOnInvalidType, $objectSupport)
  150. {
  151. // array
  152. $keys = array_keys($value);
  153. if ((1 == count($keys) && '0' == $keys[0])
  154. || (count($keys) > 1 && array_reduce($keys, function ($v, $w) { return (int) $v + $w; }, 0) == count($keys) * (count($keys) - 1) / 2)
  155. ) {
  156. $output = array();
  157. foreach ($value as $val) {
  158. $output[] = self::dump($val, $exceptionOnInvalidType, $objectSupport);
  159. }
  160. return sprintf('[%s]', implode(', ', $output));
  161. }
  162. // mapping
  163. $output = array();
  164. foreach ($value as $key => $val) {
  165. $output[] = sprintf('%s: %s', self::dump($key, $exceptionOnInvalidType, $objectSupport), self::dump($val, $exceptionOnInvalidType, $objectSupport));
  166. }
  167. return sprintf('{ %s }', implode(', ', $output));
  168. }
  169. /**
  170. * Parses a scalar to a YAML string.
  171. *
  172. * @param string $scalar
  173. * @param string $delimiters
  174. * @param array $stringDelimiters
  175. * @param int &$i
  176. * @param bool $evaluate
  177. * @param array $references
  178. *
  179. * @return string A YAML string
  180. *
  181. * @throws ParseException When malformed inline YAML string is parsed
  182. */
  183. public static function parseScalar($scalar, $delimiters = null, $stringDelimiters = array('"', "'"), &$i = 0, $evaluate = true, $references = array())
  184. {
  185. if (in_array($scalar[$i], $stringDelimiters)) {
  186. // quoted scalar
  187. $output = self::parseQuotedScalar($scalar, $i);
  188. if (null !== $delimiters) {
  189. $tmp = ltrim(substr($scalar, $i), ' ');
  190. if (!in_array($tmp[0], $delimiters)) {
  191. throw new ParseException(sprintf('Unexpected characters (%s).', substr($scalar, $i)));
  192. }
  193. }
  194. } else {
  195. // "normal" string
  196. if (!$delimiters) {
  197. $output = substr($scalar, $i);
  198. $i += strlen($output);
  199. // remove comments
  200. if (false !== $strpos = strpos($output, ' #')) {
  201. $output = rtrim(substr($output, 0, $strpos));
  202. }
  203. } elseif (preg_match('/^(.+?)('.implode('|', $delimiters).')/', substr($scalar, $i), $match)) {
  204. $output = $match[1];
  205. $i += strlen($output);
  206. } else {
  207. throw new ParseException(sprintf('Malformed inline YAML string (%s).', $scalar));
  208. }
  209. if ($evaluate) {
  210. $output = self::evaluateScalar($output, $references);
  211. }
  212. }
  213. return $output;
  214. }
  215. /**
  216. * Parses a quoted scalar to YAML.
  217. *
  218. * @param string $scalar
  219. * @param int &$i
  220. *
  221. * @return string A YAML string
  222. *
  223. * @throws ParseException When malformed inline YAML string is parsed
  224. */
  225. private static function parseQuotedScalar($scalar, &$i)
  226. {
  227. if (!preg_match('/'.self::REGEX_QUOTED_STRING.'/Au', substr($scalar, $i), $match)) {
  228. throw new ParseException(sprintf('Malformed inline YAML string (%s).', substr($scalar, $i)));
  229. }
  230. $output = substr($match[0], 1, strlen($match[0]) - 2);
  231. $unescaper = new Unescaper();
  232. if ('"' == $scalar[$i]) {
  233. $output = $unescaper->unescapeDoubleQuotedString($output);
  234. } else {
  235. $output = $unescaper->unescapeSingleQuotedString($output);
  236. }
  237. $i += strlen($match[0]);
  238. return $output;
  239. }
  240. /**
  241. * Parses a sequence to a YAML string.
  242. *
  243. * @param string $sequence
  244. * @param int &$i
  245. * @param array $references
  246. *
  247. * @return string A YAML string
  248. *
  249. * @throws ParseException When malformed inline YAML string is parsed
  250. */
  251. private static function parseSequence($sequence, &$i = 0, $references = array())
  252. {
  253. $output = array();
  254. $len = strlen($sequence);
  255. $i += 1;
  256. // [foo, bar, ...]
  257. while ($i < $len) {
  258. switch ($sequence[$i]) {
  259. case '[':
  260. // nested sequence
  261. $output[] = self::parseSequence($sequence, $i, $references);
  262. break;
  263. case '{':
  264. // nested mapping
  265. $output[] = self::parseMapping($sequence, $i, $references);
  266. break;
  267. case ']':
  268. return $output;
  269. case ',':
  270. case ' ':
  271. break;
  272. default:
  273. $isQuoted = in_array($sequence[$i], array('"', "'"));
  274. $value = self::parseScalar($sequence, array(',', ']'), array('"', "'"), $i, true, $references);
  275. // the value can be an array if a reference has been resolved to an array var
  276. if (!is_array($value) && !$isQuoted && false !== strpos($value, ': ')) {
  277. // embedded mapping?
  278. try {
  279. $pos = 0;
  280. $value = self::parseMapping('{'.$value.'}', $pos, $references);
  281. } catch (\InvalidArgumentException $e) {
  282. // no, it's not
  283. }
  284. }
  285. $output[] = $value;
  286. --$i;
  287. }
  288. ++$i;
  289. }
  290. throw new ParseException(sprintf('Malformed inline YAML string %s', $sequence));
  291. }
  292. /**
  293. * Parses a mapping to a YAML string.
  294. *
  295. * @param string $mapping
  296. * @param int &$i
  297. * @param array $references
  298. *
  299. * @return string A YAML string
  300. *
  301. * @throws ParseException When malformed inline YAML string is parsed
  302. */
  303. private static function parseMapping($mapping, &$i = 0, $references = array())
  304. {
  305. $output = array();
  306. $len = strlen($mapping);
  307. $i += 1;
  308. // {foo: bar, bar:foo, ...}
  309. while ($i < $len) {
  310. switch ($mapping[$i]) {
  311. case ' ':
  312. case ',':
  313. ++$i;
  314. continue 2;
  315. case '}':
  316. if (self::$objectForMap) {
  317. return (object) $output;
  318. }
  319. return $output;
  320. }
  321. // key
  322. $key = self::parseScalar($mapping, array(':', ' '), array('"', "'"), $i, false);
  323. // value
  324. $done = false;
  325. while ($i < $len) {
  326. switch ($mapping[$i]) {
  327. case '[':
  328. // nested sequence
  329. $value = self::parseSequence($mapping, $i, $references);
  330. // Spec: Keys MUST be unique; first one wins.
  331. // Parser cannot abort this mapping earlier, since lines
  332. // are processed sequentially.
  333. if (!isset($output[$key])) {
  334. $output[$key] = $value;
  335. }
  336. $done = true;
  337. break;
  338. case '{':
  339. // nested mapping
  340. $value = self::parseMapping($mapping, $i, $references);
  341. // Spec: Keys MUST be unique; first one wins.
  342. // Parser cannot abort this mapping earlier, since lines
  343. // are processed sequentially.
  344. if (!isset($output[$key])) {
  345. $output[$key] = $value;
  346. }
  347. $done = true;
  348. break;
  349. case ':':
  350. case ' ':
  351. break;
  352. default:
  353. $value = self::parseScalar($mapping, array(',', '}'), array('"', "'"), $i, true, $references);
  354. // Spec: Keys MUST be unique; first one wins.
  355. // Parser cannot abort this mapping earlier, since lines
  356. // are processed sequentially.
  357. if (!isset($output[$key])) {
  358. $output[$key] = $value;
  359. }
  360. $done = true;
  361. --$i;
  362. }
  363. ++$i;
  364. if ($done) {
  365. continue 2;
  366. }
  367. }
  368. }
  369. throw new ParseException(sprintf('Malformed inline YAML string %s', $mapping));
  370. }
  371. /**
  372. * Evaluates scalars and replaces magic values.
  373. *
  374. * @param string $scalar
  375. * @param array $references
  376. *
  377. * @return string A YAML string
  378. *
  379. * @throws ParseException when object parsing support was disabled and the parser detected a PHP object or when a reference could not be resolved
  380. */
  381. private static function evaluateScalar($scalar, $references = array())
  382. {
  383. $scalar = trim($scalar);
  384. $scalarLower = strtolower($scalar);
  385. if (0 === strpos($scalar, '*')) {
  386. if (false !== $pos = strpos($scalar, '#')) {
  387. $value = substr($scalar, 1, $pos - 2);
  388. } else {
  389. $value = substr($scalar, 1);
  390. }
  391. // an unquoted *
  392. if (false === $value || '' === $value) {
  393. throw new ParseException('A reference must contain at least one character.');
  394. }
  395. if (!array_key_exists($value, $references)) {
  396. throw new ParseException(sprintf('Reference "%s" does not exist.', $value));
  397. }
  398. return $references[$value];
  399. }
  400. switch (true) {
  401. case 'null' === $scalarLower:
  402. case '' === $scalar:
  403. case '~' === $scalar:
  404. return;
  405. case 'true' === $scalarLower:
  406. return true;
  407. case 'false' === $scalarLower:
  408. return false;
  409. // Optimise for returning strings.
  410. case $scalar[0] === '+' || $scalar[0] === '-' || $scalar[0] === '.' || $scalar[0] === '!' || is_numeric($scalar[0]):
  411. switch (true) {
  412. case 0 === strpos($scalar, '!str'):
  413. return (string) substr($scalar, 5);
  414. case 0 === strpos($scalar, '! '):
  415. return intval(self::parseScalar(substr($scalar, 2)));
  416. case 0 === strpos($scalar, '!!php/object:'):
  417. if (self::$objectSupport) {
  418. return unserialize(substr($scalar, 13));
  419. }
  420. if (self::$exceptionOnInvalidType) {
  421. throw new ParseException('Object support when parsing a YAML file has been disabled.');
  422. }
  423. return;
  424. case 0 === strpos($scalar, '!!float '):
  425. return (float) substr($scalar, 8);
  426. case ctype_digit($scalar):
  427. $raw = $scalar;
  428. $cast = intval($scalar);
  429. return '0' == $scalar[0] ? octdec($scalar) : (((string) $raw == (string) $cast) ? $cast : $raw);
  430. case '-' === $scalar[0] && ctype_digit(substr($scalar, 1)):
  431. $raw = $scalar;
  432. $cast = intval($scalar);
  433. return '0' == $scalar[1] ? octdec($scalar) : (((string) $raw == (string) $cast) ? $cast : $raw);
  434. case is_numeric($scalar):
  435. return '0x' == $scalar[0].$scalar[1] ? hexdec($scalar) : floatval($scalar);
  436. case '.inf' === $scalarLower:
  437. case '.nan' === $scalarLower:
  438. return -log(0);
  439. case '-.inf' === $scalarLower:
  440. return log(0);
  441. case preg_match('/^(-|\+)?[0-9,]+(\.[0-9]+)?$/', $scalar):
  442. return floatval(str_replace(',', '', $scalar));
  443. case preg_match(self::getTimestampRegex(), $scalar):
  444. return strtotime($scalar);
  445. }
  446. default:
  447. return (string) $scalar;
  448. }
  449. }
  450. /**
  451. * Gets a regex that matches a YAML date.
  452. *
  453. * @return string The regular expression
  454. *
  455. * @see http://www.yaml.org/spec/1.2/spec.html#id2761573
  456. */
  457. private static function getTimestampRegex()
  458. {
  459. return <<<EOF
  460. ~^
  461. (?P<year>[0-9][0-9][0-9][0-9])
  462. -(?P<month>[0-9][0-9]?)
  463. -(?P<day>[0-9][0-9]?)
  464. (?:(?:[Tt]|[ \t]+)
  465. (?P<hour>[0-9][0-9]?)
  466. :(?P<minute>[0-9][0-9])
  467. :(?P<second>[0-9][0-9])
  468. (?:\.(?P<fraction>[0-9]*))?
  469. (?:[ \t]*(?P<tz>Z|(?P<tz_sign>[-+])(?P<tz_hour>[0-9][0-9]?)
  470. (?::(?P<tz_minute>[0-9][0-9]))?))?)?
  471. $~x
  472. EOF;
  473. }
  474. }