Inline.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. * (c) Fabien Potencier <fabien@symfony.com>
  5. *
  6. * For the full copyright and license information, please view the LICENSE
  7. * file that was distributed with this source code.
  8. */
  9. namespace Symfony\Component\Yaml;
  10. use Symfony\Component\Yaml\Exception\ParseException;
  11. use Symfony\Component\Yaml\Exception\DumpException;
  12. /**
  13. * Inline implements a YAML parser/dumper for the YAML inline syntax.
  14. *
  15. * @author Fabien Potencier <fabien@symfony.com>
  16. */
  17. class Inline
  18. {
  19. const REGEX_QUOTED_STRING = '(?:"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"|\'([^\']*(?:\'\'[^\']*)*)\')';
  20. private static $exceptionOnInvalidType = false;
  21. private static $objectSupport = false;
  22. /**
  23. * Converts a YAML string to a PHP array.
  24. *
  25. * @param string $value A YAML string
  26. * @param Boolean $exceptionOnInvalidType true if an exception must be thrown on invalid types (a PHP resource or object), false otherwise
  27. * @param Boolean $objectSupport true if object support is enabled, false otherwise
  28. *
  29. * @return array A PHP array representing the YAML string
  30. *
  31. * @throws ParseException
  32. */
  33. public static function parse($value, $exceptionOnInvalidType = false, $objectSupport = false)
  34. {
  35. self::$exceptionOnInvalidType = $exceptionOnInvalidType;
  36. self::$objectSupport = $objectSupport;
  37. $value = trim($value);
  38. if (0 == strlen($value)) {
  39. return '';
  40. }
  41. if (function_exists('mb_internal_encoding') && ((int) ini_get('mbstring.func_overload')) & 2) {
  42. $mbEncoding = mb_internal_encoding();
  43. mb_internal_encoding('ASCII');
  44. }
  45. $i = 0;
  46. switch ($value[0]) {
  47. case '[':
  48. $result = self::parseSequence($value, $i);
  49. ++$i;
  50. break;
  51. case '{':
  52. $result = self::parseMapping($value, $i);
  53. ++$i;
  54. break;
  55. default:
  56. $result = self::parseScalar($value, null, array('"', "'"), $i);
  57. }
  58. // some comments are allowed at the end
  59. if (preg_replace('/\s+#.*$/A', '', substr($value, $i))) {
  60. throw new ParseException(sprintf('Unexpected characters near "%s".', substr($value, $i)));
  61. }
  62. if (isset($mbEncoding)) {
  63. mb_internal_encoding($mbEncoding);
  64. }
  65. return $result;
  66. }
  67. /**
  68. * Dumps a given PHP variable to a YAML string.
  69. *
  70. * @param mixed $value The PHP variable to convert
  71. * @param Boolean $exceptionOnInvalidType true if an exception must be thrown on invalid types (a PHP resource or object), false otherwise
  72. * @param Boolean $objectSupport true if object support is enabled, false otherwise
  73. *
  74. * @return string The YAML string representing the PHP array
  75. *
  76. * @throws DumpException When trying to dump PHP resource
  77. */
  78. public static function dump($value, $exceptionOnInvalidType = false, $objectSupport = false)
  79. {
  80. switch (true) {
  81. case is_resource($value):
  82. if ($exceptionOnInvalidType) {
  83. throw new DumpException(sprintf('Unable to dump PHP resources in a YAML file ("%s").', get_resource_type($value)));
  84. }
  85. return 'null';
  86. case is_object($value):
  87. if ($objectSupport) {
  88. return '!!php/object:'.serialize($value);
  89. }
  90. if ($exceptionOnInvalidType) {
  91. throw new DumpException('Object support when dumping a YAML file has been disabled.');
  92. }
  93. return 'null';
  94. case is_array($value):
  95. return self::dumpArray($value, $exceptionOnInvalidType, $objectSupport);
  96. case null === $value:
  97. return 'null';
  98. case true === $value:
  99. return 'true';
  100. case false === $value:
  101. return 'false';
  102. case ctype_digit($value):
  103. return is_string($value) ? "'$value'" : (int) $value;
  104. case is_numeric($value):
  105. $locale = setlocale(LC_NUMERIC, 0);
  106. if (false !== $locale) {
  107. setlocale(LC_NUMERIC, 'C');
  108. }
  109. $repr = is_string($value) ? "'$value'" : (is_infinite($value) ? str_ireplace('INF', '.Inf', strval($value)) : strval($value));
  110. if (false !== $locale) {
  111. setlocale(LC_NUMERIC, $locale);
  112. }
  113. return $repr;
  114. case Escaper::requiresDoubleQuoting($value):
  115. return Escaper::escapeWithDoubleQuotes($value);
  116. case Escaper::requiresSingleQuoting($value):
  117. return Escaper::escapeWithSingleQuotes($value);
  118. case '' == $value:
  119. return "''";
  120. case preg_match(self::getTimestampRegex(), $value):
  121. case in_array(strtolower($value), array('null', '~', 'true', 'false')):
  122. return "'$value'";
  123. default:
  124. return $value;
  125. }
  126. }
  127. /**
  128. * Dumps a PHP array to a YAML string.
  129. *
  130. * @param array $value The PHP array to dump
  131. * @param Boolean $exceptionOnInvalidType true if an exception must be thrown on invalid types (a PHP resource or object), false otherwise
  132. * @param Boolean $objectSupport true if object support is enabled, false otherwise
  133. *
  134. * @return string The YAML string representing the PHP array
  135. */
  136. private static function dumpArray($value, $exceptionOnInvalidType, $objectSupport)
  137. {
  138. // array
  139. $keys = array_keys($value);
  140. if ((1 == count($keys) && '0' == $keys[0])
  141. || (count($keys) > 1 && array_reduce($keys, function ($v, $w) { return (integer) $v + $w; }, 0) == count($keys) * (count($keys) - 1) / 2)
  142. ) {
  143. $output = array();
  144. foreach ($value as $val) {
  145. $output[] = self::dump($val, $exceptionOnInvalidType, $objectSupport);
  146. }
  147. return sprintf('[%s]', implode(', ', $output));
  148. }
  149. // mapping
  150. $output = array();
  151. foreach ($value as $key => $val) {
  152. $output[] = sprintf('%s: %s', self::dump($key, $exceptionOnInvalidType, $objectSupport), self::dump($val, $exceptionOnInvalidType, $objectSupport));
  153. }
  154. return sprintf('{ %s }', implode(', ', $output));
  155. }
  156. /**
  157. * Parses a scalar to a YAML string.
  158. *
  159. * @param scalar $scalar
  160. * @param string $delimiters
  161. * @param array $stringDelimiters
  162. * @param integer &$i
  163. * @param Boolean $evaluate
  164. *
  165. * @return string A YAML string
  166. *
  167. * @throws ParseException When malformed inline YAML string is parsed
  168. */
  169. public static function parseScalar($scalar, $delimiters = null, $stringDelimiters = array('"', "'"), &$i = 0, $evaluate = true)
  170. {
  171. if (in_array($scalar[$i], $stringDelimiters)) {
  172. // quoted scalar
  173. $output = self::parseQuotedScalar($scalar, $i);
  174. if (null !== $delimiters) {
  175. $tmp = ltrim(substr($scalar, $i), ' ');
  176. if (!in_array($tmp[0], $delimiters)) {
  177. throw new ParseException(sprintf('Unexpected characters (%s).', substr($scalar, $i)));
  178. }
  179. }
  180. } else {
  181. // "normal" string
  182. if (!$delimiters) {
  183. $output = substr($scalar, $i);
  184. $i += strlen($output);
  185. // remove comments
  186. if (false !== $strpos = strpos($output, ' #')) {
  187. $output = rtrim(substr($output, 0, $strpos));
  188. }
  189. } elseif (preg_match('/^(.+?)('.implode('|', $delimiters).')/', substr($scalar, $i), $match)) {
  190. $output = $match[1];
  191. $i += strlen($output);
  192. } else {
  193. throw new ParseException(sprintf('Malformed inline YAML string (%s).', $scalar));
  194. }
  195. $output = $evaluate ? self::evaluateScalar($output) : $output;
  196. }
  197. return $output;
  198. }
  199. /**
  200. * Parses a quoted scalar to YAML.
  201. *
  202. * @param string $scalar
  203. * @param integer &$i
  204. *
  205. * @return string A YAML string
  206. *
  207. * @throws ParseException When malformed inline YAML string is parsed
  208. */
  209. private static function parseQuotedScalar($scalar, &$i)
  210. {
  211. if (!preg_match('/'.self::REGEX_QUOTED_STRING.'/Au', substr($scalar, $i), $match)) {
  212. throw new ParseException(sprintf('Malformed inline YAML string (%s).', substr($scalar, $i)));
  213. }
  214. $output = substr($match[0], 1, strlen($match[0]) - 2);
  215. $unescaper = new Unescaper();
  216. if ('"' == $scalar[$i]) {
  217. $output = $unescaper->unescapeDoubleQuotedString($output);
  218. } else {
  219. $output = $unescaper->unescapeSingleQuotedString($output);
  220. }
  221. $i += strlen($match[0]);
  222. return $output;
  223. }
  224. /**
  225. * Parses a sequence to a YAML string.
  226. *
  227. * @param string $sequence
  228. * @param integer &$i
  229. *
  230. * @return string A YAML string
  231. *
  232. * @throws ParseException When malformed inline YAML string is parsed
  233. */
  234. private static function parseSequence($sequence, &$i = 0)
  235. {
  236. $output = array();
  237. $len = strlen($sequence);
  238. $i += 1;
  239. // [foo, bar, ...]
  240. while ($i < $len) {
  241. switch ($sequence[$i]) {
  242. case '[':
  243. // nested sequence
  244. $output[] = self::parseSequence($sequence, $i);
  245. break;
  246. case '{':
  247. // nested mapping
  248. $output[] = self::parseMapping($sequence, $i);
  249. break;
  250. case ']':
  251. return $output;
  252. case ',':
  253. case ' ':
  254. break;
  255. default:
  256. $isQuoted = in_array($sequence[$i], array('"', "'"));
  257. $value = self::parseScalar($sequence, array(',', ']'), array('"', "'"), $i);
  258. if (!$isQuoted && false !== strpos($value, ': ')) {
  259. // embedded mapping?
  260. try {
  261. $value = self::parseMapping('{'.$value.'}');
  262. } catch (\InvalidArgumentException $e) {
  263. // no, it's not
  264. }
  265. }
  266. $output[] = $value;
  267. --$i;
  268. }
  269. ++$i;
  270. }
  271. throw new ParseException(sprintf('Malformed inline YAML string %s', $sequence));
  272. }
  273. /**
  274. * Parses a mapping to a YAML string.
  275. *
  276. * @param string $mapping
  277. * @param integer &$i
  278. *
  279. * @return string A YAML string
  280. *
  281. * @throws ParseException When malformed inline YAML string is parsed
  282. */
  283. private static function parseMapping($mapping, &$i = 0)
  284. {
  285. $output = array();
  286. $len = strlen($mapping);
  287. $i += 1;
  288. // {foo: bar, bar:foo, ...}
  289. while ($i < $len) {
  290. switch ($mapping[$i]) {
  291. case ' ':
  292. case ',':
  293. ++$i;
  294. continue 2;
  295. case '}':
  296. return $output;
  297. }
  298. // key
  299. $key = self::parseScalar($mapping, array(':', ' '), array('"', "'"), $i, false);
  300. // value
  301. $done = false;
  302. while ($i < $len) {
  303. switch ($mapping[$i]) {
  304. case '[':
  305. // nested sequence
  306. $output[$key] = self::parseSequence($mapping, $i);
  307. $done = true;
  308. break;
  309. case '{':
  310. // nested mapping
  311. $output[$key] = self::parseMapping($mapping, $i);
  312. $done = true;
  313. break;
  314. case ':':
  315. case ' ':
  316. break;
  317. default:
  318. $output[$key] = self::parseScalar($mapping, array(',', '}'), array('"', "'"), $i);
  319. $done = true;
  320. --$i;
  321. }
  322. ++$i;
  323. if ($done) {
  324. continue 2;
  325. }
  326. }
  327. }
  328. throw new ParseException(sprintf('Malformed inline YAML string %s', $mapping));
  329. }
  330. /**
  331. * Evaluates scalars and replaces magic values.
  332. *
  333. * @param string $scalar
  334. *
  335. * @return string A YAML string
  336. */
  337. private static function evaluateScalar($scalar)
  338. {
  339. $scalar = trim($scalar);
  340. switch (true) {
  341. case 'null' == strtolower($scalar):
  342. case '' == $scalar:
  343. case '~' == $scalar:
  344. return null;
  345. case 0 === strpos($scalar, '!str'):
  346. return (string) substr($scalar, 5);
  347. case 0 === strpos($scalar, '! '):
  348. return intval(self::parseScalar(substr($scalar, 2)));
  349. case 0 === strpos($scalar, '!!php/object:'):
  350. if (self::$objectSupport) {
  351. return unserialize(substr($scalar, 13));
  352. }
  353. if (self::$exceptionOnInvalidType) {
  354. throw new ParseException('Object support when parsing a YAML file has been disabled.');
  355. }
  356. return null;
  357. case ctype_digit($scalar):
  358. $raw = $scalar;
  359. $cast = intval($scalar);
  360. return '0' == $scalar[0] ? octdec($scalar) : (((string) $raw == (string) $cast) ? $cast : $raw);
  361. case '-' === $scalar[0] && ctype_digit(substr($scalar, 1)):
  362. $raw = $scalar;
  363. $cast = intval($scalar);
  364. return '0' == $scalar[1] ? octdec($scalar) : (((string) $raw == (string) $cast) ? $cast : $raw);
  365. case 'true' === strtolower($scalar):
  366. return true;
  367. case 'false' === strtolower($scalar):
  368. return false;
  369. case is_numeric($scalar):
  370. return '0x' == $scalar[0].$scalar[1] ? hexdec($scalar) : floatval($scalar);
  371. case 0 == strcasecmp($scalar, '.inf'):
  372. case 0 == strcasecmp($scalar, '.NaN'):
  373. return -log(0);
  374. case 0 == strcasecmp($scalar, '-.inf'):
  375. return log(0);
  376. case preg_match('/^(-|\+)?[0-9,]+(\.[0-9]+)?$/', $scalar):
  377. return floatval(str_replace(',', '', $scalar));
  378. case preg_match(self::getTimestampRegex(), $scalar):
  379. return strtotime($scalar);
  380. default:
  381. return (string) $scalar;
  382. }
  383. }
  384. /**
  385. * Gets a regex that matches a YAML date.
  386. *
  387. * @return string The regular expression
  388. *
  389. * @see http://www.yaml.org/spec/1.2/spec.html#id2761573
  390. */
  391. private static function getTimestampRegex()
  392. {
  393. return <<<EOF
  394. ~^
  395. (?P<year>[0-9][0-9][0-9][0-9])
  396. -(?P<month>[0-9][0-9]?)
  397. -(?P<day>[0-9][0-9]?)
  398. (?:(?:[Tt]|[ \t]+)
  399. (?P<hour>[0-9][0-9]?)
  400. :(?P<minute>[0-9][0-9])
  401. :(?P<second>[0-9][0-9])
  402. (?:\.(?P<fraction>[0-9]*))?
  403. (?:[ \t]*(?P<tz>Z|(?P<tz_sign>[-+])(?P<tz_hour>[0-9][0-9]?)
  404. (?::(?P<tz_minute>[0-9][0-9]))?))?)?
  405. $~x
  406. EOF;
  407. }
  408. }