Parser.php 19 KB

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