sfYamlParser.php 17 KB

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