Parser.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.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. namespace Symfony\Component\Yaml;
  11. use Symfony\Component\Yaml\Exception\ParseException;
  12. /**
  13. * Parser parses YAML strings to convert them to PHP arrays.
  14. *
  15. * @author Fabien Potencier <fabien@symfony.com>
  16. */
  17. class Parser
  18. {
  19. const FOLDED_SCALAR_PATTERN = '(?P<separator>\||>)(?P<modifiers>\+|\-|\d+|\+\d+|\-\d+|\d+\+|\d+\-)?(?P<comments> +#.*)?';
  20. private $offset = 0;
  21. private $lines = array();
  22. private $currentLineNb = -1;
  23. private $currentLine = '';
  24. private $refs = array();
  25. /**
  26. * Constructor.
  27. *
  28. * @param int $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. * @param bool $exceptionOnInvalidType true if an exception must be thrown on invalid types (a PHP resource or object), false otherwise
  39. * @param bool $objectSupport true if object support is enabled, false otherwise
  40. * @param bool $objectForMap true if maps should return a stdClass instead of array()
  41. *
  42. * @return mixed A PHP value
  43. *
  44. * @throws ParseException If the YAML is not valid
  45. */
  46. public function parse($value, $exceptionOnInvalidType = false, $objectSupport = false, $objectForMap = false)
  47. {
  48. if (!preg_match('//u', $value)) {
  49. throw new ParseException('The YAML value does not appear to be valid UTF-8.');
  50. }
  51. $this->currentLineNb = -1;
  52. $this->currentLine = '';
  53. $value = $this->cleanup($value);
  54. $this->lines = explode("\n", $value);
  55. if (function_exists('mb_internal_encoding') && ((int) ini_get('mbstring.func_overload')) & 2) {
  56. $mbEncoding = mb_internal_encoding();
  57. mb_internal_encoding('UTF-8');
  58. }
  59. $data = array();
  60. $context = null;
  61. $allowOverwrite = false;
  62. while ($this->moveToNextLine()) {
  63. if ($this->isCurrentLineEmpty()) {
  64. continue;
  65. }
  66. // tab?
  67. if ("\t" === $this->currentLine[0]) {
  68. throw new ParseException('A YAML file cannot contain tabs as indentation.', $this->getRealCurrentLineNb() + 1, $this->currentLine);
  69. }
  70. $isRef = $mergeNode = false;
  71. if (preg_match('#^\-((?P<leadspaces>\s+)(?P<value>.+?))?\s*$#u', $this->currentLine, $values)) {
  72. if ($context && 'mapping' == $context) {
  73. throw new ParseException('You cannot define a sequence item when in a mapping');
  74. }
  75. $context = 'sequence';
  76. if (isset($values['value']) && preg_match('#^&(?P<ref>[^ ]+) *(?P<value>.*)#u', $values['value'], $matches)) {
  77. $isRef = $matches['ref'];
  78. $values['value'] = $matches['value'];
  79. }
  80. // array
  81. if (!isset($values['value']) || '' == trim($values['value'], ' ') || 0 === strpos(ltrim($values['value'], ' '), '#')) {
  82. $c = $this->getRealCurrentLineNb() + 1;
  83. $parser = new self($c);
  84. $parser->refs = &$this->refs;
  85. $data[] = $parser->parse($this->getNextEmbedBlock(null, true), $exceptionOnInvalidType, $objectSupport, $objectForMap);
  86. } else {
  87. if (isset($values['leadspaces'])
  88. && preg_match('#^(?P<key>'.Inline::REGEX_QUOTED_STRING.'|[^ \'"\{\[].*?) *\:(\s+(?P<value>.+?))?\s*$#u', $values['value'], $matches)
  89. ) {
  90. // this is a compact notation element, add to next block and parse
  91. $c = $this->getRealCurrentLineNb();
  92. $parser = new self($c);
  93. $parser->refs = &$this->refs;
  94. $block = $values['value'];
  95. if ($this->isNextLineIndented()) {
  96. $block .= "\n".$this->getNextEmbedBlock($this->getCurrentLineIndentation() + strlen($values['leadspaces']) + 1);
  97. }
  98. $data[] = $parser->parse($block, $exceptionOnInvalidType, $objectSupport, $objectForMap);
  99. } else {
  100. $data[] = $this->parseValue($values['value'], $exceptionOnInvalidType, $objectSupport, $objectForMap);
  101. }
  102. }
  103. if ($isRef) {
  104. $this->refs[$isRef] = end($data);
  105. }
  106. } elseif (preg_match('#^(?P<key>'.Inline::REGEX_QUOTED_STRING.'|[^ \'"\[\{].*?) *\:(\s+(?P<value>.+?))?\s*$#u', $this->currentLine, $values) && (false === strpos($values['key'], ' #') || in_array($values['key'][0], array('"', "'")))) {
  107. if ($context && 'sequence' == $context) {
  108. throw new ParseException('You cannot define a mapping item when in a sequence');
  109. }
  110. $context = 'mapping';
  111. // force correct settings
  112. Inline::parse(null, $exceptionOnInvalidType, $objectSupport, $objectForMap, $this->refs);
  113. try {
  114. $key = Inline::parseScalar($values['key']);
  115. } catch (ParseException $e) {
  116. $e->setParsedLine($this->getRealCurrentLineNb() + 1);
  117. $e->setSnippet($this->currentLine);
  118. throw $e;
  119. }
  120. // Convert float keys to strings, to avoid being converted to integers by PHP
  121. if (is_float($key)) {
  122. $key = (string) $key;
  123. }
  124. if ('<<' === $key) {
  125. $mergeNode = true;
  126. $allowOverwrite = true;
  127. if (isset($values['value']) && 0 === strpos($values['value'], '*')) {
  128. $refName = substr($values['value'], 1);
  129. if (!array_key_exists($refName, $this->refs)) {
  130. throw new ParseException(sprintf('Reference "%s" does not exist.', $refName), $this->getRealCurrentLineNb() + 1, $this->currentLine);
  131. }
  132. $refValue = $this->refs[$refName];
  133. if (!is_array($refValue)) {
  134. throw new ParseException('YAML merge keys used with a scalar value instead of an array.', $this->getRealCurrentLineNb() + 1, $this->currentLine);
  135. }
  136. foreach ($refValue as $key => $value) {
  137. if (!isset($data[$key])) {
  138. $data[$key] = $value;
  139. }
  140. }
  141. } else {
  142. if (isset($values['value']) && $values['value'] !== '') {
  143. $value = $values['value'];
  144. } else {
  145. $value = $this->getNextEmbedBlock();
  146. }
  147. $c = $this->getRealCurrentLineNb() + 1;
  148. $parser = new self($c);
  149. $parser->refs = &$this->refs;
  150. $parsed = $parser->parse($value, $exceptionOnInvalidType, $objectSupport, $objectForMap);
  151. if (!is_array($parsed)) {
  152. throw new ParseException('YAML merge keys used with a scalar value instead of an array.', $this->getRealCurrentLineNb() + 1, $this->currentLine);
  153. }
  154. if (isset($parsed[0])) {
  155. // If the value associated with the merge key is a sequence, then this sequence is expected to contain mapping nodes
  156. // and each of these nodes is merged in turn according to its order in the sequence. Keys in mapping nodes earlier
  157. // in the sequence override keys specified in later mapping nodes.
  158. foreach ($parsed as $parsedItem) {
  159. if (!is_array($parsedItem)) {
  160. throw new ParseException('Merge items must be arrays.', $this->getRealCurrentLineNb() + 1, $parsedItem);
  161. }
  162. foreach ($parsedItem as $key => $value) {
  163. if (!isset($data[$key])) {
  164. $data[$key] = $value;
  165. }
  166. }
  167. }
  168. } else {
  169. // If the value associated with the key is a single mapping node, each of its key/value pairs is inserted into the
  170. // current mapping, unless the key already exists in it.
  171. foreach ($parsed as $key => $value) {
  172. if (!isset($data[$key])) {
  173. $data[$key] = $value;
  174. }
  175. }
  176. }
  177. }
  178. } elseif (isset($values['value']) && preg_match('#^&(?P<ref>[^ ]+) *(?P<value>.*)#u', $values['value'], $matches)) {
  179. $isRef = $matches['ref'];
  180. $values['value'] = $matches['value'];
  181. }
  182. if ($mergeNode) {
  183. // Merge keys
  184. } elseif (!isset($values['value']) || '' == trim($values['value'], ' ') || 0 === strpos(ltrim($values['value'], ' '), '#')) {
  185. // hash
  186. // if next line is less indented or equal, then it means that the current value is null
  187. if (!$this->isNextLineIndented() && !$this->isNextLineUnIndentedCollection()) {
  188. // Spec: Keys MUST be unique; first one wins.
  189. // But overwriting is allowed when a merge node is used in current block.
  190. if ($allowOverwrite || !isset($data[$key])) {
  191. $data[$key] = null;
  192. }
  193. } else {
  194. $c = $this->getRealCurrentLineNb() + 1;
  195. $parser = new self($c);
  196. $parser->refs = &$this->refs;
  197. $value = $parser->parse($this->getNextEmbedBlock(), $exceptionOnInvalidType, $objectSupport, $objectForMap);
  198. // Spec: Keys MUST be unique; first one wins.
  199. // But overwriting is allowed when a merge node is used in current block.
  200. if ($allowOverwrite || !isset($data[$key])) {
  201. $data[$key] = $value;
  202. }
  203. }
  204. } else {
  205. $value = $this->parseValue($values['value'], $exceptionOnInvalidType, $objectSupport, $objectForMap);
  206. // Spec: Keys MUST be unique; first one wins.
  207. // But overwriting is allowed when a merge node is used in current block.
  208. if ($allowOverwrite || !isset($data[$key])) {
  209. $data[$key] = $value;
  210. }
  211. }
  212. if ($isRef) {
  213. $this->refs[$isRef] = $data[$key];
  214. }
  215. } else {
  216. // multiple documents are not supported
  217. if ('---' === $this->currentLine) {
  218. throw new ParseException('Multiple documents are not supported.');
  219. }
  220. // 1-liner optionally followed by newline(s)
  221. if (is_string($value) && $this->lines[0] === trim($value)) {
  222. try {
  223. $value = Inline::parse($this->lines[0], $exceptionOnInvalidType, $objectSupport, $objectForMap, $this->refs);
  224. } catch (ParseException $e) {
  225. $e->setParsedLine($this->getRealCurrentLineNb() + 1);
  226. $e->setSnippet($this->currentLine);
  227. throw $e;
  228. }
  229. if (is_array($value)) {
  230. $first = reset($value);
  231. if (is_string($first) && 0 === strpos($first, '*')) {
  232. $data = array();
  233. foreach ($value as $alias) {
  234. $data[] = $this->refs[substr($alias, 1)];
  235. }
  236. $value = $data;
  237. }
  238. }
  239. if (isset($mbEncoding)) {
  240. mb_internal_encoding($mbEncoding);
  241. }
  242. return $value;
  243. }
  244. switch (preg_last_error()) {
  245. case PREG_INTERNAL_ERROR:
  246. $error = 'Internal PCRE error.';
  247. break;
  248. case PREG_BACKTRACK_LIMIT_ERROR:
  249. $error = 'pcre.backtrack_limit reached.';
  250. break;
  251. case PREG_RECURSION_LIMIT_ERROR:
  252. $error = 'pcre.recursion_limit reached.';
  253. break;
  254. case PREG_BAD_UTF8_ERROR:
  255. $error = 'Malformed UTF-8 data.';
  256. break;
  257. case PREG_BAD_UTF8_OFFSET_ERROR:
  258. $error = 'Offset doesn\'t correspond to the begin of a valid UTF-8 code point.';
  259. break;
  260. default:
  261. $error = 'Unable to parse.';
  262. }
  263. throw new ParseException($error, $this->getRealCurrentLineNb() + 1, $this->currentLine);
  264. }
  265. }
  266. if (isset($mbEncoding)) {
  267. mb_internal_encoding($mbEncoding);
  268. }
  269. return empty($data) ? null : $data;
  270. }
  271. /**
  272. * Returns the current line number (takes the offset into account).
  273. *
  274. * @return int The current line number
  275. */
  276. private function getRealCurrentLineNb()
  277. {
  278. return $this->currentLineNb + $this->offset;
  279. }
  280. /**
  281. * Returns the current line indentation.
  282. *
  283. * @return int The current line indentation
  284. */
  285. private function getCurrentLineIndentation()
  286. {
  287. return strlen($this->currentLine) - strlen(ltrim($this->currentLine, ' '));
  288. }
  289. /**
  290. * Returns the next embed block of YAML.
  291. *
  292. * @param int $indentation The indent level at which the block is to be read, or null for default
  293. * @param bool $inSequence True if the enclosing data structure is a sequence
  294. *
  295. * @return string A YAML string
  296. *
  297. * @throws ParseException When indentation problem are detected
  298. */
  299. private function getNextEmbedBlock($indentation = null, $inSequence = false)
  300. {
  301. $oldLineIndentation = $this->getCurrentLineIndentation();
  302. if (!$this->moveToNextLine()) {
  303. return;
  304. }
  305. if (null === $indentation) {
  306. $newIndent = $this->getCurrentLineIndentation();
  307. $unindentedEmbedBlock = $this->isStringUnIndentedCollectionItem($this->currentLine);
  308. if (!$this->isCurrentLineEmpty() && 0 === $newIndent && !$unindentedEmbedBlock) {
  309. throw new ParseException('Indentation problem.', $this->getRealCurrentLineNb() + 1, $this->currentLine);
  310. }
  311. } else {
  312. $newIndent = $indentation;
  313. }
  314. $data = array();
  315. if ($this->getCurrentLineIndentation() >= $newIndent) {
  316. $data[] = substr($this->currentLine, $newIndent);
  317. } else {
  318. $this->moveToPreviousLine();
  319. return;
  320. }
  321. if ($inSequence && $oldLineIndentation === $newIndent && isset($data[0][0]) && '-' === $data[0][0]) {
  322. // the previous line contained a dash but no item content, this line is a sequence item with the same indentation
  323. // and therefore no nested list or mapping
  324. $this->moveToPreviousLine();
  325. return;
  326. }
  327. $isItUnindentedCollection = $this->isStringUnIndentedCollectionItem($this->currentLine);
  328. // Comments must not be removed inside a string block (ie. after a line ending with "|")
  329. $removeCommentsPattern = '~'.self::FOLDED_SCALAR_PATTERN.'$~';
  330. $removeComments = !preg_match($removeCommentsPattern, $this->currentLine);
  331. while ($this->moveToNextLine()) {
  332. $indent = $this->getCurrentLineIndentation();
  333. if ($indent === $newIndent) {
  334. $removeComments = !preg_match($removeCommentsPattern, $this->currentLine);
  335. }
  336. if ($isItUnindentedCollection && !$this->isStringUnIndentedCollectionItem($this->currentLine) && $newIndent === $indent) {
  337. $this->moveToPreviousLine();
  338. break;
  339. }
  340. if ($this->isCurrentLineBlank()) {
  341. $data[] = substr($this->currentLine, $newIndent);
  342. continue;
  343. }
  344. if ($removeComments && $this->isCurrentLineComment()) {
  345. continue;
  346. }
  347. if ($indent >= $newIndent) {
  348. $data[] = substr($this->currentLine, $newIndent);
  349. } elseif (0 == $indent) {
  350. $this->moveToPreviousLine();
  351. break;
  352. } else {
  353. throw new ParseException('Indentation problem.', $this->getRealCurrentLineNb() + 1, $this->currentLine);
  354. }
  355. }
  356. return implode("\n", $data);
  357. }
  358. /**
  359. * Moves the parser to the next line.
  360. *
  361. * @return bool
  362. */
  363. private function moveToNextLine()
  364. {
  365. if ($this->currentLineNb >= count($this->lines) - 1) {
  366. return false;
  367. }
  368. $this->currentLine = $this->lines[++$this->currentLineNb];
  369. return true;
  370. }
  371. /**
  372. * Moves the parser to the previous line.
  373. */
  374. private function moveToPreviousLine()
  375. {
  376. $this->currentLine = $this->lines[--$this->currentLineNb];
  377. }
  378. /**
  379. * Parses a YAML value.
  380. *
  381. * @param string $value A YAML value
  382. * @param bool $exceptionOnInvalidType True if an exception must be thrown on invalid types false otherwise
  383. * @param bool $objectSupport True if object support is enabled, false otherwise
  384. * @param bool $objectForMap true if maps should return a stdClass instead of array()
  385. *
  386. * @return mixed A PHP value
  387. *
  388. * @throws ParseException When reference does not exist
  389. */
  390. private function parseValue($value, $exceptionOnInvalidType, $objectSupport, $objectForMap)
  391. {
  392. if (0 === strpos($value, '*')) {
  393. if (false !== $pos = strpos($value, '#')) {
  394. $value = substr($value, 1, $pos - 2);
  395. } else {
  396. $value = substr($value, 1);
  397. }
  398. if (!array_key_exists($value, $this->refs)) {
  399. throw new ParseException(sprintf('Reference "%s" does not exist.', $value), $this->currentLine);
  400. }
  401. return $this->refs[$value];
  402. }
  403. if (preg_match('/^'.self::FOLDED_SCALAR_PATTERN.'$/', $value, $matches)) {
  404. $modifiers = isset($matches['modifiers']) ? $matches['modifiers'] : '';
  405. return $this->parseFoldedScalar($matches['separator'], preg_replace('#\d+#', '', $modifiers), (int) abs($modifiers));
  406. }
  407. try {
  408. return Inline::parse($value, $exceptionOnInvalidType, $objectSupport, $objectForMap, $this->refs);
  409. } catch (ParseException $e) {
  410. $e->setParsedLine($this->getRealCurrentLineNb() + 1);
  411. $e->setSnippet($this->currentLine);
  412. throw $e;
  413. }
  414. }
  415. /**
  416. * Parses a folded scalar.
  417. *
  418. * @param string $separator The separator that was used to begin this folded scalar (| or >)
  419. * @param string $indicator The indicator that was used to begin this folded scalar (+ or -)
  420. * @param int $indentation The indentation that was used to begin this folded scalar
  421. *
  422. * @return string The text value
  423. */
  424. private function parseFoldedScalar($separator, $indicator = '', $indentation = 0)
  425. {
  426. $notEOF = $this->moveToNextLine();
  427. if (!$notEOF) {
  428. return '';
  429. }
  430. $isCurrentLineBlank = $this->isCurrentLineBlank();
  431. $text = '';
  432. // leading blank lines are consumed before determining indentation
  433. while ($notEOF && $isCurrentLineBlank) {
  434. // newline only if not EOF
  435. if ($notEOF = $this->moveToNextLine()) {
  436. $text .= "\n";
  437. $isCurrentLineBlank = $this->isCurrentLineBlank();
  438. }
  439. }
  440. // determine indentation if not specified
  441. if (0 === $indentation) {
  442. if (preg_match('/^ +/', $this->currentLine, $matches)) {
  443. $indentation = strlen($matches[0]);
  444. }
  445. }
  446. if ($indentation > 0) {
  447. $pattern = sprintf('/^ {%d}(.*)$/', $indentation);
  448. while (
  449. $notEOF && (
  450. $isCurrentLineBlank ||
  451. preg_match($pattern, $this->currentLine, $matches)
  452. )
  453. ) {
  454. if ($isCurrentLineBlank) {
  455. $text .= substr($this->currentLine, $indentation);
  456. } else {
  457. $text .= $matches[1];
  458. }
  459. // newline only if not EOF
  460. if ($notEOF = $this->moveToNextLine()) {
  461. $text .= "\n";
  462. $isCurrentLineBlank = $this->isCurrentLineBlank();
  463. }
  464. }
  465. } elseif ($notEOF) {
  466. $text .= "\n";
  467. }
  468. if ($notEOF) {
  469. $this->moveToPreviousLine();
  470. }
  471. // replace all non-trailing single newlines with spaces in folded blocks
  472. if ('>' === $separator) {
  473. preg_match('/(\n*)$/', $text, $matches);
  474. $text = preg_replace('/(?<!\n)\n(?!\n)/', ' ', rtrim($text, "\n"));
  475. $text .= $matches[1];
  476. }
  477. // deal with trailing newlines as indicated
  478. if ('' === $indicator) {
  479. $text = preg_replace('/\n+$/', "\n", $text);
  480. } elseif ('-' === $indicator) {
  481. $text = preg_replace('/\n+$/', '', $text);
  482. }
  483. return $text;
  484. }
  485. /**
  486. * Returns true if the next line is indented.
  487. *
  488. * @return bool Returns true if the next line is indented, false otherwise
  489. */
  490. private function isNextLineIndented()
  491. {
  492. $currentIndentation = $this->getCurrentLineIndentation();
  493. $EOF = !$this->moveToNextLine();
  494. while (!$EOF && $this->isCurrentLineEmpty()) {
  495. $EOF = !$this->moveToNextLine();
  496. }
  497. if ($EOF) {
  498. return false;
  499. }
  500. $ret = false;
  501. if ($this->getCurrentLineIndentation() > $currentIndentation) {
  502. $ret = true;
  503. }
  504. $this->moveToPreviousLine();
  505. return $ret;
  506. }
  507. /**
  508. * Returns true if the current line is blank or if it is a comment line.
  509. *
  510. * @return bool Returns true if the current line is empty or if it is a comment line, false otherwise
  511. */
  512. private function isCurrentLineEmpty()
  513. {
  514. return $this->isCurrentLineBlank() || $this->isCurrentLineComment();
  515. }
  516. /**
  517. * Returns true if the current line is blank.
  518. *
  519. * @return bool Returns true if the current line is blank, false otherwise
  520. */
  521. private function isCurrentLineBlank()
  522. {
  523. return '' == trim($this->currentLine, ' ');
  524. }
  525. /**
  526. * Returns true if the current line is a comment line.
  527. *
  528. * @return bool Returns true if the current line is a comment line, false otherwise
  529. */
  530. private function isCurrentLineComment()
  531. {
  532. //checking explicitly the first char of the trim is faster than loops or strpos
  533. $ltrimmedLine = ltrim($this->currentLine, ' ');
  534. return $ltrimmedLine[0] === '#';
  535. }
  536. /**
  537. * Cleanups a YAML string to be parsed.
  538. *
  539. * @param string $value The input YAML string
  540. *
  541. * @return string A cleaned up YAML string
  542. */
  543. private function cleanup($value)
  544. {
  545. $value = str_replace(array("\r\n", "\r"), "\n", $value);
  546. // strip YAML header
  547. $count = 0;
  548. $value = preg_replace('#^\%YAML[: ][\d\.]+.*\n#u', '', $value, -1, $count);
  549. $this->offset += $count;
  550. // remove leading comments
  551. $trimmedValue = preg_replace('#^(\#.*?\n)+#s', '', $value, -1, $count);
  552. if ($count == 1) {
  553. // items have been removed, update the offset
  554. $this->offset += substr_count($value, "\n") - substr_count($trimmedValue, "\n");
  555. $value = $trimmedValue;
  556. }
  557. // remove start of the document marker (---)
  558. $trimmedValue = preg_replace('#^\-\-\-.*?\n#s', '', $value, -1, $count);
  559. if ($count == 1) {
  560. // items have been removed, update the offset
  561. $this->offset += substr_count($value, "\n") - substr_count($trimmedValue, "\n");
  562. $value = $trimmedValue;
  563. // remove end of the document marker (...)
  564. $value = preg_replace('#\.\.\.\s*$#', '', $value);
  565. }
  566. return $value;
  567. }
  568. /**
  569. * Returns true if the next line starts unindented collection.
  570. *
  571. * @return bool Returns true if the next line starts unindented collection, false otherwise
  572. */
  573. private function isNextLineUnIndentedCollection()
  574. {
  575. $currentIndentation = $this->getCurrentLineIndentation();
  576. $notEOF = $this->moveToNextLine();
  577. while ($notEOF && $this->isCurrentLineEmpty()) {
  578. $notEOF = $this->moveToNextLine();
  579. }
  580. if (false === $notEOF) {
  581. return false;
  582. }
  583. $ret = false;
  584. if (
  585. $this->getCurrentLineIndentation() == $currentIndentation
  586. &&
  587. $this->isStringUnIndentedCollectionItem($this->currentLine)
  588. ) {
  589. $ret = true;
  590. }
  591. $this->moveToPreviousLine();
  592. return $ret;
  593. }
  594. /**
  595. * Returns true if the string is un-indented collection item.
  596. *
  597. * @return bool Returns true if the string is un-indented collection item, false otherwise
  598. */
  599. private function isStringUnIndentedCollectionItem()
  600. {
  601. return (0 === strpos($this->currentLine, '- '));
  602. }
  603. }