PageRenderTime 60ms CodeModel.GetById 17ms RepoModel.GetById 2ms app.codeStats 0ms

/src/Symfony/Component/Yaml/Parser.php

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