PageRenderTime 32ms CodeModel.GetById 1ms RepoModel.GetById 0ms app.codeStats 0ms

/runtime/lib/parser/yaml/sfYamlParser.php

https://github.com/1989gaurav/Propel
PHP | 600 lines | 417 code | 73 blank | 110 comment | 90 complexity | 3720939733387b888e81602d22e5e987 MD5 | raw file
  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.php');
  10. if (!defined('PREG_BAD_UTF8_OFFSET_ERROR'))
  11. {
  12. define('PREG_BAD_UTF8_OFFSET_ERROR', 5);
  13. }
  14. /**
  15. * sfYamlParser parses YAML strings to convert them to PHP arrays.
  16. *
  17. * @package symfony
  18. * @subpackage yaml
  19. * @author Fabien Potencier <fabien.potencier@symfony-project.com>
  20. * @version SVN: $Id: sfYamlParser.class.php 10832 2008-08-13 07:46:08Z fabien $
  21. */
  22. class sfYamlParser
  23. {
  24. protected
  25. $offset = 0,
  26. $lines = array(),
  27. $currentLineNb = -1,
  28. $currentLine = '',
  29. $refs = array();
  30. /**
  31. * Constructor
  32. *
  33. * @param integer $offset The offset of YAML document (used for line numbers in error messages)
  34. */
  35. public function __construct($offset = 0)
  36. {
  37. $this->offset = $offset;
  38. }
  39. /**
  40. * Parses a YAML string to a PHP value.
  41. *
  42. * @param string $value A YAML string
  43. *
  44. * @return mixed A PHP value
  45. *
  46. * @throws InvalidArgumentException If the YAML is not valid
  47. */
  48. public function parse($value)
  49. {
  50. $this->currentLineNb = -1;
  51. $this->currentLine = '';
  52. $this->lines = explode("\n", $this->cleanup($value));
  53. if (function_exists('mb_internal_encoding') && ((int) ini_get('mbstring.func_overload')) & 2)
  54. {
  55. $mbEncoding = mb_internal_encoding();
  56. mb_internal_encoding('UTF-8');
  57. }
  58. $data = array();
  59. while ($this->moveToNextLine())
  60. {
  61. if ($this->isCurrentLineEmpty())
  62. {
  63. continue;
  64. }
  65. // tab?
  66. if (preg_match('#^\t+#', $this->currentLine))
  67. {
  68. throw new InvalidArgumentException(sprintf('A YAML file cannot contain tabs as indentation at line %d (%s).', $this->getRealCurrentLineNb() + 1, $this->currentLine));
  69. }
  70. $isRef = $isInPlace = $isProcessed = false;
  71. if (preg_match('#^\-(\s+(?P<value>.+?))?\s*$#u', $this->currentLine, $values))
  72. {
  73. if (isset($values['value']) && preg_match('#^&(?P<ref>[^ ]+) *(?P<value>.*)#u', $values['value'], $matches))
  74. {
  75. $isRef = $matches['ref'];
  76. $values['value'] = $matches['value'];
  77. }
  78. // array
  79. if (!isset($values['value']) || '' == trim($values['value'], ' ') || 0 === strpos(ltrim($values['value'], ' '), '#'))
  80. {
  81. $c = $this->getRealCurrentLineNb() + 1;
  82. $parser = new sfYamlParser($c);
  83. $parser->refs =& $this->refs;
  84. $data[] = $parser->parse($this->getNextEmbedBlock());
  85. }
  86. else
  87. {
  88. if (preg_match('/^([^ ]+)\: +({.*?)$/u', $values['value'], $matches))
  89. {
  90. $data[] = array($matches[1] => sfYamlInline::load($matches[2]));
  91. }
  92. else
  93. {
  94. $data[] = $this->parseValue($values['value']);
  95. }
  96. }
  97. }
  98. else if (preg_match('#^(?P<key>'.sfYamlInline::REGEX_QUOTED_STRING.'|[^ ].*?) *\:(\s+(?P<value>.+?))?\s*$#u', $this->currentLine, $values))
  99. {
  100. $key = sfYamlInline::parseScalar($values['key']);
  101. if ('<<' === $key)
  102. {
  103. if (isset($values['value']) && '*' === substr($values['value'], 0, 1))
  104. {
  105. $isInPlace = substr($values['value'], 1);
  106. if (!array_key_exists($isInPlace, $this->refs))
  107. {
  108. throw new InvalidArgumentException(sprintf('Reference "%s" does not exist at line %s (%s).', $isInPlace, $this->getRealCurrentLineNb() + 1, $this->currentLine));
  109. }
  110. }
  111. else
  112. {
  113. if (isset($values['value']) && $values['value'] !== '')
  114. {
  115. $value = $values['value'];
  116. }
  117. else
  118. {
  119. $value = $this->getNextEmbedBlock();
  120. }
  121. $c = $this->getRealCurrentLineNb() + 1;
  122. $parser = new sfYamlParser($c);
  123. $parser->refs =& $this->refs;
  124. $parsed = $parser->parse($value);
  125. $merged = array();
  126. if (!is_array($parsed))
  127. {
  128. 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));
  129. }
  130. else if (isset($parsed[0]))
  131. {
  132. // Numeric array, merge individual elements
  133. foreach (array_reverse($parsed) as $parsedItem)
  134. {
  135. if (!is_array($parsedItem))
  136. {
  137. throw new InvalidArgumentException(sprintf("Merge items must be arrays at line %s (%s).", $this->getRealCurrentLineNb() + 1, $parsedItem));
  138. }
  139. $merged = array_merge($parsedItem, $merged);
  140. }
  141. }
  142. else
  143. {
  144. // Associative array, merge
  145. $merged = array_merge($merge, $parsed);
  146. }
  147. $isProcessed = $merged;
  148. }
  149. }
  150. else if (isset($values['value']) && preg_match('#^&(?P<ref>[^ ]+) *(?P<value>.*)#u', $values['value'], $matches))
  151. {
  152. $isRef = $matches['ref'];
  153. $values['value'] = $matches['value'];
  154. }
  155. if ($isProcessed)
  156. {
  157. // Merge keys
  158. $data = $isProcessed;
  159. }
  160. // hash
  161. else if (!isset($values['value']) || '' == trim($values['value'], ' ') || 0 === strpos(ltrim($values['value'], ' '), '#'))
  162. {
  163. // if next line is less indented or equal, then it means that the current value is null
  164. if ($this->isNextLineIndented())
  165. {
  166. $data[$key] = null;
  167. }
  168. else
  169. {
  170. $c = $this->getRealCurrentLineNb() + 1;
  171. $parser = new sfYamlParser($c);
  172. $parser->refs =& $this->refs;
  173. $data[$key] = $parser->parse($this->getNextEmbedBlock());
  174. }
  175. }
  176. else
  177. {
  178. if ($isInPlace)
  179. {
  180. $data = $this->refs[$isInPlace];
  181. }
  182. else
  183. {
  184. $data[$key] = $this->parseValue($values['value']);
  185. }
  186. }
  187. }
  188. else
  189. {
  190. // 1-liner followed by newline
  191. if (2 == count($this->lines) && empty($this->lines[1]))
  192. {
  193. $value = sfYamlInline::load($this->lines[0]);
  194. if (is_array($value))
  195. {
  196. $first = reset($value);
  197. if ('*' === substr($first, 0, 1))
  198. {
  199. $data = array();
  200. foreach ($value as $alias)
  201. {
  202. $data[] = $this->refs[substr($alias, 1)];
  203. }
  204. $value = $data;
  205. }
  206. }
  207. if (isset($mbEncoding))
  208. {
  209. mb_internal_encoding($mbEncoding);
  210. }
  211. return $value;
  212. }
  213. switch (preg_last_error())
  214. {
  215. case PREG_INTERNAL_ERROR:
  216. $error = 'Internal PCRE error on line';
  217. break;
  218. case PREG_BACKTRACK_LIMIT_ERROR:
  219. $error = 'pcre.backtrack_limit reached on line';
  220. break;
  221. case PREG_RECURSION_LIMIT_ERROR:
  222. $error = 'pcre.recursion_limit reached on line';
  223. break;
  224. case PREG_BAD_UTF8_ERROR:
  225. $error = 'Malformed UTF-8 data on line';
  226. break;
  227. case PREG_BAD_UTF8_OFFSET_ERROR:
  228. $error = 'Offset doesn\'t correspond to the begin of a valid UTF-8 code point on line';
  229. break;
  230. default:
  231. $error = 'Unable to parse line';
  232. }
  233. throw new InvalidArgumentException(sprintf('%s %d (%s).', $error, $this->getRealCurrentLineNb() + 1, $this->currentLine));
  234. }
  235. if ($isRef)
  236. {
  237. $this->refs[$isRef] = end($data);
  238. }
  239. }
  240. if (isset($mbEncoding))
  241. {
  242. mb_internal_encoding($mbEncoding);
  243. }
  244. return empty($data) ? null : $data;
  245. }
  246. /**
  247. * Returns the current line number (takes the offset into account).
  248. *
  249. * @return integer The current line number
  250. */
  251. protected function getRealCurrentLineNb()
  252. {
  253. return $this->currentLineNb + $this->offset;
  254. }
  255. /**
  256. * Returns the current line indentation.
  257. *
  258. * @return integer The current line indentation
  259. */
  260. protected function getCurrentLineIndentation()
  261. {
  262. return strlen($this->currentLine) - strlen(ltrim($this->currentLine, ' '));
  263. }
  264. /**
  265. * Returns the next embed block of YAML.
  266. *
  267. * @return string A YAML string
  268. */
  269. protected function getNextEmbedBlock()
  270. {
  271. $this->moveToNextLine();
  272. $newIndent = $this->getCurrentLineIndentation();
  273. if (!$this->isCurrentLineEmpty() && 0 == $newIndent)
  274. {
  275. throw new InvalidArgumentException(sprintf('Indentation problem at line %d (%s)', $this->getRealCurrentLineNb() + 1, $this->currentLine));
  276. }
  277. $data = array(substr($this->currentLine, $newIndent));
  278. while ($this->moveToNextLine())
  279. {
  280. if ($this->isCurrentLineEmpty())
  281. {
  282. if ($this->isCurrentLineBlank())
  283. {
  284. $data[] = substr($this->currentLine, $newIndent);
  285. }
  286. continue;
  287. }
  288. $indent = $this->getCurrentLineIndentation();
  289. if (preg_match('#^(?P<text> *)$#', $this->currentLine, $match))
  290. {
  291. // empty line
  292. $data[] = $match['text'];
  293. }
  294. else if ($indent >= $newIndent)
  295. {
  296. $data[] = substr($this->currentLine, $newIndent);
  297. }
  298. else if (0 == $indent)
  299. {
  300. $this->moveToPreviousLine();
  301. break;
  302. }
  303. else
  304. {
  305. throw new InvalidArgumentException(sprintf('Indentation problem at line %d (%s)', $this->getRealCurrentLineNb() + 1, $this->currentLine));
  306. }
  307. }
  308. return implode("\n", $data);
  309. }
  310. /**
  311. * Moves the parser to the next line.
  312. */
  313. protected function moveToNextLine()
  314. {
  315. if ($this->currentLineNb >= count($this->lines) - 1)
  316. {
  317. return false;
  318. }
  319. $this->currentLine = $this->lines[++$this->currentLineNb];
  320. return true;
  321. }
  322. /**
  323. * Moves the parser to the previous line.
  324. */
  325. protected function moveToPreviousLine()
  326. {
  327. $this->currentLine = $this->lines[--$this->currentLineNb];
  328. }
  329. /**
  330. * Parses a YAML value.
  331. *
  332. * @param string $value A YAML value
  333. *
  334. * @return mixed A PHP value
  335. */
  336. protected function parseValue($value)
  337. {
  338. if ('*' === substr($value, 0, 1))
  339. {
  340. if (false !== $pos = strpos($value, '#'))
  341. {
  342. $value = substr($value, 1, $pos - 2);
  343. }
  344. else
  345. {
  346. $value = substr($value, 1);
  347. }
  348. if (!array_key_exists($value, $this->refs))
  349. {
  350. throw new InvalidArgumentException(sprintf('Reference "%s" does not exist (%s).', $value, $this->currentLine));
  351. }
  352. return $this->refs[$value];
  353. }
  354. if (preg_match('/^(?P<separator>\||>)(?P<modifiers>\+|\-|\d+|\+\d+|\-\d+|\d+\+|\d+\-)?(?P<comments> +#.*)?$/', $value, $matches))
  355. {
  356. $modifiers = isset($matches['modifiers']) ? $matches['modifiers'] : '';
  357. return $this->parseFoldedScalar($matches['separator'], preg_replace('#\d+#', '', $modifiers), intval(abs($modifiers)));
  358. }
  359. else
  360. {
  361. return sfYamlInline::load($value);
  362. }
  363. }
  364. /**
  365. * Parses a folded scalar.
  366. *
  367. * @param string $separator The separator that was used to begin this folded scalar (| or >)
  368. * @param string $indicator The indicator that was used to begin this folded scalar (+ or -)
  369. * @param integer $indentation The indentation that was used to begin this folded scalar
  370. *
  371. * @return string The text value
  372. */
  373. protected function parseFoldedScalar($separator, $indicator = '', $indentation = 0)
  374. {
  375. $separator = '|' == $separator ? "\n" : ' ';
  376. $text = '';
  377. $notEOF = $this->moveToNextLine();
  378. while ($notEOF && $this->isCurrentLineBlank())
  379. {
  380. $text .= "\n";
  381. $notEOF = $this->moveToNextLine();
  382. }
  383. if (!$notEOF)
  384. {
  385. return '';
  386. }
  387. if (!preg_match('#^(?P<indent>'.($indentation ? str_repeat(' ', $indentation) : ' +').')(?P<text>.*)$#u', $this->currentLine, $matches))
  388. {
  389. $this->moveToPreviousLine();
  390. return '';
  391. }
  392. $textIndent = $matches['indent'];
  393. $previousIndent = 0;
  394. $text .= $matches['text'].$separator;
  395. while ($this->currentLineNb + 1 < count($this->lines))
  396. {
  397. $this->moveToNextLine();
  398. if (preg_match('#^(?P<indent> {'.strlen($textIndent).',})(?P<text>.+)$#u', $this->currentLine, $matches))
  399. {
  400. if (' ' == $separator && $previousIndent != $matches['indent'])
  401. {
  402. $text = substr($text, 0, -1)."\n";
  403. }
  404. $previousIndent = $matches['indent'];
  405. $text .= str_repeat(' ', $diff = strlen($matches['indent']) - strlen($textIndent)).$matches['text'].($diff ? "\n" : $separator);
  406. }
  407. else if (preg_match('#^(?P<text> *)$#', $this->currentLine, $matches))
  408. {
  409. $text .= preg_replace('#^ {1,'.strlen($textIndent).'}#', '', $matches['text'])."\n";
  410. }
  411. else
  412. {
  413. $this->moveToPreviousLine();
  414. break;
  415. }
  416. }
  417. if (' ' == $separator)
  418. {
  419. // replace last separator by a newline
  420. $text = preg_replace('/ (\n*)$/', "\n$1", $text);
  421. }
  422. switch ($indicator)
  423. {
  424. case '':
  425. $text = preg_replace('#\n+$#s', "\n", $text);
  426. break;
  427. case '+':
  428. break;
  429. case '-':
  430. $text = preg_replace('#\n+$#s', '', $text);
  431. break;
  432. }
  433. return $text;
  434. }
  435. /**
  436. * Returns true if the next line is indented.
  437. *
  438. * @return Boolean Returns true if the next line is indented, false otherwise
  439. */
  440. protected function isNextLineIndented()
  441. {
  442. $currentIndentation = $this->getCurrentLineIndentation();
  443. $notEOF = $this->moveToNextLine();
  444. while ($notEOF && $this->isCurrentLineEmpty())
  445. {
  446. $notEOF = $this->moveToNextLine();
  447. }
  448. if (false === $notEOF)
  449. {
  450. return false;
  451. }
  452. $ret = false;
  453. if ($this->getCurrentLineIndentation() <= $currentIndentation)
  454. {
  455. $ret = true;
  456. }
  457. $this->moveToPreviousLine();
  458. return $ret;
  459. }
  460. /**
  461. * Returns true if the current line is blank or if it is a comment line.
  462. *
  463. * @return Boolean Returns true if the current line is empty or if it is a comment line, false otherwise
  464. */
  465. protected function isCurrentLineEmpty()
  466. {
  467. return $this->isCurrentLineBlank() || $this->isCurrentLineComment();
  468. }
  469. /**
  470. * Returns true if the current line is blank.
  471. *
  472. * @return Boolean Returns true if the current line is blank, false otherwise
  473. */
  474. protected function isCurrentLineBlank()
  475. {
  476. return '' == trim($this->currentLine, ' ');
  477. }
  478. /**
  479. * Returns true if the current line is a comment line.
  480. *
  481. * @return Boolean Returns true if the current line is a comment line, false otherwise
  482. */
  483. protected function isCurrentLineComment()
  484. {
  485. //checking explicitly the first char of the trim is faster than loops or strpos
  486. $ltrimmedLine = ltrim($this->currentLine, ' ');
  487. return $ltrimmedLine[0] === '#';
  488. }
  489. /**
  490. * Cleanups a YAML string to be parsed.
  491. *
  492. * @param string $value The input YAML string
  493. *
  494. * @return string A cleaned up YAML string
  495. */
  496. protected function cleanup($value)
  497. {
  498. $value = str_replace(array("\r\n", "\r"), "\n", $value);
  499. if (!preg_match("#\n$#", $value))
  500. {
  501. $value .= "\n";
  502. }
  503. // strip YAML header
  504. $count = 0;
  505. $value = preg_replace('#^\%YAML[: ][\d\.]+.*\n#su', '', $value, -1, $count);
  506. $this->offset += $count;
  507. // remove leading comments
  508. $trimmedValue = preg_replace('#^(\#.*?\n)+#s', '', $value, -1, $count);
  509. if ($count == 1)
  510. {
  511. // items have been removed, update the offset
  512. $this->offset += substr_count($value, "\n") - substr_count($trimmedValue, "\n");
  513. $value = $trimmedValue;
  514. }
  515. // remove start of the document marker (---)
  516. $trimmedValue = preg_replace('#^\-\-\-.*?\n#s', '', $value, -1, $count);
  517. if ($count == 1)
  518. {
  519. // items have been removed, update the offset
  520. $this->offset += substr_count($value, "\n") - substr_count($trimmedValue, "\n");
  521. $value = $trimmedValue;
  522. // remove end of the document marker (...)
  523. $value = preg_replace('#\.\.\.\s*$#s', '', $value);
  524. }
  525. return $value;
  526. }
  527. }