sfYamlInline.php 11 KB

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