PageRenderTime 70ms CodeModel.GetById 34ms RepoModel.GetById 1ms app.codeStats 0ms

/config/src/lmbYamlInline.class.php

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