Inline.php 11 KB

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