PageRenderTime 45ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/library/Doctrine/Parser/YamlSf/Parser.php

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