Inline.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  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. /**
  21. * Converts a YAML string to a PHP array.
  22. *
  23. * @param string $value A YAML string
  24. *
  25. * @return array A PHP array representing the YAML string
  26. */
  27. static public function parse($value)
  28. {
  29. $value = trim($value);
  30. if (0 == strlen($value)) {
  31. return '';
  32. }
  33. if (function_exists('mb_internal_encoding') && ((int) ini_get('mbstring.func_overload')) & 2) {
  34. $mbEncoding = mb_internal_encoding();
  35. mb_internal_encoding('ASCII');
  36. }
  37. switch ($value[0]) {
  38. case '[':
  39. $result = self::parseSequence($value);
  40. break;
  41. case '{':
  42. $result = self::parseMapping($value);
  43. break;
  44. default:
  45. $result = self::parseScalar($value);
  46. }
  47. if (isset($mbEncoding)) {
  48. mb_internal_encoding($mbEncoding);
  49. }
  50. return $result;
  51. }
  52. /**
  53. * Dumps a given PHP variable to a YAML string.
  54. *
  55. * @param mixed $value The PHP variable to convert
  56. *
  57. * @return string The YAML string representing the PHP array
  58. *
  59. * @throws DumpException When trying to dump PHP resource
  60. */
  61. static public function dump($value)
  62. {
  63. switch (true) {
  64. case is_resource($value):
  65. throw new DumpException(sprintf('Unable to dump PHP resources in a YAML file ("%s").', get_resource_type($value)));
  66. case is_object($value):
  67. return '!!php/object:'.serialize($value);
  68. case is_array($value):
  69. return self::dumpArray($value);
  70. case null === $value:
  71. return 'null';
  72. case true === $value:
  73. return 'true';
  74. case false === $value:
  75. return 'false';
  76. case ctype_digit($value):
  77. return is_string($value) ? "'$value'" : (int) $value;
  78. case is_numeric($value):
  79. return is_string($value) ? "'$value'" : (is_infinite($value) ? str_ireplace('INF', '.Inf', strval($value)) : $value);
  80. case Escaper::requiresDoubleQuoting($value):
  81. return Escaper::escapeWithDoubleQuotes($value);
  82. case Escaper::requiresSingleQuoting($value):
  83. return Escaper::escapeWithSingleQuotes($value);
  84. case '' == $value:
  85. return "''";
  86. case preg_match(self::getTimestampRegex(), $value):
  87. case in_array(strtolower($value), array('null', '~', 'true', 'false')):
  88. return "'$value'";
  89. default:
  90. return $value;
  91. }
  92. }
  93. /**
  94. * Dumps a PHP array to a YAML string.
  95. *
  96. * @param array $value The PHP array to dump
  97. *
  98. * @return string The YAML string representing the PHP array
  99. */
  100. static private function dumpArray($value)
  101. {
  102. // array
  103. $keys = array_keys($value);
  104. if ((1 == count($keys) && '0' == $keys[0])
  105. || (count($keys) > 1 && array_reduce($keys, function ($v, $w) { return (integer) $v + $w; }, 0) == count($keys) * (count($keys) - 1) / 2)
  106. ) {
  107. $output = array();
  108. foreach ($value as $val) {
  109. $output[] = self::dump($val);
  110. }
  111. return sprintf('[%s]', implode(', ', $output));
  112. }
  113. // mapping
  114. $output = array();
  115. foreach ($value as $key => $val) {
  116. $output[] = sprintf('%s: %s', self::dump($key), self::dump($val));
  117. }
  118. return sprintf('{ %s }', implode(', ', $output));
  119. }
  120. /**
  121. * Parses a scalar to a YAML string.
  122. *
  123. * @param scalar $scalar
  124. * @param string $delimiters
  125. * @param array $stringDelimiters
  126. * @param integer &$i
  127. * @param Boolean $evaluate
  128. *
  129. * @return string A YAML string
  130. *
  131. * @throws ParseException When malformed inline YAML string is parsed
  132. */
  133. static public function parseScalar($scalar, $delimiters = null, $stringDelimiters = array('"', "'"), &$i = 0, $evaluate = true)
  134. {
  135. if (in_array($scalar[$i], $stringDelimiters)) {
  136. // quoted scalar
  137. $output = self::parseQuotedScalar($scalar, $i);
  138. } else {
  139. // "normal" string
  140. if (!$delimiters) {
  141. $output = substr($scalar, $i);
  142. $i += strlen($output);
  143. // remove comments
  144. if (false !== $strpos = strpos($output, ' #')) {
  145. $output = rtrim(substr($output, 0, $strpos));
  146. }
  147. } else if (preg_match('/^(.+?)('.implode('|', $delimiters).')/', substr($scalar, $i), $match)) {
  148. $output = $match[1];
  149. $i += strlen($output);
  150. } else {
  151. throw new ParseException(sprintf('Malformed inline YAML string (%s).', $scalar));
  152. }
  153. $output = $evaluate ? self::evaluateScalar($output) : $output;
  154. }
  155. return $output;
  156. }
  157. /**
  158. * Parses a quoted scalar to YAML.
  159. *
  160. * @param string $scalar
  161. * @param integer $i
  162. *
  163. * @return string A YAML string
  164. *
  165. * @throws ParseException When malformed inline YAML string is parsed
  166. */
  167. static private function parseQuotedScalar($scalar, &$i)
  168. {
  169. if (!preg_match('/'.self::REGEX_QUOTED_STRING.'/Au', substr($scalar, $i), $match)) {
  170. throw new ParseException(sprintf('Malformed inline YAML string (%s).', substr($scalar, $i)));
  171. }
  172. $output = substr($match[0], 1, strlen($match[0]) - 2);
  173. $unescaper = new Unescaper();
  174. if ('"' == $scalar[$i]) {
  175. $output = $unescaper->unescapeDoubleQuotedString($output);
  176. } else {
  177. $output = $unescaper->unescapeSingleQuotedString($output);
  178. }
  179. $i += strlen($match[0]);
  180. return $output;
  181. }
  182. /**
  183. * Parses a sequence to a YAML string.
  184. *
  185. * @param string $sequence
  186. * @param integer $i
  187. *
  188. * @return string A YAML string
  189. *
  190. * @throws ParseException When malformed inline YAML string is parsed
  191. */
  192. static private function parseSequence($sequence, &$i = 0)
  193. {
  194. $output = array();
  195. $len = strlen($sequence);
  196. $i += 1;
  197. // [foo, bar, ...]
  198. while ($i < $len) {
  199. switch ($sequence[$i]) {
  200. case '[':
  201. // nested sequence
  202. $output[] = self::parseSequence($sequence, $i);
  203. break;
  204. case '{':
  205. // nested mapping
  206. $output[] = self::parseMapping($sequence, $i);
  207. break;
  208. case ']':
  209. return $output;
  210. case ',':
  211. case ' ':
  212. break;
  213. default:
  214. $isQuoted = in_array($sequence[$i], array('"', "'"));
  215. $value = self::parseScalar($sequence, array(',', ']'), array('"', "'"), $i);
  216. if (!$isQuoted && false !== strpos($value, ': ')) {
  217. // embedded mapping?
  218. try {
  219. $value = self::parseMapping('{'.$value.'}');
  220. } catch (\InvalidArgumentException $e) {
  221. // no, it's not
  222. }
  223. }
  224. $output[] = $value;
  225. --$i;
  226. }
  227. ++$i;
  228. }
  229. throw new ParseException(sprintf('Malformed inline YAML string %s', $sequence));
  230. }
  231. /**
  232. * Parses a mapping to a YAML string.
  233. *
  234. * @param string $mapping
  235. * @param integer $i
  236. *
  237. * @return string A YAML string
  238. *
  239. * @throws ParseException When malformed inline YAML string is parsed
  240. */
  241. static private function parseMapping($mapping, &$i = 0)
  242. {
  243. $output = array();
  244. $len = strlen($mapping);
  245. $i += 1;
  246. // {foo: bar, bar:foo, ...}
  247. while ($i < $len) {
  248. switch ($mapping[$i]) {
  249. case ' ':
  250. case ',':
  251. ++$i;
  252. continue 2;
  253. case '}':
  254. return $output;
  255. }
  256. // key
  257. $key = self::parseScalar($mapping, array(':', ' '), array('"', "'"), $i, false);
  258. // value
  259. $done = false;
  260. while ($i < $len) {
  261. switch ($mapping[$i]) {
  262. case '[':
  263. // nested sequence
  264. $output[$key] = self::parseSequence($mapping, $i);
  265. $done = true;
  266. break;
  267. case '{':
  268. // nested mapping
  269. $output[$key] = self::parseMapping($mapping, $i);
  270. $done = true;
  271. break;
  272. case ':':
  273. case ' ':
  274. break;
  275. default:
  276. $output[$key] = self::parseScalar($mapping, array(',', '}'), array('"', "'"), $i);
  277. $done = true;
  278. --$i;
  279. }
  280. ++$i;
  281. if ($done) {
  282. continue 2;
  283. }
  284. }
  285. }
  286. throw new ParseException(sprintf('Malformed inline YAML string %s', $mapping));
  287. }
  288. /**
  289. * Evaluates scalars and replaces magic values.
  290. *
  291. * @param string $scalar
  292. *
  293. * @return string A YAML string
  294. */
  295. static private function evaluateScalar($scalar)
  296. {
  297. $scalar = trim($scalar);
  298. switch (true) {
  299. case 'null' == strtolower($scalar):
  300. case '' == $scalar:
  301. case '~' == $scalar:
  302. return null;
  303. case 0 === strpos($scalar, '!str'):
  304. return (string) substr($scalar, 5);
  305. case 0 === strpos($scalar, '! '):
  306. return intval(self::parseScalar(substr($scalar, 2)));
  307. case 0 === strpos($scalar, '!!php/object:'):
  308. return unserialize(substr($scalar, 13));
  309. case ctype_digit($scalar):
  310. $raw = $scalar;
  311. $cast = intval($scalar);
  312. return '0' == $scalar[0] ? octdec($scalar) : (((string) $raw == (string) $cast) ? $cast : $raw);
  313. case 'true' === strtolower($scalar):
  314. return true;
  315. case 'false' === strtolower($scalar):
  316. return false;
  317. case is_numeric($scalar):
  318. return '0x' == $scalar[0].$scalar[1] ? hexdec($scalar) : floatval($scalar);
  319. case 0 == strcasecmp($scalar, '.inf'):
  320. case 0 == strcasecmp($scalar, '.NaN'):
  321. return -log(0);
  322. case 0 == strcasecmp($scalar, '-.inf'):
  323. return log(0);
  324. case preg_match('/^(-|\+)?[0-9,]+(\.[0-9]+)?$/', $scalar):
  325. return floatval(str_replace(',', '', $scalar));
  326. case preg_match(self::getTimestampRegex(), $scalar):
  327. return strtotime($scalar);
  328. default:
  329. return (string) $scalar;
  330. }
  331. }
  332. /**
  333. * Gets a regex that matches an unix timestamp
  334. *
  335. * @return string The regular expression
  336. */
  337. static private function getTimestampRegex()
  338. {
  339. return <<<EOF
  340. ~^
  341. (?P<year>[0-9][0-9][0-9][0-9])
  342. -(?P<month>[0-9][0-9]?)
  343. -(?P<day>[0-9][0-9]?)
  344. (?:(?:[Tt]|[ \t]+)
  345. (?P<hour>[0-9][0-9]?)
  346. :(?P<minute>[0-9][0-9])
  347. :(?P<second>[0-9][0-9])
  348. (?:\.(?P<fraction>[0-9]*))?
  349. (?:[ \t]*(?P<tz>Z|(?P<tz_sign>[-+])(?P<tz_hour>[0-9][0-9]?)
  350. (?::(?P<tz_minute>[0-9][0-9]))?))?)?
  351. $~x
  352. EOF;
  353. }
  354. }