Parser.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  1. <?php
  2. namespace Symfony\Components\Yaml;
  3. /*
  4. * This file is part of the symfony package.
  5. * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. /**
  11. * Parser parses YAML strings to convert them to PHP arrays.
  12. *
  13. * @package symfony
  14. * @subpackage yaml
  15. * @author Fabien Potencier <fabien.potencier@symfony-project.com>
  16. */
  17. class Parser
  18. {
  19. protected $value = '';
  20. protected $offset = 0;
  21. protected $lines = array();
  22. protected $currentLineNb = -1;
  23. protected $currentLine = '';
  24. protected $refs = array();
  25. /**
  26. * Constructor
  27. *
  28. * @param integer $offset The offset of YAML document (used for line numbers in error messages)
  29. */
  30. public function __construct($offset = 0)
  31. {
  32. $this->offset = $offset;
  33. }
  34. /**
  35. * Parses a YAML string to a PHP value.
  36. *
  37. * @param string $value A YAML string
  38. *
  39. * @return mixed A PHP value
  40. *
  41. * @throws \InvalidArgumentException If the YAML is not valid
  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 Parser($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] => Inline::load($matches[2]));
  82. }
  83. else
  84. {
  85. $data[] = $this->parseValue($values['value']);
  86. }
  87. }
  88. }
  89. else if (preg_match('#^(?P<key>'.Inline::REGEX_QUOTED_STRING.'|[^ ].*?) *\:(\s+(?P<value>.+?))?\s*$#', $this->currentLine, $values))
  90. {
  91. $key = Inline::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 Parser($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 Parser($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 = Inline::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. switch (preg_last_error())
  201. {
  202. case PREG_INTERNAL_ERROR:
  203. $error = 'Internal PCRE error on line';
  204. break;
  205. case PREG_BACKTRACK_LIMIT_ERROR:
  206. $error = 'pcre.backtrack_limit reached on line';
  207. break;
  208. case PREG_RECURSION_LIMIT_ERROR:
  209. $error = 'pcre.recursion_limit reached on line';
  210. break;
  211. case PREG_BAD_UTF8_ERROR:
  212. $error = 'Malformed UTF-8 data on line';
  213. break;
  214. case PREG_BAD_UTF8_OFFSET_ERROR:
  215. $error = 'Offset doesn\'t correspond to the begin of a valid UTF-8 code point on line';
  216. break;
  217. default:
  218. $error = 'Unable to parse line';
  219. }
  220. throw new \InvalidArgumentException(sprintf('%s %d (%s).', $error, $this->getRealCurrentLineNb() + 1, $this->currentLine));
  221. }
  222. if ($isRef)
  223. {
  224. $this->refs[$isRef] = end($data);
  225. }
  226. }
  227. return empty($data) ? null : $data;
  228. }
  229. /**
  230. * Returns the current line number (takes the offset into account).
  231. *
  232. * @return integer The current line number
  233. */
  234. protected function getRealCurrentLineNb()
  235. {
  236. return $this->currentLineNb + $this->offset;
  237. }
  238. /**
  239. * Returns the current line indentation.
  240. *
  241. * @return integer The current line indentation
  242. */
  243. protected function getCurrentLineIndentation()
  244. {
  245. return strlen($this->currentLine) - strlen(ltrim($this->currentLine, ' '));
  246. }
  247. /**
  248. * Returns the next embed block of YAML.
  249. *
  250. * @return string A YAML string
  251. */
  252. protected function getNextEmbedBlock()
  253. {
  254. $this->moveToNextLine();
  255. $newIndent = $this->getCurrentLineIndentation();
  256. if (!$this->isCurrentLineEmpty() && 0 == $newIndent)
  257. {
  258. throw new \InvalidArgumentException(sprintf('Indentation problem at line %d (%s)', $this->getRealCurrentLineNb() + 1, $this->currentLine));
  259. }
  260. $data = array(substr($this->currentLine, $newIndent));
  261. while ($this->moveToNextLine())
  262. {
  263. if ($this->isCurrentLineEmpty())
  264. {
  265. if ($this->isCurrentLineBlank())
  266. {
  267. $data[] = substr($this->currentLine, $newIndent);
  268. }
  269. continue;
  270. }
  271. $indent = $this->getCurrentLineIndentation();
  272. if (preg_match('#^(?P<text> *)$#', $this->currentLine, $match))
  273. {
  274. // empty line
  275. $data[] = $match['text'];
  276. }
  277. else if ($indent >= $newIndent)
  278. {
  279. $data[] = substr($this->currentLine, $newIndent);
  280. }
  281. else if (0 == $indent)
  282. {
  283. $this->moveToPreviousLine();
  284. break;
  285. }
  286. else
  287. {
  288. throw new \InvalidArgumentException(sprintf('Indentation problem at line %d (%s)', $this->getRealCurrentLineNb() + 1, $this->currentLine));
  289. }
  290. }
  291. return implode("\n", $data);
  292. }
  293. /**
  294. * Moves the parser to the next line.
  295. */
  296. protected function moveToNextLine()
  297. {
  298. if ($this->currentLineNb >= count($this->lines) - 1)
  299. {
  300. return false;
  301. }
  302. $this->currentLine = $this->lines[++$this->currentLineNb];
  303. return true;
  304. }
  305. /**
  306. * Moves the parser to the previous line.
  307. */
  308. protected function moveToPreviousLine()
  309. {
  310. $this->currentLine = $this->lines[--$this->currentLineNb];
  311. }
  312. /**
  313. * Parses a YAML value.
  314. *
  315. * @param string $value A YAML value
  316. *
  317. * @return mixed A PHP value
  318. */
  319. protected function parseValue($value)
  320. {
  321. if ('*' === substr($value, 0, 1))
  322. {
  323. if (false !== $pos = strpos($value, '#'))
  324. {
  325. $value = substr($value, 1, $pos - 2);
  326. }
  327. else
  328. {
  329. $value = substr($value, 1);
  330. }
  331. if (!array_key_exists($value, $this->refs))
  332. {
  333. throw new \InvalidArgumentException(sprintf('Reference "%s" does not exist (%s).', $value, $this->currentLine));
  334. }
  335. return $this->refs[$value];
  336. }
  337. if (preg_match('/^(?P<separator>\||>)(?P<modifiers>\+|\-|\d+|\+\d+|\-\d+|\d+\+|\d+\-)?(?P<comments> +#.*)?$/', $value, $matches))
  338. {
  339. $modifiers = isset($matches['modifiers']) ? $matches['modifiers'] : '';
  340. return $this->parseFoldedScalar($matches['separator'], preg_replace('#\d+#', '', $modifiers), intval(abs($modifiers)));
  341. }
  342. else
  343. {
  344. return Inline::load($value);
  345. }
  346. }
  347. /**
  348. * Parses a folded scalar.
  349. *
  350. * @param string $separator The separator that was used to begin this folded scalar (| or >)
  351. * @param string $indicator The indicator that was used to begin this folded scalar (+ or -)
  352. * @param integer $indentation The indentation that was used to begin this folded scalar
  353. *
  354. * @return string The text value
  355. */
  356. protected function parseFoldedScalar($separator, $indicator = '', $indentation = 0)
  357. {
  358. $separator = '|' == $separator ? "\n" : ' ';
  359. $text = '';
  360. $notEOF = $this->moveToNextLine();
  361. while ($notEOF && $this->isCurrentLineBlank())
  362. {
  363. $text .= "\n";
  364. $notEOF = $this->moveToNextLine();
  365. }
  366. if (!$notEOF)
  367. {
  368. return '';
  369. }
  370. if (!preg_match('#^(?P<indent>'.($indentation ? str_repeat(' ', $indentation) : ' +').')(?P<text>.*)$#', $this->currentLine, $matches))
  371. {
  372. $this->moveToPreviousLine();
  373. return '';
  374. }
  375. $textIndent = $matches['indent'];
  376. $previousIndent = 0;
  377. $text .= $matches['text'].$separator;
  378. while ($this->currentLineNb + 1 < count($this->lines))
  379. {
  380. $this->moveToNextLine();
  381. if (preg_match('#^(?P<indent> {'.strlen($textIndent).',})(?P<text>.+)$#', $this->currentLine, $matches))
  382. {
  383. if (' ' == $separator && $previousIndent != $matches['indent'])
  384. {
  385. $text = substr($text, 0, -1)."\n";
  386. }
  387. $previousIndent = $matches['indent'];
  388. $text .= str_repeat(' ', $diff = strlen($matches['indent']) - strlen($textIndent)).$matches['text'].($diff ? "\n" : $separator);
  389. }
  390. else if (preg_match('#^(?P<text> *)$#', $this->currentLine, $matches))
  391. {
  392. $text .= preg_replace('#^ {1,'.strlen($textIndent).'}#', '', $matches['text'])."\n";
  393. }
  394. else
  395. {
  396. $this->moveToPreviousLine();
  397. break;
  398. }
  399. }
  400. if (' ' == $separator)
  401. {
  402. // replace last separator by a newline
  403. $text = preg_replace('/ (\n*)$/', "\n$1", $text);
  404. }
  405. switch ($indicator)
  406. {
  407. case '':
  408. $text = preg_replace('#\n+$#s', "\n", $text);
  409. break;
  410. case '+':
  411. break;
  412. case '-':
  413. $text = preg_replace('#\n+$#s', '', $text);
  414. break;
  415. }
  416. return $text;
  417. }
  418. /**
  419. * Returns true if the next line is indented.
  420. *
  421. * @return Boolean Returns true if the next line is indented, false otherwise
  422. */
  423. protected function isNextLineIndented()
  424. {
  425. $currentIndentation = $this->getCurrentLineIndentation();
  426. $notEOF = $this->moveToNextLine();
  427. while ($notEOF && $this->isCurrentLineEmpty())
  428. {
  429. $notEOF = $this->moveToNextLine();
  430. }
  431. if (false === $notEOF)
  432. {
  433. return false;
  434. }
  435. $ret = false;
  436. if ($this->getCurrentLineIndentation() <= $currentIndentation)
  437. {
  438. $ret = true;
  439. }
  440. $this->moveToPreviousLine();
  441. return $ret;
  442. }
  443. /**
  444. * Returns true if the current line is blank or if it is a comment line.
  445. *
  446. * @return Boolean Returns true if the current line is empty or if it is a comment line, false otherwise
  447. */
  448. protected function isCurrentLineEmpty()
  449. {
  450. return $this->isCurrentLineBlank() || $this->isCurrentLineComment();
  451. }
  452. /**
  453. * Returns true if the current line is blank.
  454. *
  455. * @return Boolean Returns true if the current line is blank, false otherwise
  456. */
  457. protected function isCurrentLineBlank()
  458. {
  459. return '' == trim($this->currentLine, ' ');
  460. }
  461. /**
  462. * Returns true if the current line is a comment line.
  463. *
  464. * @return Boolean Returns true if the current line is a comment line, false otherwise
  465. */
  466. protected function isCurrentLineComment()
  467. {
  468. //checking explicitly the first char of the trim is faster than loops or strpos
  469. $ltrimmedLine = ltrim($this->currentLine, ' ');
  470. return $ltrimmedLine[0] === '#';
  471. }
  472. /**
  473. * Cleanups a YAML string to be parsed.
  474. *
  475. * @param string $value The input YAML string
  476. *
  477. * @return string A cleaned up YAML string
  478. */
  479. protected function cleanup($value)
  480. {
  481. $value = str_replace(array("\r\n", "\r"), "\n", $value);
  482. if (!preg_match("#\n$#", $value))
  483. {
  484. $value .= "\n";
  485. }
  486. // strip YAML header
  487. preg_replace('#^\%YAML[: ][\d\.]+.*\n#s', '', $value);
  488. // remove ---
  489. $value = preg_replace('#^\-\-\-.*?\n#s', '', $value);
  490. return $value;
  491. }
  492. }