sfYamlParser.class.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  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 10832 2008-08-13 07:46:08Z 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 = $isProcessed = 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. if (isset($values['value']) && $values['value'] !== '')
  105. {
  106. $value = $values['value'];
  107. }
  108. else
  109. {
  110. $value = $this->getNextEmbedBlock();
  111. }
  112. $c = $this->getRealCurrentLineNb() + 1;
  113. $parser = new sfYamlParser($c);
  114. $parser->refs =& $this->refs;
  115. $parsed = $parser->parse($value);
  116. $merged = array();
  117. if (!is_array($parsed))
  118. {
  119. throw new InvalidArgumentException(sprintf("YAML merge keys used with a scalar value instead of an array at line %s (%s)", $this->getRealCurrentLineNb() + 1, $this->currentLine));
  120. }
  121. else if (isset($parsed[0]))
  122. {
  123. // Numeric array, merge individual elements
  124. foreach (array_reverse($parsed) as $parsedItem)
  125. {
  126. if (!is_array($parsedItem))
  127. {
  128. throw new InvalidArgumentException(sprintf("Merge items must be arrays at line %s (%s).", $this->getRealCurrentLineNb() + 1, $parsedItem));
  129. }
  130. $merged = array_merge($parsedItem, $merged);
  131. }
  132. }
  133. else
  134. {
  135. // Associative array, merge
  136. $merged = array_merge($merge, $parsed);
  137. }
  138. $isProcessed = $merged;
  139. }
  140. }
  141. else if (isset($values['value']) && preg_match('#^&(?P<ref>[^ ]+) *(?P<value>.*)#', $values['value'], $matches))
  142. {
  143. $isRef = $matches['ref'];
  144. $values['value'] = $matches['value'];
  145. }
  146. if ($isProcessed)
  147. {
  148. // Merge keys
  149. $data = $isProcessed;
  150. }
  151. // hash
  152. else if (!isset($values['value']) || '' == trim($values['value'], ' ') || 0 === strpos(ltrim($values['value'], ' '), '#'))
  153. {
  154. // if next line is less indented or equal, then it means that the current value is null
  155. if ($this->isNextLineIndented())
  156. {
  157. $data[$key] = null;
  158. }
  159. else
  160. {
  161. $c = $this->getRealCurrentLineNb() + 1;
  162. $parser = new sfYamlParser($c);
  163. $parser->refs =& $this->refs;
  164. $data[$key] = $parser->parse($this->getNextEmbedBlock());
  165. }
  166. }
  167. else
  168. {
  169. if ($isInPlace)
  170. {
  171. $data = $this->refs[$isInPlace];
  172. }
  173. else
  174. {
  175. $data[$key] = $this->parseValue($values['value']);
  176. }
  177. }
  178. }
  179. else
  180. {
  181. // one liner?
  182. if (1 == count(explode("\n", rtrim($this->value, "\n"))))
  183. {
  184. $value = sfYamlInline::load($this->lines[0]);
  185. if (is_array($value))
  186. {
  187. $first = reset($value);
  188. if ('*' === substr($first, 0, 1))
  189. {
  190. $data = array();
  191. foreach ($value as $alias)
  192. {
  193. $data[] = $this->refs[substr($alias, 1)];
  194. }
  195. $value = $data;
  196. }
  197. }
  198. return $value;
  199. }
  200. throw new InvalidArgumentException(sprintf('Unable to parse line %d (%s).', $this->getRealCurrentLineNb() + 1, $this->currentLine));
  201. }
  202. if ($isRef)
  203. {
  204. $this->refs[$isRef] = end($data);
  205. }
  206. }
  207. return empty($data) ? null : $data;
  208. }
  209. /**
  210. * Returns the current line number (takes the offset into account).
  211. *
  212. * @return integer The current line number
  213. */
  214. protected function getRealCurrentLineNb()
  215. {
  216. return $this->currentLineNb + $this->offset;
  217. }
  218. /**
  219. * Returns the current line indentation.
  220. *
  221. * @returns integer The current line indentation
  222. */
  223. protected function getCurrentLineIndentation()
  224. {
  225. return strlen($this->currentLine) - strlen(ltrim($this->currentLine, ' '));
  226. }
  227. /**
  228. * Returns the next embed block of YAML.
  229. *
  230. * @param string A YAML string
  231. */
  232. protected function getNextEmbedBlock()
  233. {
  234. $this->moveToNextLine();
  235. $newIndent = $this->getCurrentLineIndentation();
  236. if (!$this->isCurrentLineEmpty() && 0 == $newIndent)
  237. {
  238. throw new InvalidArgumentException(sprintf('Indentation problem at line %d (%s)', $this->getRealCurrentLineNb() + 1, $this->currentLine));
  239. }
  240. $data = array(substr($this->currentLine, $newIndent));
  241. while ($this->moveToNextLine())
  242. {
  243. if ($this->isCurrentLineEmpty())
  244. {
  245. if ($this->isCurrentLineBlank())
  246. {
  247. $data[] = substr($this->currentLine, $newIndent);
  248. }
  249. continue;
  250. }
  251. $indent = $this->getCurrentLineIndentation();
  252. if (preg_match('#^(?P<text> *)$#', $this->currentLine, $match))
  253. {
  254. // empty line
  255. $data[] = $match['text'];
  256. }
  257. else if ($indent >= $newIndent)
  258. {
  259. $data[] = substr($this->currentLine, $newIndent);
  260. }
  261. else if (0 == $indent)
  262. {
  263. $this->moveToPreviousLine();
  264. break;
  265. }
  266. else
  267. {
  268. throw new InvalidArgumentException(sprintf('Indentation problem at line %d (%s)', $this->getRealCurrentLineNb() + 1, $this->currentLine));
  269. }
  270. }
  271. return implode("\n", $data);
  272. }
  273. /**
  274. * Moves the parser to the next line.
  275. */
  276. protected function moveToNextLine()
  277. {
  278. if ($this->currentLineNb >= count($this->lines) - 1)
  279. {
  280. return false;
  281. }
  282. $this->currentLine = $this->lines[++$this->currentLineNb];
  283. return true;
  284. }
  285. /**
  286. * Moves the parser to the previous line.
  287. */
  288. protected function moveToPreviousLine()
  289. {
  290. $this->currentLine = $this->lines[--$this->currentLineNb];
  291. }
  292. /**
  293. * Parses a YAML value.
  294. *
  295. * @param string A YAML value
  296. *
  297. * @return mixed A PHP value
  298. */
  299. protected function parseValue($value)
  300. {
  301. if ('*' === substr($value, 0, 1))
  302. {
  303. if (false !== $pos = strpos($value, '#'))
  304. {
  305. $value = substr($value, 1, $pos - 2);
  306. }
  307. else
  308. {
  309. $value = substr($value, 1);
  310. }
  311. if (!array_key_exists($value, $this->refs))
  312. {
  313. throw new InvalidArgumentException(sprintf('Reference "%s" does not exist (%s).', $value, $this->currentLine));
  314. }
  315. return $this->refs[$value];
  316. }
  317. if (preg_match('/^(?P<separator>\||>)(?P<modifiers>\+|\-|\d+|\+\d+|\-\d+|\d+\+|\d+\-)?(?P<comments> +#.*)?$/', $value, $matches))
  318. {
  319. $modifiers = isset($matches['modifiers']) ? $matches['modifiers'] : '';
  320. return $this->parseFoldedScalar($matches['separator'], preg_replace('#\d+#', '', $modifiers), intval(abs($modifiers)));
  321. }
  322. else
  323. {
  324. return sfYamlInline::load($value);
  325. }
  326. }
  327. /**
  328. * Parses a folded scalar.
  329. *
  330. * @param string The separator that was used to begin this folded scalar (| or >)
  331. * @param string The indicator that was used to begin this folded scalar (+ or -)
  332. * @param integer The indentation that was used to begin this folded scalar
  333. *
  334. * @return string The text value
  335. */
  336. protected function parseFoldedScalar($separator, $indicator = '', $indentation = 0)
  337. {
  338. $separator = '|' == $separator ? "\n" : ' ';
  339. $text = '';
  340. $notEOF = $this->moveToNextLine();
  341. while ($notEOF && $this->isCurrentLineBlank())
  342. {
  343. $text .= "\n";
  344. $notEOF = $this->moveToNextLine();
  345. }
  346. if (!$notEOF)
  347. {
  348. return '';
  349. }
  350. if (!preg_match('#^(?P<indent>'.($indentation ? str_repeat(' ', $indentation) : ' +').')(?P<text>.*)$#', $this->currentLine, $matches))
  351. {
  352. $this->moveToPreviousLine();
  353. return '';
  354. }
  355. $textIndent = $matches['indent'];
  356. $previousIndent = 0;
  357. $text .= $matches['text'].$separator;
  358. while ($this->currentLineNb + 1 < count($this->lines))
  359. {
  360. $this->moveToNextLine();
  361. if (preg_match('#^(?P<indent> {'.strlen($textIndent).',})(?P<text>.+)$#', $this->currentLine, $matches))
  362. {
  363. if (' ' == $separator && $previousIndent != $matches['indent'])
  364. {
  365. $text = substr($text, 0, -1)."\n";
  366. }
  367. $previousIndent = $matches['indent'];
  368. $text .= str_repeat(' ', $diff = strlen($matches['indent']) - strlen($textIndent)).$matches['text'].($diff ? "\n" : $separator);
  369. }
  370. else if (preg_match('#^(?P<text> *)$#', $this->currentLine, $matches))
  371. {
  372. $text .= preg_replace('#^ {1,'.strlen($textIndent).'}#', '', $matches['text'])."\n";
  373. }
  374. else
  375. {
  376. $this->moveToPreviousLine();
  377. break;
  378. }
  379. }
  380. if (' ' == $separator)
  381. {
  382. // replace last separator by a newline
  383. $text = preg_replace('/ (\n*)$/', "\n$1", $text);
  384. }
  385. switch ($indicator)
  386. {
  387. case '':
  388. $text = preg_replace('#\n+$#s', "\n", $text);
  389. break;
  390. case '+':
  391. break;
  392. case '-':
  393. $text = preg_replace('#\n+$#s', '', $text);
  394. break;
  395. }
  396. return $text;
  397. }
  398. /**
  399. * Returns true if the next line is indented.
  400. *
  401. * @return Boolean Returns true if the next line is indented, false otherwise
  402. */
  403. protected function isNextLineIndented()
  404. {
  405. $currentIndentation = $this->getCurrentLineIndentation();
  406. $notEOF = $this->moveToNextLine();
  407. while ($notEOF && $this->isCurrentLineEmpty())
  408. {
  409. $notEOF = $this->moveToNextLine();
  410. }
  411. if (false === $notEOF)
  412. {
  413. return false;
  414. }
  415. $ret = false;
  416. if ($this->getCurrentLineIndentation() <= $currentIndentation)
  417. {
  418. $ret = true;
  419. }
  420. $this->moveToPreviousLine();
  421. return $ret;
  422. }
  423. /**
  424. * Returns true if the current line is blank or if it is a comment line.
  425. *
  426. * @return Boolean Returns true if the current line is empty or if it is a comment line, false otherwise
  427. */
  428. protected function isCurrentLineEmpty()
  429. {
  430. return $this->isCurrentLineBlank() || $this->isCurrentLineComment();
  431. }
  432. /**
  433. * Returns true if the current line is blank.
  434. *
  435. * @return Boolean Returns true if the current line is blank, false otherwise
  436. */
  437. protected function isCurrentLineBlank()
  438. {
  439. return '' == trim($this->currentLine, ' ');
  440. }
  441. /**
  442. * Returns true if the current line is a comment line.
  443. *
  444. * @return Boolean Returns true if the current line is a comment line, false otherwise
  445. */
  446. protected function isCurrentLineComment()
  447. {
  448. return 0 === strpos(ltrim($this->currentLine, ' '), '#');
  449. }
  450. /**
  451. * Cleanups a YAML string to be parsed.
  452. *
  453. * @param string The input YAML string
  454. *
  455. * @return string A cleaned up YAML string
  456. */
  457. protected function cleanup($value)
  458. {
  459. $value = str_replace(array("\r\n", "\r"), "\n", $value);
  460. if (!preg_match("#\n$#", $value))
  461. {
  462. $value .= "\n";
  463. }
  464. // strip YAML header
  465. preg_replace('#^\%YAML[: ][\d\.]+.*\n#s', '', $value);
  466. // remove ---
  467. $value = preg_replace('#^\-\-\-.*?\n#s', '', $value);
  468. return $value;
  469. }
  470. }