Parser.php 19 KB

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