PageRenderTime 64ms CodeModel.GetById 31ms RepoModel.GetById 0ms app.codeStats 0ms

/vendor/symfony/yaml/Parser.php

https://gitlab.com/btkm/correct_fb
PHP | 778 lines | 583 code | 78 blank | 117 comment | 101 complexity | af32aaf344bb7a102727c58199070f8c MD5 | raw file
  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 BLOCK_SCALAR_HEADER_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 (2 /* MB_OVERLOAD_STRING */ & (int) ini_get('mbstring.func_overload')) {
  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, $context);
  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, $context);
  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. if ($objectForMap && !is_object($data) && 'mapping' === $context) {
  270. $object = new \stdClass();
  271. foreach ($data as $key => $value) {
  272. $object->$key = $value;
  273. }
  274. $data = $object;
  275. }
  276. return empty($data) ? null : $data;
  277. }
  278. /**
  279. * Returns the current line number (takes the offset into account).
  280. *
  281. * @return int The current line number
  282. */
  283. private function getRealCurrentLineNb()
  284. {
  285. return $this->currentLineNb + $this->offset;
  286. }
  287. /**
  288. * Returns the current line indentation.
  289. *
  290. * @return int The current line indentation
  291. */
  292. private function getCurrentLineIndentation()
  293. {
  294. return strlen($this->currentLine) - strlen(ltrim($this->currentLine, ' '));
  295. }
  296. /**
  297. * Returns the next embed block of YAML.
  298. *
  299. * @param int $indentation The indent level at which the block is to be read, or null for default
  300. * @param bool $inSequence True if the enclosing data structure is a sequence
  301. *
  302. * @return string A YAML string
  303. *
  304. * @throws ParseException When indentation problem are detected
  305. */
  306. private function getNextEmbedBlock($indentation = null, $inSequence = false)
  307. {
  308. $oldLineIndentation = $this->getCurrentLineIndentation();
  309. $blockScalarIndentations = array();
  310. if ($this->isBlockScalarHeader()) {
  311. $blockScalarIndentations[] = $this->getCurrentLineIndentation();
  312. }
  313. if (!$this->moveToNextLine()) {
  314. return;
  315. }
  316. if (null === $indentation) {
  317. $newIndent = $this->getCurrentLineIndentation();
  318. $unindentedEmbedBlock = $this->isStringUnIndentedCollectionItem();
  319. if (!$this->isCurrentLineEmpty() && 0 === $newIndent && !$unindentedEmbedBlock) {
  320. throw new ParseException('Indentation problem.', $this->getRealCurrentLineNb() + 1, $this->currentLine);
  321. }
  322. } else {
  323. $newIndent = $indentation;
  324. }
  325. $data = array();
  326. if ($this->getCurrentLineIndentation() >= $newIndent) {
  327. $data[] = substr($this->currentLine, $newIndent);
  328. } else {
  329. $this->moveToPreviousLine();
  330. return;
  331. }
  332. if ($inSequence && $oldLineIndentation === $newIndent && isset($data[0][0]) && '-' === $data[0][0]) {
  333. // the previous line contained a dash but no item content, this line is a sequence item with the same indentation
  334. // and therefore no nested list or mapping
  335. $this->moveToPreviousLine();
  336. return;
  337. }
  338. $isItUnindentedCollection = $this->isStringUnIndentedCollectionItem();
  339. if (empty($blockScalarIndentations) && $this->isBlockScalarHeader()) {
  340. $blockScalarIndentations[] = $this->getCurrentLineIndentation();
  341. }
  342. $previousLineIndentation = $this->getCurrentLineIndentation();
  343. while ($this->moveToNextLine()) {
  344. $indent = $this->getCurrentLineIndentation();
  345. // terminate all block scalars that are more indented than the current line
  346. if (!empty($blockScalarIndentations) && $indent < $previousLineIndentation && trim($this->currentLine) !== '') {
  347. foreach ($blockScalarIndentations as $key => $blockScalarIndentation) {
  348. if ($blockScalarIndentation >= $this->getCurrentLineIndentation()) {
  349. unset($blockScalarIndentations[$key]);
  350. }
  351. }
  352. }
  353. if (empty($blockScalarIndentations) && !$this->isCurrentLineComment() && $this->isBlockScalarHeader()) {
  354. $blockScalarIndentations[] = $this->getCurrentLineIndentation();
  355. }
  356. $previousLineIndentation = $indent;
  357. if ($isItUnindentedCollection && !$this->isStringUnIndentedCollectionItem() && $newIndent === $indent) {
  358. $this->moveToPreviousLine();
  359. break;
  360. }
  361. if ($this->isCurrentLineBlank()) {
  362. $data[] = substr($this->currentLine, $newIndent);
  363. continue;
  364. }
  365. // we ignore "comment" lines only when we are not inside a scalar block
  366. if (empty($blockScalarIndentations) && $this->isCurrentLineComment()) {
  367. continue;
  368. }
  369. if ($indent >= $newIndent) {
  370. $data[] = substr($this->currentLine, $newIndent);
  371. } elseif (0 == $indent) {
  372. $this->moveToPreviousLine();
  373. break;
  374. } else {
  375. throw new ParseException('Indentation problem.', $this->getRealCurrentLineNb() + 1, $this->currentLine);
  376. }
  377. }
  378. return implode("\n", $data);
  379. }
  380. /**
  381. * Moves the parser to the next line.
  382. *
  383. * @return bool
  384. */
  385. private function moveToNextLine()
  386. {
  387. if ($this->currentLineNb >= count($this->lines) - 1) {
  388. return false;
  389. }
  390. $this->currentLine = $this->lines[++$this->currentLineNb];
  391. return true;
  392. }
  393. /**
  394. * Moves the parser to the previous line.
  395. */
  396. private function moveToPreviousLine()
  397. {
  398. $this->currentLine = $this->lines[--$this->currentLineNb];
  399. }
  400. /**
  401. * Parses a YAML value.
  402. *
  403. * @param string $value A YAML value
  404. * @param bool $exceptionOnInvalidType True if an exception must be thrown on invalid types false otherwise
  405. * @param bool $objectSupport True if object support is enabled, false otherwise
  406. * @param bool $objectForMap true if maps should return a stdClass instead of array()
  407. * @param string $context The parser context (either sequence or mapping)
  408. *
  409. * @return mixed A PHP value
  410. *
  411. * @throws ParseException When reference does not exist
  412. */
  413. private function parseValue($value, $exceptionOnInvalidType, $objectSupport, $objectForMap, $context)
  414. {
  415. if (0 === strpos($value, '*')) {
  416. if (false !== $pos = strpos($value, '#')) {
  417. $value = substr($value, 1, $pos - 2);
  418. } else {
  419. $value = substr($value, 1);
  420. }
  421. if (!array_key_exists($value, $this->refs)) {
  422. throw new ParseException(sprintf('Reference "%s" does not exist.', $value), $this->currentLine);
  423. }
  424. return $this->refs[$value];
  425. }
  426. if (preg_match('/^'.self::BLOCK_SCALAR_HEADER_PATTERN.'$/', $value, $matches)) {
  427. $modifiers = isset($matches['modifiers']) ? $matches['modifiers'] : '';
  428. return $this->parseBlockScalar($matches['separator'], preg_replace('#\d+#', '', $modifiers), (int) abs($modifiers));
  429. }
  430. try {
  431. $parsedValue = Inline::parse($value, $exceptionOnInvalidType, $objectSupport, $objectForMap, $this->refs);
  432. if ('mapping' === $context && '"' !== $value[0] && "'" !== $value[0] && '[' !== $value[0] && '{' !== $value[0] && '!' !== $value[0] && false !== strpos($parsedValue, ': ')) {
  433. throw new ParseException('A colon cannot be used in an unquoted mapping value.');
  434. }
  435. return $parsedValue;
  436. } catch (ParseException $e) {
  437. $e->setParsedLine($this->getRealCurrentLineNb() + 1);
  438. $e->setSnippet($this->currentLine);
  439. throw $e;
  440. }
  441. }
  442. /**
  443. * Parses a block scalar.
  444. *
  445. * @param string $style The style indicator that was used to begin this block scalar (| or >)
  446. * @param string $chomping The chomping indicator that was used to begin this block scalar (+ or -)
  447. * @param int $indentation The indentation indicator that was used to begin this block scalar
  448. *
  449. * @return string The text value
  450. */
  451. private function parseBlockScalar($style, $chomping = '', $indentation = 0)
  452. {
  453. $notEOF = $this->moveToNextLine();
  454. if (!$notEOF) {
  455. return '';
  456. }
  457. $isCurrentLineBlank = $this->isCurrentLineBlank();
  458. $blockLines = array();
  459. // leading blank lines are consumed before determining indentation
  460. while ($notEOF && $isCurrentLineBlank) {
  461. // newline only if not EOF
  462. if ($notEOF = $this->moveToNextLine()) {
  463. $blockLines[] = '';
  464. $isCurrentLineBlank = $this->isCurrentLineBlank();
  465. }
  466. }
  467. // determine indentation if not specified
  468. if (0 === $indentation) {
  469. if (preg_match('/^ +/', $this->currentLine, $matches)) {
  470. $indentation = strlen($matches[0]);
  471. }
  472. }
  473. if ($indentation > 0) {
  474. $pattern = sprintf('/^ {%d}(.*)$/', $indentation);
  475. while (
  476. $notEOF && (
  477. $isCurrentLineBlank ||
  478. preg_match($pattern, $this->currentLine, $matches)
  479. )
  480. ) {
  481. if ($isCurrentLineBlank && strlen($this->currentLine) > $indentation) {
  482. $blockLines[] = substr($this->currentLine, $indentation);
  483. } elseif ($isCurrentLineBlank) {
  484. $blockLines[] = '';
  485. } else {
  486. $blockLines[] = $matches[1];
  487. }
  488. // newline only if not EOF
  489. if ($notEOF = $this->moveToNextLine()) {
  490. $isCurrentLineBlank = $this->isCurrentLineBlank();
  491. }
  492. }
  493. } elseif ($notEOF) {
  494. $blockLines[] = '';
  495. }
  496. if ($notEOF) {
  497. $blockLines[] = '';
  498. $this->moveToPreviousLine();
  499. }
  500. // folded style
  501. if ('>' === $style) {
  502. $text = '';
  503. $previousLineIndented = false;
  504. $previousLineBlank = false;
  505. for ($i = 0; $i < count($blockLines); ++$i) {
  506. if ('' === $blockLines[$i]) {
  507. $text .= "\n";
  508. $previousLineIndented = false;
  509. $previousLineBlank = true;
  510. } elseif (' ' === $blockLines[$i][0]) {
  511. $text .= "\n".$blockLines[$i];
  512. $previousLineIndented = true;
  513. $previousLineBlank = false;
  514. } elseif ($previousLineIndented) {
  515. $text .= "\n".$blockLines[$i];
  516. $previousLineIndented = false;
  517. $previousLineBlank = false;
  518. } elseif ($previousLineBlank || 0 === $i) {
  519. $text .= $blockLines[$i];
  520. $previousLineIndented = false;
  521. $previousLineBlank = false;
  522. } else {
  523. $text .= ' '.$blockLines[$i];
  524. $previousLineIndented = false;
  525. $previousLineBlank = false;
  526. }
  527. }
  528. } else {
  529. $text = implode("\n", $blockLines);
  530. }
  531. // deal with trailing newlines
  532. if ('' === $chomping) {
  533. $text = preg_replace('/\n+$/', "\n", $text);
  534. } elseif ('-' === $chomping) {
  535. $text = preg_replace('/\n+$/', '', $text);
  536. }
  537. return $text;
  538. }
  539. /**
  540. * Returns true if the next line is indented.
  541. *
  542. * @return bool Returns true if the next line is indented, false otherwise
  543. */
  544. private function isNextLineIndented()
  545. {
  546. $currentIndentation = $this->getCurrentLineIndentation();
  547. $EOF = !$this->moveToNextLine();
  548. while (!$EOF && $this->isCurrentLineEmpty()) {
  549. $EOF = !$this->moveToNextLine();
  550. }
  551. if ($EOF) {
  552. return false;
  553. }
  554. $ret = false;
  555. if ($this->getCurrentLineIndentation() > $currentIndentation) {
  556. $ret = true;
  557. }
  558. $this->moveToPreviousLine();
  559. return $ret;
  560. }
  561. /**
  562. * Returns true if the current line is blank or if it is a comment line.
  563. *
  564. * @return bool Returns true if the current line is empty or if it is a comment line, false otherwise
  565. */
  566. private function isCurrentLineEmpty()
  567. {
  568. return $this->isCurrentLineBlank() || $this->isCurrentLineComment();
  569. }
  570. /**
  571. * Returns true if the current line is blank.
  572. *
  573. * @return bool Returns true if the current line is blank, false otherwise
  574. */
  575. private function isCurrentLineBlank()
  576. {
  577. return '' == trim($this->currentLine, ' ');
  578. }
  579. /**
  580. * Returns true if the current line is a comment line.
  581. *
  582. * @return bool Returns true if the current line is a comment line, false otherwise
  583. */
  584. private function isCurrentLineComment()
  585. {
  586. //checking explicitly the first char of the trim is faster than loops or strpos
  587. $ltrimmedLine = ltrim($this->currentLine, ' ');
  588. return '' !== $ltrimmedLine && $ltrimmedLine[0] === '#';
  589. }
  590. /**
  591. * Cleanups a YAML string to be parsed.
  592. *
  593. * @param string $value The input YAML string
  594. *
  595. * @return string A cleaned up YAML string
  596. */
  597. private function cleanup($value)
  598. {
  599. $value = str_replace(array("\r\n", "\r"), "\n", $value);
  600. // strip YAML header
  601. $count = 0;
  602. $value = preg_replace('#^\%YAML[: ][\d\.]+.*\n#u', '', $value, -1, $count);
  603. $this->offset += $count;
  604. // remove leading comments
  605. $trimmedValue = preg_replace('#^(\#.*?\n)+#s', '', $value, -1, $count);
  606. if ($count == 1) {
  607. // items have been removed, update the offset
  608. $this->offset += substr_count($value, "\n") - substr_count($trimmedValue, "\n");
  609. $value = $trimmedValue;
  610. }
  611. // remove start of the document marker (---)
  612. $trimmedValue = preg_replace('#^\-\-\-.*?\n#s', '', $value, -1, $count);
  613. if ($count == 1) {
  614. // items have been removed, update the offset
  615. $this->offset += substr_count($value, "\n") - substr_count($trimmedValue, "\n");
  616. $value = $trimmedValue;
  617. // remove end of the document marker (...)
  618. $value = preg_replace('#\.\.\.\s*$#', '', $value);
  619. }
  620. return $value;
  621. }
  622. /**
  623. * Returns true if the next line starts unindented collection.
  624. *
  625. * @return bool Returns true if the next line starts unindented collection, false otherwise
  626. */
  627. private function isNextLineUnIndentedCollection()
  628. {
  629. $currentIndentation = $this->getCurrentLineIndentation();
  630. $notEOF = $this->moveToNextLine();
  631. while ($notEOF && $this->isCurrentLineEmpty()) {
  632. $notEOF = $this->moveToNextLine();
  633. }
  634. if (false === $notEOF) {
  635. return false;
  636. }
  637. $ret = false;
  638. if (
  639. $this->getCurrentLineIndentation() == $currentIndentation
  640. &&
  641. $this->isStringUnIndentedCollectionItem()
  642. ) {
  643. $ret = true;
  644. }
  645. $this->moveToPreviousLine();
  646. return $ret;
  647. }
  648. /**
  649. * Returns true if the string is un-indented collection item.
  650. *
  651. * @return bool Returns true if the string is un-indented collection item, false otherwise
  652. */
  653. private function isStringUnIndentedCollectionItem()
  654. {
  655. return 0 === strpos($this->currentLine, '- ');
  656. }
  657. /**
  658. * Tests whether or not the current line is the header of a block scalar.
  659. *
  660. * @return bool
  661. */
  662. private function isBlockScalarHeader()
  663. {
  664. return (bool) preg_match('~'.self::BLOCK_SCALAR_HEADER_PATTERN.'$~', $this->currentLine);
  665. }
  666. }