sfYamlParser.class.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  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__).'/sfYamlInline.class.php');
  10. /**
  11. * sfYamlParser class.
  12. *
  13. * @package symfony
  14. * @subpackage util
  15. * @author Fabien Potencier <fabien.potencier@symfony-project.com>
  16. * @version SVN: $Id: sfYamlParser.class.php 10740 2008-08-07 10:36:31Z fabien $
  17. */
  18. class sfYamlParser
  19. {
  20. protected
  21. $value = '',
  22. $offset = 0,
  23. $lines = array(),
  24. $currentLineNb = -1,
  25. $currentLine = '',
  26. $refs = array();
  27. /**
  28. * Constructor
  29. *
  30. * @param integer The offset of YAML document (used for line numbers in error messages)
  31. */
  32. public function __construct($offset = 0)
  33. {
  34. $this->offset = $offset;
  35. }
  36. /**
  37. * Parses a YAML string to a PHP value.
  38. *
  39. * @param string A YAML string
  40. *
  41. * @return mixed A PHP value
  42. */
  43. public function parse($value)
  44. {
  45. $this->value = $this->cleanup($value);
  46. $this->currentLineNb = -1;
  47. $this->currentLine = '';
  48. $this->lines = explode("\n", $this->value);
  49. $data = array();
  50. while ($this->moveToNextLine())
  51. {
  52. if ($this->isCurrentLineEmpty())
  53. {
  54. continue;
  55. }
  56. // tab?
  57. if (preg_match('#^\t+#', $this->currentLine))
  58. {
  59. throw new InvalidArgumentException(sprintf('A YAML file cannot contain tabs as indentation at line %d (%s).', $this->getRealCurrentLineNb() + 1, $this->currentLine));
  60. }
  61. $isRef = $isInPlace = false;
  62. if (preg_match('#^\-(\s+(?P<value>.+?))?\s*$#', $this->currentLine, $values))
  63. {
  64. if (isset($values['value']) && preg_match('#^&(?P<ref>[^ ]+) *(?P<value>.*)#', $values['value'], $matches))
  65. {
  66. $isRef = $matches['ref'];
  67. $values['value'] = $matches['value'];
  68. }
  69. // array
  70. if (!isset($values['value']) || '' == trim($values['value'], ' ') || 0 === strpos(ltrim($values['value'], ' '), '#'))
  71. {
  72. $c = $this->getRealCurrentLineNb() + 1;
  73. $parser = new sfYamlParser($c);
  74. $parser->refs =& $this->refs;
  75. $data[] = $parser->parse($this->getNextEmbedBlock());
  76. }
  77. else
  78. {
  79. if (preg_match('/^([^ ]+)\: +({.*?)$/', $values['value'], $matches))
  80. {
  81. $data[] = array($matches[1] => sfYamlInline::load($matches[2]));
  82. }
  83. else
  84. {
  85. $data[] = $this->parseValue($values['value']);
  86. }
  87. }
  88. }
  89. else if (preg_match('#^(?P<key>[^ ].*?) *\:(\s+(?P<value>.+?))?\s*$#', $this->currentLine, $values))
  90. {
  91. $key = sfYamlInline::parseScalar($values['key']);
  92. if ('<<' === $key)
  93. {
  94. if (isset($values['value']) && '*' === substr($values['value'], 0, 1))
  95. {
  96. $isInPlace = substr($values['value'], 1);
  97. if (!array_key_exists($isInPlace, $this->refs))
  98. {
  99. throw new InvalidArgumentException(sprintf('Reference "%s" does not exist at line %s (%s).', $isInPlace, $this->getRealCurrentLineNb() + 1, $this->currentLine));
  100. }
  101. }
  102. else
  103. {
  104. throw new InvalidArgumentException(sprintf('In place substitution must point to a reference at line %s (%s).', $this->getRealCurrentLineNb() + 1, $this->currentLine));
  105. }
  106. }
  107. else if (isset($values['value']) && preg_match('#^&(?P<ref>[^ ]+) *(?P<value>.*)#', $values['value'], $matches))
  108. {
  109. $isRef = $matches['ref'];
  110. $values['value'] = $matches['value'];
  111. }
  112. // hash
  113. if (!isset($values['value']) || '' == trim($values['value'], ' ') || 0 === strpos(ltrim($values['value'], ' '), '#'))
  114. {
  115. // if next line is less indented or equal, then it means that the current value is null
  116. if ($this->isNextLineIndented())
  117. {
  118. $data[$key] = null;
  119. }
  120. else
  121. {
  122. $c = $this->getRealCurrentLineNb() + 1;
  123. $parser = new sfYamlParser($c);
  124. $parser->refs =& $this->refs;
  125. $data[$key] = $parser->parse($this->getNextEmbedBlock());
  126. }
  127. }
  128. else
  129. {
  130. if ($isInPlace)
  131. {
  132. $data = $this->refs[$isInPlace];
  133. }
  134. else
  135. {
  136. $data[$key] = $this->parseValue($values['value']);
  137. }
  138. }
  139. }
  140. else
  141. {
  142. // one liner?
  143. if (1 == count(explode("\n", rtrim($this->value, "\n"))))
  144. {
  145. return sfYamlInline::load($this->lines[0]);
  146. }
  147. throw new InvalidArgumentException(sprintf('Unable to parse line %d (%s).', $this->getRealCurrentLineNb() + 1, $this->currentLine));
  148. }
  149. if ($isRef)
  150. {
  151. $this->refs[$isRef] = end($data);
  152. }
  153. }
  154. return empty($data) ? null : $data;
  155. }
  156. /**
  157. * Returns the current line number (takes the offset into account).
  158. *
  159. * @return integer The current line number
  160. */
  161. protected function getRealCurrentLineNb()
  162. {
  163. return $this->currentLineNb + $this->offset;
  164. }
  165. /**
  166. * Returns the current line indentation.
  167. *
  168. * @returns integer The current line indentation
  169. */
  170. protected function getCurrentLineIndentation()
  171. {
  172. return strlen($this->currentLine) - strlen(ltrim($this->currentLine, ' '));
  173. }
  174. /**
  175. * Returns the next embed block of YAML.
  176. *
  177. * @param string A YAML string
  178. */
  179. protected function getNextEmbedBlock()
  180. {
  181. $this->moveToNextLine();
  182. $newIndent = $this->getCurrentLineIndentation();
  183. if (!$this->isCurrentLineEmpty() && 0 == $newIndent)
  184. {
  185. throw new InvalidArgumentException(sprintf('Indentation problem at line %d (%s)', $this->getRealCurrentLineNb() + 1, $this->currentLine));
  186. }
  187. $data = array(substr($this->currentLine, $newIndent));
  188. while ($this->moveToNextLine())
  189. {
  190. if ($this->isCurrentLineEmpty())
  191. {
  192. if ($this->isCurrentLineBlank())
  193. {
  194. $data[] = substr($this->currentLine, $newIndent);
  195. }
  196. continue;
  197. }
  198. $indent = $this->getCurrentLineIndentation();
  199. if (preg_match('#^(?P<text> *)$#', $this->currentLine, $match))
  200. {
  201. // empty line
  202. $data[] = $match['text'];
  203. }
  204. else if ($indent >= $newIndent)
  205. {
  206. $data[] = substr($this->currentLine, $newIndent);
  207. }
  208. else if (0 == $indent)
  209. {
  210. $this->moveToPreviousLine();
  211. break;
  212. }
  213. else
  214. {
  215. throw new InvalidArgumentException(sprintf('Indentation problem at line %d (%s)', $this->getRealCurrentLineNb() + 1, $this->currentLine));
  216. }
  217. }
  218. return implode("\n", $data);
  219. }
  220. /**
  221. * Moves the parser to the next line.
  222. */
  223. protected function moveToNextLine()
  224. {
  225. if ($this->currentLineNb >= count($this->lines) - 1)
  226. {
  227. return false;
  228. }
  229. $this->currentLine = $this->lines[++$this->currentLineNb];
  230. return true;
  231. }
  232. /**
  233. * Moves the parser to the previous line.
  234. */
  235. protected function moveToPreviousLine()
  236. {
  237. $this->currentLine = $this->lines[--$this->currentLineNb];
  238. }
  239. /**
  240. * Parses a YAML value.
  241. *
  242. * @param string A YAML value
  243. *
  244. * @return mixed A PHP value
  245. */
  246. protected function parseValue($value)
  247. {
  248. if ('*' === substr($value, 0, 1))
  249. {
  250. if (false !== $pos = strpos($value, '#'))
  251. {
  252. $value = substr($value, 1, $pos - 2);
  253. }
  254. else
  255. {
  256. $value = substr($value, 1);
  257. }
  258. if (!array_key_exists($value, $this->refs))
  259. {
  260. throw new InvalidArgumentException(sprintf('Reference "%s" does not exist (%s).', $value, $this->currentLine));
  261. }
  262. return $this->refs[$value];
  263. }
  264. if (preg_match('/^(?P<separator>\||>)(?P<modifiers>\+|\-|\d+|\+\d+|\-\d+|\d+\+|\d+\-)?(?P<comments> +#.*)?$/', $value, $matches))
  265. {
  266. $modifiers = isset($matches['modifiers']) ? $matches['modifiers'] : '';
  267. return $this->parseFoldedScalar($matches['separator'], preg_replace('#\d+#', '', $modifiers), intval(abs($modifiers)));
  268. }
  269. else
  270. {
  271. return sfYamlInline::load($value);
  272. }
  273. }
  274. /**
  275. * Parses a folded scalar.
  276. *
  277. * @param string The separator that was used to begin this folded scalar (| or >)
  278. * @param string The indicator that was used to begin this folded scalar (+ or -)
  279. * @param integer The indentation that was used to begin this folded scalar
  280. *
  281. * @return string The text value
  282. */
  283. protected function parseFoldedScalar($separator, $indicator = '', $indentation = 0)
  284. {
  285. $separator = '|' == $separator ? "\n" : ' ';
  286. $text = '';
  287. $notEOF = $this->moveToNextLine();
  288. while ($notEOF && $this->isCurrentLineBlank())
  289. {
  290. $text .= "\n";
  291. $notEOF = $this->moveToNextLine();
  292. }
  293. if (!$notEOF)
  294. {
  295. return '';
  296. }
  297. if (!preg_match('#^(?P<indent>'.($indentation ? str_repeat(' ', $indentation) : ' +').')(?P<text>.*)$#', $this->currentLine, $matches))
  298. {
  299. $this->moveToPreviousLine();
  300. return '';
  301. }
  302. $textIndent = $matches['indent'];
  303. $previousIndent = 0;
  304. $text .= $matches['text'].$separator;
  305. while ($this->currentLineNb + 1 < count($this->lines))
  306. {
  307. $this->moveToNextLine();
  308. if (preg_match('#^(?P<indent> {'.strlen($textIndent).',})(?P<text>.+)$#', $this->currentLine, $matches))
  309. {
  310. if (' ' == $separator && $previousIndent != $matches['indent'])
  311. {
  312. $text = substr($text, 0, -1)."\n";
  313. }
  314. $previousIndent = $matches['indent'];
  315. $text .= str_repeat(' ', $diff = strlen($matches['indent']) - strlen($textIndent)).$matches['text'].($diff ? "\n" : $separator);
  316. }
  317. else if (preg_match('#^(?P<text> *)$#', $this->currentLine, $matches))
  318. {
  319. $text .= preg_replace('#^ {1,'.strlen($textIndent).'}#', '', $matches['text'])."\n";
  320. }
  321. else
  322. {
  323. $this->moveToPreviousLine();
  324. break;
  325. }
  326. }
  327. if (' ' == $separator)
  328. {
  329. // replace last separator by a newline
  330. $text = preg_replace('/ (\n*)$/', "\n$1", $text);
  331. }
  332. switch ($indicator)
  333. {
  334. case '':
  335. $text = preg_replace('#\n+$#s', "\n", $text);
  336. break;
  337. case '+':
  338. break;
  339. case '-':
  340. $text = preg_replace('#\n+$#s', '', $text);
  341. break;
  342. }
  343. return $text;
  344. }
  345. /**
  346. * Returns true if the next line is indented.
  347. *
  348. * @return Boolean Returns true if the next line is indented, false otherwise
  349. */
  350. protected function isNextLineIndented()
  351. {
  352. $currentIndentation = $this->getCurrentLineIndentation();
  353. $notEOF = $this->moveToNextLine();
  354. while ($notEOF && $this->isCurrentLineEmpty())
  355. {
  356. $notEOF = $this->moveToNextLine();
  357. }
  358. if (false === $notEOF)
  359. {
  360. return false;
  361. }
  362. $ret = false;
  363. if ($this->getCurrentLineIndentation() <= $currentIndentation)
  364. {
  365. $ret = true;
  366. }
  367. $this->moveToPreviousLine();
  368. return $ret;
  369. }
  370. /**
  371. * Returns true if the current line is blank or if it is a comment line.
  372. *
  373. * @return Boolean Returns true if the current line is empty or if it is a comment line, false otherwise
  374. */
  375. protected function isCurrentLineEmpty()
  376. {
  377. return $this->isCurrentLineBlank() || $this->isCurrentLineComment();
  378. }
  379. /**
  380. * Returns true if the current line is blank.
  381. *
  382. * @return Boolean Returns true if the current line is blank, false otherwise
  383. */
  384. protected function isCurrentLineBlank()
  385. {
  386. return '' == trim($this->currentLine, ' ');
  387. }
  388. /**
  389. * Returns true if the current line is a comment line.
  390. *
  391. * @return Boolean Returns true if the current line is a comment line, false otherwise
  392. */
  393. protected function isCurrentLineComment()
  394. {
  395. return 0 === strpos(ltrim($this->currentLine, ' '), '#');
  396. }
  397. /**
  398. * Cleanups a YAML string to be parsed.
  399. *
  400. * @param string The input YAML string
  401. *
  402. * @return string A cleaned up YAML string
  403. */
  404. protected function cleanup($value)
  405. {
  406. $value = str_replace(array("\r\n", "\r"), "\n", $value);
  407. if (!preg_match("#\n$#", $value))
  408. {
  409. $value .= "\n";
  410. }
  411. // strip YAML header
  412. preg_replace('#^\%YAML[: ][\d\.]+.*\n#s', '', $value);
  413. // remove ---
  414. $value = preg_replace('#^\-\-\-.*?\n#s', '', $value);
  415. return $value;
  416. }
  417. }