4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Yaml;
14 use Symfony\Component\Yaml\Exception\ParseException;
15 use Symfony\Component\Yaml\Tag\TaggedValue;
18 * Parser parses YAML strings to convert them to PHP arrays.
20 * @author Fabien Potencier <fabien@symfony.com>
22 * @final since version 3.4
26 const TAG_PATTERN = '(?P<tag>![\w!.\/:-]+)';
27 const BLOCK_SCALAR_HEADER_PATTERN = '(?P<separator>\||>)(?P<modifiers>\+|\-|\d+|\+\d+|\-\d+|\d+\+|\d+\-)?(?P<comments> +#.*)?';
31 private $totalNumberOfLines;
32 private $lines = array();
33 private $currentLineNb = -1;
34 private $currentLine = '';
35 private $refs = array();
36 private $skippedLineNumbers = array();
37 private $locallySkippedLineNumbers = array();
39 public function __construct()
41 if (\func_num_args() > 0) {
42 @trigger_error(sprintf('The constructor arguments $offset, $totalNumberOfLines, $skippedLineNumbers of %s are deprecated and will be removed in 4.0', self::class), E_USER_DEPRECATED);
44 $this->offset = func_get_arg(0);
45 if (\func_num_args() > 1) {
46 $this->totalNumberOfLines = func_get_arg(1);
48 if (\func_num_args() > 2) {
49 $this->skippedLineNumbers = func_get_arg(2);
55 * Parses a YAML file into a PHP value.
57 * @param string $filename The path to the YAML file to be parsed
58 * @param int $flags A bit field of PARSE_* constants to customize the YAML parser behavior
60 * @return mixed The YAML converted to a PHP value
62 * @throws ParseException If the file could not be read or the YAML is not valid
64 public function parseFile($filename, $flags = 0)
66 if (!is_file($filename)) {
67 throw new ParseException(sprintf('File "%s" does not exist.', $filename));
70 if (!is_readable($filename)) {
71 throw new ParseException(sprintf('File "%s" cannot be read.', $filename));
74 $this->filename = $filename;
77 return $this->parse(file_get_contents($filename), $flags);
79 $this->filename = null;
84 * Parses a YAML string to a PHP value.
86 * @param string $value A YAML string
87 * @param int $flags A bit field of PARSE_* constants to customize the YAML parser behavior
89 * @return mixed A PHP value
91 * @throws ParseException If the YAML is not valid
93 public function parse($value, $flags = 0)
95 if (\is_bool($flags)) {
96 @trigger_error('Passing a boolean flag to toggle exception handling is deprecated since Symfony 3.1 and will be removed in 4.0. Use the Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE flag instead.', E_USER_DEPRECATED);
99 $flags = Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE;
105 if (\func_num_args() >= 3) {
106 @trigger_error('Passing a boolean flag to toggle object support is deprecated since Symfony 3.1 and will be removed in 4.0. Use the Yaml::PARSE_OBJECT flag instead.', E_USER_DEPRECATED);
108 if (func_get_arg(2)) {
109 $flags |= Yaml::PARSE_OBJECT;
113 if (\func_num_args() >= 4) {
114 @trigger_error('Passing a boolean flag to toggle object for map support is deprecated since Symfony 3.1 and will be removed in 4.0. Use the Yaml::PARSE_OBJECT_FOR_MAP flag instead.', E_USER_DEPRECATED);
116 if (func_get_arg(3)) {
117 $flags |= Yaml::PARSE_OBJECT_FOR_MAP;
121 if (Yaml::PARSE_KEYS_AS_STRINGS & $flags) {
122 @trigger_error('Using the Yaml::PARSE_KEYS_AS_STRINGS flag is deprecated since Symfony 3.4 as it will be removed in 4.0. Quote your keys when they are evaluable instead.', E_USER_DEPRECATED);
125 if (false === preg_match('//u', $value)) {
126 throw new ParseException('The YAML value does not appear to be valid UTF-8.', -1, null, $this->filename);
129 $this->refs = array();
135 if (2 /* MB_OVERLOAD_STRING */ & (int) ini_get('mbstring.func_overload')) {
136 $mbEncoding = mb_internal_encoding();
137 mb_internal_encoding('UTF-8');
141 $data = $this->doParse($value, $flags);
142 } catch (\Exception $e) {
143 } catch (\Throwable $e) {
146 if (null !== $mbEncoding) {
147 mb_internal_encoding($mbEncoding);
150 $this->lines = array();
151 $this->currentLine = '';
152 $this->refs = array();
153 $this->skippedLineNumbers = array();
154 $this->locallySkippedLineNumbers = array();
163 private function doParse($value, $flags)
165 $this->currentLineNb = -1;
166 $this->currentLine = '';
167 $value = $this->cleanup($value);
168 $this->lines = explode("\n", $value);
169 $this->locallySkippedLineNumbers = array();
171 if (null === $this->totalNumberOfLines) {
172 $this->totalNumberOfLines = \count($this->lines);
175 if (!$this->moveToNextLine()) {
181 $allowOverwrite = false;
183 while ($this->isCurrentLineEmpty()) {
184 if (!$this->moveToNextLine()) {
189 // Resolves the tag and returns if end of the document
190 if (null !== ($tag = $this->getLineTag($this->currentLine, $flags, false)) && !$this->moveToNextLine()) {
191 return new TaggedValue($tag, '');
195 if ($this->isCurrentLineEmpty()) {
200 if ("\t" === $this->currentLine[0]) {
201 throw new ParseException('A YAML file cannot contain tabs as indentation.', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
204 Inline::initialize($flags, $this->getRealCurrentLineNb(), $this->filename);
206 $isRef = $mergeNode = false;
207 if (self::preg_match('#^\-((?P<leadspaces>\s+)(?P<value>.+))?$#u', rtrim($this->currentLine), $values)) {
208 if ($context && 'mapping' == $context) {
209 throw new ParseException('You cannot define a sequence item when in a mapping', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
211 $context = 'sequence';
213 if (isset($values['value']) && self::preg_match('#^&(?P<ref>[^ ]+) *(?P<value>.*)#u', $values['value'], $matches)) {
214 $isRef = $matches['ref'];
215 $values['value'] = $matches['value'];
218 if (isset($values['value'][1]) && '?' === $values['value'][0] && ' ' === $values['value'][1]) {
219 @trigger_error($this->getDeprecationMessage('Starting an unquoted string with a question mark followed by a space is deprecated since Symfony 3.3 and will throw \Symfony\Component\Yaml\Exception\ParseException in 4.0.'), E_USER_DEPRECATED);
223 if (!isset($values['value']) || '' == trim($values['value'], ' ') || 0 === strpos(ltrim($values['value'], ' '), '#')) {
224 $data[] = $this->parseBlock($this->getRealCurrentLineNb() + 1, $this->getNextEmbedBlock(null, true), $flags);
225 } elseif (null !== $subTag = $this->getLineTag(ltrim($values['value'], ' '), $flags)) {
226 $data[] = new TaggedValue(
228 $this->parseBlock($this->getRealCurrentLineNb() + 1, $this->getNextEmbedBlock(null, true), $flags)
231 if (isset($values['leadspaces'])
232 && self::preg_match('#^(?P<key>'.Inline::REGEX_QUOTED_STRING.'|[^ \'"\{\[].*?) *\:(\s+(?P<value>.+?))?\s*$#u', $this->trimTag($values['value']), $matches)
234 // this is a compact notation element, add to next block and parse
235 $block = $values['value'];
236 if ($this->isNextLineIndented()) {
237 $block .= "\n".$this->getNextEmbedBlock($this->getCurrentLineIndentation() + \strlen($values['leadspaces']) + 1);
240 $data[] = $this->parseBlock($this->getRealCurrentLineNb(), $block, $flags);
242 $data[] = $this->parseValue($values['value'], $flags, $context);
246 $this->refs[$isRef] = end($data);
249 self::preg_match('#^(?P<key>(?:![^\s]++\s++)?(?:'.Inline::REGEX_QUOTED_STRING.'|(?:!?!php/const:)?[^ \'"\[\{!].*?)) *\:(\s++(?P<value>.+))?$#u', rtrim($this->currentLine), $values)
250 && (false === strpos($values['key'], ' #') || \in_array($values['key'][0], array('"', "'")))
252 if ($context && 'sequence' == $context) {
253 throw new ParseException('You cannot define a mapping item when in a sequence', $this->currentLineNb + 1, $this->currentLine, $this->filename);
255 $context = 'mapping';
259 $evaluateKey = !(Yaml::PARSE_KEYS_AS_STRINGS & $flags);
261 // constants in key will be evaluated anyway
262 if (isset($values['key'][0]) && '!' === $values['key'][0] && Yaml::PARSE_CONSTANT & $flags) {
266 $key = Inline::parseScalar($values['key'], 0, null, $i, $evaluateKey);
267 } catch (ParseException $e) {
268 $e->setParsedLine($this->getRealCurrentLineNb() + 1);
269 $e->setSnippet($this->currentLine);
274 if (!\is_string($key) && !\is_int($key)) {
275 $keyType = is_numeric($key) ? 'numeric key' : 'non-string key';
276 @trigger_error($this->getDeprecationMessage(sprintf('Implicit casting of %s to string is deprecated since Symfony 3.3 and will throw \Symfony\Component\Yaml\Exception\ParseException in 4.0. Quote your evaluable mapping keys instead.', $keyType)), E_USER_DEPRECATED);
279 // Convert float keys to strings, to avoid being converted to integers by PHP
280 if (\is_float($key)) {
281 $key = (string) $key;
284 if ('<<' === $key && (!isset($values['value']) || !self::preg_match('#^&(?P<ref>[^ ]+)#u', $values['value'], $refMatches))) {
286 $allowOverwrite = true;
287 if (isset($values['value'][0]) && '*' === $values['value'][0]) {
288 $refName = substr(rtrim($values['value']), 1);
289 if (!array_key_exists($refName, $this->refs)) {
290 throw new ParseException(sprintf('Reference "%s" does not exist.', $refName), $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
293 $refValue = $this->refs[$refName];
295 if (Yaml::PARSE_OBJECT_FOR_MAP & $flags && $refValue instanceof \stdClass) {
296 $refValue = (array) $refValue;
299 if (!\is_array($refValue)) {
300 throw new ParseException('YAML merge keys used with a scalar value instead of an array.', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
303 $data += $refValue; // array union
305 if (isset($values['value']) && '' !== $values['value']) {
306 $value = $values['value'];
308 $value = $this->getNextEmbedBlock();
310 $parsed = $this->parseBlock($this->getRealCurrentLineNb() + 1, $value, $flags);
312 if (Yaml::PARSE_OBJECT_FOR_MAP & $flags && $parsed instanceof \stdClass) {
313 $parsed = (array) $parsed;
316 if (!\is_array($parsed)) {
317 throw new ParseException('YAML merge keys used with a scalar value instead of an array.', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
320 if (isset($parsed[0])) {
321 // If the value associated with the merge key is a sequence, then this sequence is expected to contain mapping nodes
322 // and each of these nodes is merged in turn according to its order in the sequence. Keys in mapping nodes earlier
323 // in the sequence override keys specified in later mapping nodes.
324 foreach ($parsed as $parsedItem) {
325 if (Yaml::PARSE_OBJECT_FOR_MAP & $flags && $parsedItem instanceof \stdClass) {
326 $parsedItem = (array) $parsedItem;
329 if (!\is_array($parsedItem)) {
330 throw new ParseException('Merge items must be arrays.', $this->getRealCurrentLineNb() + 1, $parsedItem, $this->filename);
333 $data += $parsedItem; // array union
336 // If the value associated with the key is a single mapping node, each of its key/value pairs is inserted into the
337 // current mapping, unless the key already exists in it.
338 $data += $parsed; // array union
341 } elseif ('<<' !== $key && isset($values['value']) && self::preg_match('#^&(?P<ref>[^ ]++) *+(?P<value>.*)#u', $values['value'], $matches)) {
342 $isRef = $matches['ref'];
343 $values['value'] = $matches['value'];
349 } elseif (!isset($values['value']) || '' === $values['value'] || 0 === strpos($values['value'], '#') || (null !== $subTag = $this->getLineTag($values['value'], $flags)) || '<<' === $key) {
351 // if next line is less indented or equal, then it means that the current value is null
352 if (!$this->isNextLineIndented() && !$this->isNextLineUnIndentedCollection()) {
353 // Spec: Keys MUST be unique; first one wins.
354 // But overwriting is allowed when a merge node is used in current block.
355 if ($allowOverwrite || !isset($data[$key])) {
356 if (null !== $subTag) {
357 $data[$key] = new TaggedValue($subTag, '');
362 @trigger_error($this->getDeprecationMessage(sprintf('Duplicate key "%s" detected whilst parsing YAML. Silent handling of duplicate mapping keys in YAML is deprecated since Symfony 3.2 and will throw \Symfony\Component\Yaml\Exception\ParseException in 4.0.', $key)), E_USER_DEPRECATED);
365 $value = $this->parseBlock($this->getRealCurrentLineNb() + 1, $this->getNextEmbedBlock(), $flags);
367 $this->refs[$refMatches['ref']] = $value;
369 if (Yaml::PARSE_OBJECT_FOR_MAP & $flags && $value instanceof \stdClass) {
370 $value = (array) $value;
374 } elseif ($allowOverwrite || !isset($data[$key])) {
375 // Spec: Keys MUST be unique; first one wins.
376 // But overwriting is allowed when a merge node is used in current block.
377 if (null !== $subTag) {
378 $data[$key] = new TaggedValue($subTag, $value);
380 $data[$key] = $value;
383 @trigger_error($this->getDeprecationMessage(sprintf('Duplicate key "%s" detected whilst parsing YAML. Silent handling of duplicate mapping keys in YAML is deprecated since Symfony 3.2 and will throw \Symfony\Component\Yaml\Exception\ParseException in 4.0.', $key)), E_USER_DEPRECATED);
387 $value = $this->parseValue(rtrim($values['value']), $flags, $context);
388 // Spec: Keys MUST be unique; first one wins.
389 // But overwriting is allowed when a merge node is used in current block.
390 if ($allowOverwrite || !isset($data[$key])) {
391 $data[$key] = $value;
393 @trigger_error($this->getDeprecationMessage(sprintf('Duplicate key "%s" detected whilst parsing YAML. Silent handling of duplicate mapping keys in YAML is deprecated since Symfony 3.2 and will throw \Symfony\Component\Yaml\Exception\ParseException in 4.0.', $key)), E_USER_DEPRECATED);
397 $this->refs[$isRef] = $data[$key];
400 // multiple documents are not supported
401 if ('---' === $this->currentLine) {
402 throw new ParseException('Multiple documents are not supported.', $this->currentLineNb + 1, $this->currentLine, $this->filename);
405 if ($deprecatedUsage = (isset($this->currentLine[1]) && '?' === $this->currentLine[0] && ' ' === $this->currentLine[1])) {
406 @trigger_error($this->getDeprecationMessage('Starting an unquoted string with a question mark followed by a space is deprecated since Symfony 3.3 and will throw \Symfony\Component\Yaml\Exception\ParseException in 4.0.'), E_USER_DEPRECATED);
409 // 1-liner optionally followed by newline(s)
410 if (\is_string($value) && $this->lines[0] === trim($value)) {
412 $value = Inline::parse($this->lines[0], $flags, $this->refs);
413 } catch (ParseException $e) {
414 $e->setParsedLine($this->getRealCurrentLineNb() + 1);
415 $e->setSnippet($this->currentLine);
423 // try to parse the value as a multi-line string as a last resort
424 if (0 === $this->currentLineNb) {
425 $previousLineWasNewline = false;
426 $previousLineWasTerminatedWithBackslash = false;
429 foreach ($this->lines as $line) {
430 // If the indentation is not consistent at offset 0, it is to be considered as a ParseError
431 if (0 === $this->offset && !$deprecatedUsage && isset($line[0]) && ' ' === $line[0]) {
432 throw new ParseException('Unable to parse.', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
434 if ('' === trim($line)) {
436 } elseif (!$previousLineWasNewline && !$previousLineWasTerminatedWithBackslash) {
440 if ('' !== trim($line) && '\\' === substr($line, -1)) {
441 $value .= ltrim(substr($line, 0, -1));
442 } elseif ('' !== trim($line)) {
443 $value .= trim($line);
446 if ('' === trim($line)) {
447 $previousLineWasNewline = true;
448 $previousLineWasTerminatedWithBackslash = false;
449 } elseif ('\\' === substr($line, -1)) {
450 $previousLineWasNewline = false;
451 $previousLineWasTerminatedWithBackslash = true;
453 $previousLineWasNewline = false;
454 $previousLineWasTerminatedWithBackslash = false;
459 return Inline::parse(trim($value));
460 } catch (ParseException $e) {
461 // fall-through to the ParseException thrown below
465 throw new ParseException('Unable to parse.', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
467 } while ($this->moveToNextLine());
470 $data = new TaggedValue($tag, $data);
473 if (Yaml::PARSE_OBJECT_FOR_MAP & $flags && !\is_object($data) && 'mapping' === $context) {
474 $object = new \stdClass();
476 foreach ($data as $key => $value) {
477 $object->$key = $value;
483 return empty($data) ? null : $data;
486 private function parseBlock($offset, $yaml, $flags)
488 $skippedLineNumbers = $this->skippedLineNumbers;
490 foreach ($this->locallySkippedLineNumbers as $lineNumber) {
491 if ($lineNumber < $offset) {
495 $skippedLineNumbers[] = $lineNumber;
498 $parser = new self();
499 $parser->offset = $offset;
500 $parser->totalNumberOfLines = $this->totalNumberOfLines;
501 $parser->skippedLineNumbers = $skippedLineNumbers;
502 $parser->refs = &$this->refs;
504 return $parser->doParse($yaml, $flags);
508 * Returns the current line number (takes the offset into account).
512 * @return int The current line number
514 public function getRealCurrentLineNb()
516 $realCurrentLineNumber = $this->currentLineNb + $this->offset;
518 foreach ($this->skippedLineNumbers as $skippedLineNumber) {
519 if ($skippedLineNumber > $realCurrentLineNumber) {
523 ++$realCurrentLineNumber;
526 return $realCurrentLineNumber;
530 * Returns the current line indentation.
532 * @return int The current line indentation
534 private function getCurrentLineIndentation()
536 return \strlen($this->currentLine) - \strlen(ltrim($this->currentLine, ' '));
540 * Returns the next embed block of YAML.
542 * @param int $indentation The indent level at which the block is to be read, or null for default
543 * @param bool $inSequence True if the enclosing data structure is a sequence
545 * @return string A YAML string
547 * @throws ParseException When indentation problem are detected
549 private function getNextEmbedBlock($indentation = null, $inSequence = false)
551 $oldLineIndentation = $this->getCurrentLineIndentation();
553 if (!$this->moveToNextLine()) {
557 if (null === $indentation) {
564 // empty and comment-like lines do not influence the indentation depth
565 if ($this->isCurrentLineEmpty() || $this->isCurrentLineComment()) {
566 $EOF = !$this->moveToNextLine();
572 $newIndent = $this->getCurrentLineIndentation();
574 } while (!$EOF && null === $newIndent);
576 for ($i = 0; $i < $movements; ++$i) {
577 $this->moveToPreviousLine();
580 $unindentedEmbedBlock = $this->isStringUnIndentedCollectionItem();
582 if (!$this->isCurrentLineEmpty() && 0 === $newIndent && !$unindentedEmbedBlock) {
583 throw new ParseException('Indentation problem.', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
586 $newIndent = $indentation;
590 if ($this->getCurrentLineIndentation() >= $newIndent) {
591 $data[] = substr($this->currentLine, $newIndent);
592 } elseif ($this->isCurrentLineEmpty() || $this->isCurrentLineComment()) {
593 $data[] = $this->currentLine;
595 $this->moveToPreviousLine();
600 if ($inSequence && $oldLineIndentation === $newIndent && isset($data[0][0]) && '-' === $data[0][0]) {
601 // the previous line contained a dash but no item content, this line is a sequence item with the same indentation
602 // and therefore no nested list or mapping
603 $this->moveToPreviousLine();
608 $isItUnindentedCollection = $this->isStringUnIndentedCollectionItem();
610 while ($this->moveToNextLine()) {
611 $indent = $this->getCurrentLineIndentation();
613 if ($isItUnindentedCollection && !$this->isCurrentLineEmpty() && !$this->isStringUnIndentedCollectionItem() && $newIndent === $indent) {
614 $this->moveToPreviousLine();
618 if ($this->isCurrentLineBlank()) {
619 $data[] = substr($this->currentLine, $newIndent);
623 if ($indent >= $newIndent) {
624 $data[] = substr($this->currentLine, $newIndent);
625 } elseif ($this->isCurrentLineComment()) {
626 $data[] = $this->currentLine;
627 } elseif (0 == $indent) {
628 $this->moveToPreviousLine();
632 throw new ParseException('Indentation problem.', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
636 return implode("\n", $data);
640 * Moves the parser to the next line.
644 private function moveToNextLine()
646 if ($this->currentLineNb >= \count($this->lines) - 1) {
650 $this->currentLine = $this->lines[++$this->currentLineNb];
656 * Moves the parser to the previous line.
660 private function moveToPreviousLine()
662 if ($this->currentLineNb < 1) {
666 $this->currentLine = $this->lines[--$this->currentLineNb];
672 * Parses a YAML value.
674 * @param string $value A YAML value
675 * @param int $flags A bit field of PARSE_* constants to customize the YAML parser behavior
676 * @param string $context The parser context (either sequence or mapping)
678 * @return mixed A PHP value
680 * @throws ParseException When reference does not exist
682 private function parseValue($value, $flags, $context)
684 if (0 === strpos($value, '*')) {
685 if (false !== $pos = strpos($value, '#')) {
686 $value = substr($value, 1, $pos - 2);
688 $value = substr($value, 1);
691 if (!array_key_exists($value, $this->refs)) {
692 throw new ParseException(sprintf('Reference "%s" does not exist.', $value), $this->currentLineNb + 1, $this->currentLine, $this->filename);
695 return $this->refs[$value];
698 if (self::preg_match('/^(?:'.self::TAG_PATTERN.' +)?'.self::BLOCK_SCALAR_HEADER_PATTERN.'$/', $value, $matches)) {
699 $modifiers = isset($matches['modifiers']) ? $matches['modifiers'] : '';
701 $data = $this->parseBlockScalar($matches['separator'], preg_replace('#\d+#', '', $modifiers), (int) abs($modifiers));
703 if ('' !== $matches['tag']) {
704 if ('!!binary' === $matches['tag']) {
705 return Inline::evaluateBinaryScalar($data);
706 } elseif ('tagged' === $matches['tag']) {
707 return new TaggedValue(substr($matches['tag'], 1), $data);
708 } elseif ('!' !== $matches['tag']) {
709 @trigger_error($this->getDeprecationMessage(sprintf('Using the custom tag "%s" for the value "%s" is deprecated since Symfony 3.3. It will be replaced by an instance of %s in 4.0.', $matches['tag'], $data, TaggedValue::class)), E_USER_DEPRECATED);
717 $quotation = '' !== $value && ('"' === $value[0] || "'" === $value[0]) ? $value[0] : null;
719 // do not take following lines into account when the current line is a quoted single line value
720 if (null !== $quotation && self::preg_match('/^'.$quotation.'.*'.$quotation.'(\s*#.*)?$/', $value)) {
721 return Inline::parse($value, $flags, $this->refs);
726 while ($this->moveToNextLine()) {
727 // unquoted strings end before the first unindented line
728 if (null === $quotation && 0 === $this->getCurrentLineIndentation()) {
729 $this->moveToPreviousLine();
734 $lines[] = trim($this->currentLine);
736 // quoted string values end with a line that is terminated with the quotation character
737 if ('' !== $this->currentLine && substr($this->currentLine, -1) === $quotation) {
742 for ($i = 0, $linesCount = \count($lines), $previousLineBlank = false; $i < $linesCount; ++$i) {
743 if ('' === $lines[$i]) {
745 $previousLineBlank = true;
746 } elseif ($previousLineBlank) {
747 $value .= $lines[$i];
748 $previousLineBlank = false;
750 $value .= ' '.$lines[$i];
751 $previousLineBlank = false;
755 Inline::$parsedLineNumber = $this->getRealCurrentLineNb();
757 $parsedValue = Inline::parse($value, $flags, $this->refs);
759 if ('mapping' === $context && \is_string($parsedValue) && '"' !== $value[0] && "'" !== $value[0] && '[' !== $value[0] && '{' !== $value[0] && '!' !== $value[0] && false !== strpos($parsedValue, ': ')) {
760 throw new ParseException('A colon cannot be used in an unquoted mapping value.', $this->getRealCurrentLineNb() + 1, $value, $this->filename);
764 } catch (ParseException $e) {
765 $e->setParsedLine($this->getRealCurrentLineNb() + 1);
766 $e->setSnippet($this->currentLine);
773 * Parses a block scalar.
775 * @param string $style The style indicator that was used to begin this block scalar (| or >)
776 * @param string $chomping The chomping indicator that was used to begin this block scalar (+ or -)
777 * @param int $indentation The indentation indicator that was used to begin this block scalar
779 * @return string The text value
781 private function parseBlockScalar($style, $chomping = '', $indentation = 0)
783 $notEOF = $this->moveToNextLine();
788 $isCurrentLineBlank = $this->isCurrentLineBlank();
789 $blockLines = array();
791 // leading blank lines are consumed before determining indentation
792 while ($notEOF && $isCurrentLineBlank) {
793 // newline only if not EOF
794 if ($notEOF = $this->moveToNextLine()) {
796 $isCurrentLineBlank = $this->isCurrentLineBlank();
800 // determine indentation if not specified
801 if (0 === $indentation) {
802 if (self::preg_match('/^ +/', $this->currentLine, $matches)) {
803 $indentation = \strlen($matches[0]);
807 if ($indentation > 0) {
808 $pattern = sprintf('/^ {%d}(.*)$/', $indentation);
812 $isCurrentLineBlank ||
813 self::preg_match($pattern, $this->currentLine, $matches)
816 if ($isCurrentLineBlank && \strlen($this->currentLine) > $indentation) {
817 $blockLines[] = substr($this->currentLine, $indentation);
818 } elseif ($isCurrentLineBlank) {
821 $blockLines[] = $matches[1];
824 // newline only if not EOF
825 if ($notEOF = $this->moveToNextLine()) {
826 $isCurrentLineBlank = $this->isCurrentLineBlank();
835 $this->moveToPreviousLine();
836 } elseif (!$notEOF && !$this->isCurrentLineLastLineInDocument()) {
841 if ('>' === $style) {
843 $previousLineIndented = false;
844 $previousLineBlank = false;
846 for ($i = 0, $blockLinesCount = \count($blockLines); $i < $blockLinesCount; ++$i) {
847 if ('' === $blockLines[$i]) {
849 $previousLineIndented = false;
850 $previousLineBlank = true;
851 } elseif (' ' === $blockLines[$i][0]) {
852 $text .= "\n".$blockLines[$i];
853 $previousLineIndented = true;
854 $previousLineBlank = false;
855 } elseif ($previousLineIndented) {
856 $text .= "\n".$blockLines[$i];
857 $previousLineIndented = false;
858 $previousLineBlank = false;
859 } elseif ($previousLineBlank || 0 === $i) {
860 $text .= $blockLines[$i];
861 $previousLineIndented = false;
862 $previousLineBlank = false;
864 $text .= ' '.$blockLines[$i];
865 $previousLineIndented = false;
866 $previousLineBlank = false;
870 $text = implode("\n", $blockLines);
873 // deal with trailing newlines
874 if ('' === $chomping) {
875 $text = preg_replace('/\n+$/', "\n", $text);
876 } elseif ('-' === $chomping) {
877 $text = preg_replace('/\n+$/', '', $text);
884 * Returns true if the next line is indented.
886 * @return bool Returns true if the next line is indented, false otherwise
888 private function isNextLineIndented()
890 $currentIndentation = $this->getCurrentLineIndentation();
894 $EOF = !$this->moveToNextLine();
899 } while (!$EOF && ($this->isCurrentLineEmpty() || $this->isCurrentLineComment()));
905 $ret = $this->getCurrentLineIndentation() > $currentIndentation;
907 for ($i = 0; $i < $movements; ++$i) {
908 $this->moveToPreviousLine();
915 * Returns true if the current line is blank or if it is a comment line.
917 * @return bool Returns true if the current line is empty or if it is a comment line, false otherwise
919 private function isCurrentLineEmpty()
921 return $this->isCurrentLineBlank() || $this->isCurrentLineComment();
925 * Returns true if the current line is blank.
927 * @return bool Returns true if the current line is blank, false otherwise
929 private function isCurrentLineBlank()
931 return '' == trim($this->currentLine, ' ');
935 * Returns true if the current line is a comment line.
937 * @return bool Returns true if the current line is a comment line, false otherwise
939 private function isCurrentLineComment()
941 //checking explicitly the first char of the trim is faster than loops or strpos
942 $ltrimmedLine = ltrim($this->currentLine, ' ');
944 return '' !== $ltrimmedLine && '#' === $ltrimmedLine[0];
947 private function isCurrentLineLastLineInDocument()
949 return ($this->offset + $this->currentLineNb) >= ($this->totalNumberOfLines - 1);
953 * Cleanups a YAML string to be parsed.
955 * @param string $value The input YAML string
957 * @return string A cleaned up YAML string
959 private function cleanup($value)
961 $value = str_replace(array("\r\n", "\r"), "\n", $value);
965 $value = preg_replace('#^\%YAML[: ][\d\.]+.*\n#u', '', $value, -1, $count);
966 $this->offset += $count;
968 // remove leading comments
969 $trimmedValue = preg_replace('#^(\#.*?\n)+#s', '', $value, -1, $count);
971 // items have been removed, update the offset
972 $this->offset += substr_count($value, "\n") - substr_count($trimmedValue, "\n");
973 $value = $trimmedValue;
976 // remove start of the document marker (---)
977 $trimmedValue = preg_replace('#^\-\-\-.*?\n#s', '', $value, -1, $count);
979 // items have been removed, update the offset
980 $this->offset += substr_count($value, "\n") - substr_count($trimmedValue, "\n");
981 $value = $trimmedValue;
983 // remove end of the document marker (...)
984 $value = preg_replace('#\.\.\.\s*$#', '', $value);
991 * Returns true if the next line starts unindented collection.
993 * @return bool Returns true if the next line starts unindented collection, false otherwise
995 private function isNextLineUnIndentedCollection()
997 $currentIndentation = $this->getCurrentLineIndentation();
1001 $EOF = !$this->moveToNextLine();
1006 } while (!$EOF && ($this->isCurrentLineEmpty() || $this->isCurrentLineComment()));
1012 $ret = $this->getCurrentLineIndentation() === $currentIndentation && $this->isStringUnIndentedCollectionItem();
1014 for ($i = 0; $i < $movements; ++$i) {
1015 $this->moveToPreviousLine();
1022 * Returns true if the string is un-indented collection item.
1024 * @return bool Returns true if the string is un-indented collection item, false otherwise
1026 private function isStringUnIndentedCollectionItem()
1028 return '-' === rtrim($this->currentLine) || 0 === strpos($this->currentLine, '- ');
1032 * A local wrapper for `preg_match` which will throw a ParseException if there
1033 * is an internal error in the PCRE engine.
1035 * This avoids us needing to check for "false" every time PCRE is used
1036 * in the YAML engine
1038 * @throws ParseException on a PCRE internal error
1040 * @see preg_last_error()
1044 public static function preg_match($pattern, $subject, &$matches = null, $flags = 0, $offset = 0)
1046 if (false === $ret = preg_match($pattern, $subject, $matches, $flags, $offset)) {
1047 switch (preg_last_error()) {
1048 case PREG_INTERNAL_ERROR:
1049 $error = 'Internal PCRE error.';
1051 case PREG_BACKTRACK_LIMIT_ERROR:
1052 $error = 'pcre.backtrack_limit reached.';
1054 case PREG_RECURSION_LIMIT_ERROR:
1055 $error = 'pcre.recursion_limit reached.';
1057 case PREG_BAD_UTF8_ERROR:
1058 $error = 'Malformed UTF-8 data.';
1060 case PREG_BAD_UTF8_OFFSET_ERROR:
1061 $error = 'Offset doesn\'t correspond to the begin of a valid UTF-8 code point.';
1067 throw new ParseException($error);
1074 * Trim the tag on top of the value.
1076 * Prevent values such as `!foo {quz: bar}` to be considered as
1079 private function trimTag($value)
1081 if ('!' === $value[0]) {
1082 return ltrim(substr($value, 1, strcspn($value, " \r\n", 1)), ' ');
1088 private function getLineTag($value, $flags, $nextLineCheck = true)
1090 if ('' === $value || '!' !== $value[0] || 1 !== self::preg_match('/^'.self::TAG_PATTERN.' *( +#.*)?$/', $value, $matches)) {
1094 if ($nextLineCheck && !$this->isNextLineIndented()) {
1098 $tag = substr($matches['tag'], 1);
1101 if ($tag && '!' === $tag[0]) {
1102 throw new ParseException(sprintf('The built-in tag "!%s" is not implemented.', $tag), $this->getRealCurrentLineNb() + 1, $value, $this->filename);
1105 if (Yaml::PARSE_CUSTOM_TAGS & $flags) {
1109 throw new ParseException(sprintf('Tags support is not enabled. You must use the flag `Yaml::PARSE_CUSTOM_TAGS` to use "%s".', $matches['tag']), $this->getRealCurrentLineNb() + 1, $value, $this->filename);
1112 private function getDeprecationMessage($message)
1114 $message = rtrim($message, '.');
1116 if (null !== $this->filename) {
1117 $message .= ' in '.$this->filename;
1120 $message .= ' on line '.($this->getRealCurrentLineNb() + 1);
1122 return $message.'.';