PageRenderTime 47ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/sbweb/sbweb_logica/lib/symfony/yaml/sfYamlParser.class.php

http://opac-sbweb.googlecode.com/
PHP | 536 lines | 367 code | 66 blank | 103 comment | 79 complexity | fdb6659fb4fa458016e75243d5b1154b MD5 | raw file
Possible License(s): LGPL-2.1, AGPL-3.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__).'/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. }