vendor/symfony/yaml/Parser.php line 100

Open in your IDE?
  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. use Symfony\Component\Yaml\Tag\TaggedValue;
  13. /**
  14.  * Parser parses YAML strings to convert them to PHP arrays.
  15.  *
  16.  * @author Fabien Potencier <fabien@symfony.com>
  17.  *
  18.  * @final
  19.  */
  20. class Parser
  21. {
  22.     public const TAG_PATTERN = '(?P<tag>![\w!.\/:-]+)';
  23.     public const BLOCK_SCALAR_HEADER_PATTERN = '(?P<separator>\||>)(?P<modifiers>\+|\-|\d+|\+\d+|\-\d+|\d+\+|\d+\-)?(?P<comments> +#.*)?';
  24.     public const REFERENCE_PATTERN = '#^&(?P<ref>[^ ]++) *+(?P<value>.*)#u';
  25.     private ?string $filename = null;
  26.     private int $offset = 0;
  27.     private int $numberOfParsedLines = 0;
  28.     private ?int $totalNumberOfLines = null;
  29.     private array $lines = [];
  30.     private int $currentLineNb = -1;
  31.     private string $currentLine = '';
  32.     private array $refs = [];
  33.     private array $skippedLineNumbers = [];
  34.     private array $locallySkippedLineNumbers = [];
  35.     private array $refsBeingParsed = [];
  36.     /**
  37.      * Parses a YAML file into a PHP value.
  38.      *
  39.      * @param string $filename The path to the YAML file to be parsed
  40.      * @param int    $flags    A bit field of PARSE_* constants to customize the YAML parser behavior
  41.      *
  42.      * @throws ParseException If the file could not be read or the YAML is not valid
  43.      */
  44.     public function parseFile(string $filename, int $flags = 0): mixed
  45.     {
  46.         if (!is_file($filename)) {
  47.             throw new ParseException(sprintf('File "%s" does not exist.', $filename));
  48.         }
  49.         if (!is_readable($filename)) {
  50.             throw new ParseException(sprintf('File "%s" cannot be read.', $filename));
  51.         }
  52.         $this->filename = $filename;
  53.         try {
  54.             return $this->parse(file_get_contents($filename), $flags);
  55.         } finally {
  56.             $this->filename = null;
  57.         }
  58.     }
  59.     /**
  60.      * Parses a YAML string to a PHP value.
  61.      *
  62.      * @param string $value A YAML string
  63.      * @param int    $flags A bit field of PARSE_* constants to customize the YAML parser behavior
  64.      *
  65.      * @throws ParseException If the YAML is not valid
  66.      */
  67.     public function parse(string $value, int $flags = 0): mixed
  68.     {
  69.         if (false === preg_match('//u', $value)) {
  70.             throw new ParseException('The YAML value does not appear to be valid UTF-8.', -1, null, $this->filename);
  71.         }
  72.         $this->refs = [];
  73.         try {
  74.             $data = $this->doParse($value, $flags);
  75.         } finally {
  76.             $this->lines = [];
  77.             $this->currentLine = '';
  78.             $this->numberOfParsedLines = 0;
  79.             $this->refs = [];
  80.             $this->skippedLineNumbers = [];
  81.             $this->locallySkippedLineNumbers = [];
  82.             $this->totalNumberOfLines = null;
  83.         }
  84.         return $data;
  85.     }
  86.     private function doParse(string $value, int $flags)
  87.     {
  88.         $this->currentLineNb = -1;
  89.         $this->currentLine = '';
  90.         $value = $this->cleanup($value);
  91.         $this->lines = explode("\n", $value);
  92.         $this->numberOfParsedLines = \count($this->lines);
  93.         $this->locallySkippedLineNumbers = [];
  94.         if (null === $this->totalNumberOfLines) {
  95.             $this->totalNumberOfLines = $this->numberOfParsedLines;
  96.         }
  97.         if (!$this->moveToNextLine()) {
  98.             return null;
  99.         }
  100.         $data = [];
  101.         $context = null;
  102.         $allowOverwrite = false;
  103.         while ($this->isCurrentLineEmpty()) {
  104.             if (!$this->moveToNextLine()) {
  105.                 return null;
  106.             }
  107.         }
  108.         // Resolves the tag and returns if end of the document
  109.         if (null !== ($tag = $this->getLineTag($this->currentLine, $flags, false)) && !$this->moveToNextLine()) {
  110.             return new TaggedValue($tag, '');
  111.         }
  112.         do {
  113.             if ($this->isCurrentLineEmpty()) {
  114.                 continue;
  115.             }
  116.             // tab?
  117.             if ("\t" === $this->currentLine[0]) {
  118.                 throw new ParseException('A YAML file cannot contain tabs as indentation.', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
  119.             }
  120.             Inline::initialize($flags, $this->getRealCurrentLineNb(), $this->filename);
  121.             $isRef = $mergeNode = false;
  122.             if ('-' === $this->currentLine[0] && self::preg_match('#^\-((?P<leadspaces>\s+)(?P<value>.+))?$#u', rtrim($this->currentLine), $values)) {
  123.                 if ($context && 'mapping' == $context) {
  124.                     throw new ParseException('You cannot define a sequence item when in a mapping.', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
  125.                 }
  126.                 $context = 'sequence';
  127.                 if (isset($values['value']) && '&' === $values['value'][0] && self::preg_match(self::REFERENCE_PATTERN, $values['value'], $matches)) {
  128.                     $isRef = $matches['ref'];
  129.                     $this->refsBeingParsed[] = $isRef;
  130.                     $values['value'] = $matches['value'];
  131.                 }
  132.                 if (isset($values['value'][1]) && '?' === $values['value'][0] && ' ' === $values['value'][1]) {
  133.                     throw new ParseException('Complex mappings are not supported.', $this->getRealCurrentLineNb() + 1, $this->currentLine);
  134.                 }
  135.                 // array
  136.                 if (isset($values['value']) && 0 === strpos(ltrim($values['value'], ' '), '-')) {
  137.                     // Inline first child
  138.                     $currentLineNumber = $this->getRealCurrentLineNb();
  139.                     $sequenceIndentation = \strlen($values['leadspaces']) + 1;
  140.                     $sequenceYaml = substr($this->currentLine, $sequenceIndentation);
  141.                     $sequenceYaml .= "\n".$this->getNextEmbedBlock($sequenceIndentation, true);
  142.                     $data[] = $this->parseBlock($currentLineNumber, rtrim($sequenceYaml), $flags);
  143.                 } elseif (!isset($values['value']) || '' == trim($values['value'], ' ') || 0 === strpos(ltrim($values['value'], ' '), '#')) {
  144.                     $data[] = $this->parseBlock($this->getRealCurrentLineNb() + 1, $this->getNextEmbedBlock(null, true) ?? '', $flags);
  145.                 } elseif (null !== $subTag = $this->getLineTag(ltrim($values['value'], ' '), $flags)) {
  146.                     $data[] = new TaggedValue(
  147.                         $subTag,
  148.                         $this->parseBlock($this->getRealCurrentLineNb() + 1, $this->getNextEmbedBlock(null, true), $flags)
  149.                     );
  150.                 } else {
  151.                     if (
  152.                         isset($values['leadspaces'])
  153.                         && (
  154.                             '!' === $values['value'][0]
  155.                             || self::preg_match('#^(?P<key>'.Inline::REGEX_QUOTED_STRING.'|[^ \'"\{\[].*?) *\:(\s+(?P<value>.+?))?\s*$#u', $this->trimTag($values['value']), $matches)
  156.                         )
  157.                     ) {
  158.                         // this is a compact notation element, add to next block and parse
  159.                         $block = $values['value'];
  160.                         if ($this->isNextLineIndented()) {
  161.                             $block .= "\n".$this->getNextEmbedBlock($this->getCurrentLineIndentation() + \strlen($values['leadspaces']) + 1);
  162.                         }
  163.                         $data[] = $this->parseBlock($this->getRealCurrentLineNb(), $block, $flags);
  164.                     } else {
  165.                         $data[] = $this->parseValue($values['value'], $flags, $context);
  166.                     }
  167.                 }
  168.                 if ($isRef) {
  169.                     $this->refs[$isRef] = end($data);
  170.                     array_pop($this->refsBeingParsed);
  171.                 }
  172.             } elseif (
  173.                 self::preg_match('#^(?P<key>(?:![^\s]++\s++)?(?:'.Inline::REGEX_QUOTED_STRING.'|(?:!?!php/const:)?[^ \'"\[\{!].*?)) *\:(( |\t)++(?P<value>.+))?$#u', rtrim($this->currentLine), $values)
  174.                 && (false === strpos($values['key'], ' #') || \in_array($values['key'][0], ['"', "'"]))
  175.             ) {
  176.                 if ($context && 'sequence' == $context) {
  177.                     throw new ParseException('You cannot define a mapping item when in a sequence.', $this->currentLineNb + 1, $this->currentLine, $this->filename);
  178.                 }
  179.                 $context = 'mapping';
  180.                 try {
  181.                     $key = Inline::parseScalar($values['key']);
  182.                 } catch (ParseException $e) {
  183.                     $e->setParsedLine($this->getRealCurrentLineNb() + 1);
  184.                     $e->setSnippet($this->currentLine);
  185.                     throw $e;
  186.                 }
  187.                 if (!\is_string($key) && !\is_int($key)) {
  188.                     throw new ParseException((is_numeric($key) ? 'Numeric' : 'Non-string').' keys are not supported. Quote your evaluable mapping keys instead.', $this->getRealCurrentLineNb() + 1, $this->currentLine);
  189.                 }
  190.                 // Convert float keys to strings, to avoid being converted to integers by PHP
  191.                 if (\is_float($key)) {
  192.                     $key = (string) $key;
  193.                 }
  194.                 if ('<<' === $key && (!isset($values['value']) || '&' !== $values['value'][0] || !self::preg_match('#^&(?P<ref>[^ ]+)#u', $values['value'], $refMatches))) {
  195.                     $mergeNode = true;
  196.                     $allowOverwrite = true;
  197.                     if (isset($values['value'][0]) && '*' === $values['value'][0]) {
  198.                         $refName = substr(rtrim($values['value']), 1);
  199.                         if (!\array_key_exists($refName, $this->refs)) {
  200.                             if (false !== $pos = array_search($refName, $this->refsBeingParsed, true)) {
  201.                                 throw new ParseException(sprintf('Circular reference [%s] detected for reference "%s".', implode(', ', array_merge(\array_slice($this->refsBeingParsed, $pos), [$refName])), $refName), $this->currentLineNb + 1, $this->currentLine, $this->filename);
  202.                             }
  203.                             throw new ParseException(sprintf('Reference "%s" does not exist.', $refName), $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
  204.                         }
  205.                         $refValue = $this->refs[$refName];
  206.                         if (Yaml::PARSE_OBJECT_FOR_MAP & $flags && $refValue instanceof \stdClass) {
  207.                             $refValue = (array) $refValue;
  208.                         }
  209.                         if (!\is_array($refValue)) {
  210.                             throw new ParseException('YAML merge keys used with a scalar value instead of an array.', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
  211.                         }
  212.                         $data += $refValue; // array union
  213.                     } else {
  214.                         if (isset($values['value']) && '' !== $values['value']) {
  215.                             $value = $values['value'];
  216.                         } else {
  217.                             $value = $this->getNextEmbedBlock();
  218.                         }
  219.                         $parsed = $this->parseBlock($this->getRealCurrentLineNb() + 1, $value, $flags);
  220.                         if (Yaml::PARSE_OBJECT_FOR_MAP & $flags && $parsed instanceof \stdClass) {
  221.                             $parsed = (array) $parsed;
  222.                         }
  223.                         if (!\is_array($parsed)) {
  224.                             throw new ParseException('YAML merge keys used with a scalar value instead of an array.', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
  225.                         }
  226.                         if (isset($parsed[0])) {
  227.                             // If the value associated with the merge key is a sequence, then this sequence is expected to contain mapping nodes
  228.                             // and each of these nodes is merged in turn according to its order in the sequence. Keys in mapping nodes earlier
  229.                             // in the sequence override keys specified in later mapping nodes.
  230.                             foreach ($parsed as $parsedItem) {
  231.                                 if (Yaml::PARSE_OBJECT_FOR_MAP & $flags && $parsedItem instanceof \stdClass) {
  232.                                     $parsedItem = (array) $parsedItem;
  233.                                 }
  234.                                 if (!\is_array($parsedItem)) {
  235.                                     throw new ParseException('Merge items must be arrays.', $this->getRealCurrentLineNb() + 1, $parsedItem, $this->filename);
  236.                                 }
  237.                                 $data += $parsedItem; // array union
  238.                             }
  239.                         } else {
  240.                             // If the value associated with the key is a single mapping node, each of its key/value pairs is inserted into the
  241.                             // current mapping, unless the key already exists in it.
  242.                             $data += $parsed; // array union
  243.                         }
  244.                     }
  245.                 } elseif ('<<' !== $key && isset($values['value']) && '&' === $values['value'][0] && self::preg_match(self::REFERENCE_PATTERN, $values['value'], $matches)) {
  246.                     $isRef = $matches['ref'];
  247.                     $this->refsBeingParsed[] = $isRef;
  248.                     $values['value'] = $matches['value'];
  249.                 }
  250.                 $subTag = null;
  251.                 if ($mergeNode) {
  252.                     // Merge keys
  253.                 } elseif (!isset($values['value']) || '' === $values['value'] || 0 === strpos($values['value'], '#') || (null !== $subTag = $this->getLineTag($values['value'], $flags)) || '<<' === $key) {
  254.                     // hash
  255.                     // if next line is less indented or equal, then it means that the current value is null
  256.                     if (!$this->isNextLineIndented() && !$this->isNextLineUnIndentedCollection()) {
  257.                         // Spec: Keys MUST be unique; first one wins.
  258.                         // But overwriting is allowed when a merge node is used in current block.
  259.                         if ($allowOverwrite || !isset($data[$key])) {
  260.                             if (null !== $subTag) {
  261.                                 $data[$key] = new TaggedValue($subTag, '');
  262.                             } else {
  263.                                 $data[$key] = null;
  264.                             }
  265.                         } else {
  266.                             throw new ParseException(sprintf('Duplicate key "%s" detected.', $key), $this->getRealCurrentLineNb() + 1, $this->currentLine);
  267.                         }
  268.                     } else {
  269.                         // remember the parsed line number here in case we need it to provide some contexts in error messages below
  270.                         $realCurrentLineNbKey = $this->getRealCurrentLineNb();
  271.                         $value = $this->parseBlock($this->getRealCurrentLineNb() + 1, $this->getNextEmbedBlock(), $flags);
  272.                         if ('<<' === $key) {
  273.                             $this->refs[$refMatches['ref']] = $value;
  274.                             if (Yaml::PARSE_OBJECT_FOR_MAP & $flags && $value instanceof \stdClass) {
  275.                                 $value = (array) $value;
  276.                             }
  277.                             $data += $value;
  278.                         } elseif ($allowOverwrite || !isset($data[$key])) {
  279.                             // Spec: Keys MUST be unique; first one wins.
  280.                             // But overwriting is allowed when a merge node is used in current block.
  281.                             if (null !== $subTag) {
  282.                                 $data[$key] = new TaggedValue($subTag, $value);
  283.                             } else {
  284.                                 $data[$key] = $value;
  285.                             }
  286.                         } else {
  287.                             throw new ParseException(sprintf('Duplicate key "%s" detected.', $key), $realCurrentLineNbKey + 1, $this->currentLine);
  288.                         }
  289.                     }
  290.                 } else {
  291.                     $value = $this->parseValue(rtrim($values['value']), $flags, $context);
  292.                     // Spec: Keys MUST be unique; first one wins.
  293.                     // But overwriting is allowed when a merge node is used in current block.
  294.                     if ($allowOverwrite || !isset($data[$key])) {
  295.                         $data[$key] = $value;
  296.                     } else {
  297.                         throw new ParseException(sprintf('Duplicate key "%s" detected.', $key), $this->getRealCurrentLineNb() + 1, $this->currentLine);
  298.                     }
  299.                 }
  300.                 if ($isRef) {
  301.                     $this->refs[$isRef] = $data[$key];
  302.                     array_pop($this->refsBeingParsed);
  303.                 }
  304.             } elseif ('"' === $this->currentLine[0] || "'" === $this->currentLine[0]) {
  305.                 if (null !== $context) {
  306.                     throw new ParseException('Unable to parse.', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
  307.                 }
  308.                 try {
  309.                     return Inline::parse($this->lexInlineQuotedString(), $flags, $this->refs);
  310.                 } catch (ParseException $e) {
  311.                     $e->setParsedLine($this->getRealCurrentLineNb() + 1);
  312.                     $e->setSnippet($this->currentLine);
  313.                     throw $e;
  314.                 }
  315.             } elseif ('{' === $this->currentLine[0]) {
  316.                 if (null !== $context) {
  317.                     throw new ParseException('Unable to parse.', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
  318.                 }
  319.                 try {
  320.                     $parsedMapping = Inline::parse($this->lexInlineMapping(), $flags, $this->refs);
  321.                     while ($this->moveToNextLine()) {
  322.                         if (!$this->isCurrentLineEmpty()) {
  323.                             throw new ParseException('Unable to parse.', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
  324.                         }
  325.                     }
  326.                     return $parsedMapping;
  327.                 } catch (ParseException $e) {
  328.                     $e->setParsedLine($this->getRealCurrentLineNb() + 1);
  329.                     $e->setSnippet($this->currentLine);
  330.                     throw $e;
  331.                 }
  332.             } elseif ('[' === $this->currentLine[0]) {
  333.                 if (null !== $context) {
  334.                     throw new ParseException('Unable to parse.', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
  335.                 }
  336.                 try {
  337.                     $parsedSequence = Inline::parse($this->lexInlineSequence(), $flags, $this->refs);
  338.                     while ($this->moveToNextLine()) {
  339.                         if (!$this->isCurrentLineEmpty()) {
  340.                             throw new ParseException('Unable to parse.', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
  341.                         }
  342.                     }
  343.                     return $parsedSequence;
  344.                 } catch (ParseException $e) {
  345.                     $e->setParsedLine($this->getRealCurrentLineNb() + 1);
  346.                     $e->setSnippet($this->currentLine);
  347.                     throw $e;
  348.                 }
  349.             } else {
  350.                 // multiple documents are not supported
  351.                 if ('---' === $this->currentLine) {
  352.                     throw new ParseException('Multiple documents are not supported.', $this->currentLineNb + 1, $this->currentLine, $this->filename);
  353.                 }
  354.                 if ($deprecatedUsage = (isset($this->currentLine[1]) && '?' === $this->currentLine[0] && ' ' === $this->currentLine[1])) {
  355.                     throw new ParseException('Complex mappings are not supported.', $this->getRealCurrentLineNb() + 1, $this->currentLine);
  356.                 }
  357.                 // 1-liner optionally followed by newline(s)
  358.                 if (\is_string($value) && $this->lines[0] === trim($value)) {
  359.                     try {
  360.                         $value = Inline::parse($this->lines[0], $flags, $this->refs);
  361.                     } catch (ParseException $e) {
  362.                         $e->setParsedLine($this->getRealCurrentLineNb() + 1);
  363.                         $e->setSnippet($this->currentLine);
  364.                         throw $e;
  365.                     }
  366.                     return $value;
  367.                 }
  368.                 // try to parse the value as a multi-line string as a last resort
  369.                 if (0 === $this->currentLineNb) {
  370.                     $previousLineWasNewline = false;
  371.                     $previousLineWasTerminatedWithBackslash = false;
  372.                     $value = '';
  373.                     foreach ($this->lines as $line) {
  374.                         $trimmedLine = trim($line);
  375.                         if ('#' === ($trimmedLine[0] ?? '')) {
  376.                             continue;
  377.                         }
  378.                         // If the indentation is not consistent at offset 0, it is to be considered as a ParseError
  379.                         if (0 === $this->offset && !$deprecatedUsage && isset($line[0]) && ' ' === $line[0]) {
  380.                             throw new ParseException('Unable to parse.', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
  381.                         }
  382.                         if (false !== strpos($line, ': ')) {
  383.                             throw new ParseException('Mapping values are not allowed in multi-line blocks.', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
  384.                         }
  385.                         if ('' === $trimmedLine) {
  386.                             $value .= "\n";
  387.                         } elseif (!$previousLineWasNewline && !$previousLineWasTerminatedWithBackslash) {
  388.                             $value .= ' ';
  389.                         }
  390.                         if ('' !== $trimmedLine && '\\' === substr($line, -1)) {
  391.                             $value .= ltrim(substr($line, 0, -1));
  392.                         } elseif ('' !== $trimmedLine) {
  393.                             $value .= $trimmedLine;
  394.                         }
  395.                         if ('' === $trimmedLine) {
  396.                             $previousLineWasNewline = true;
  397.                             $previousLineWasTerminatedWithBackslash = false;
  398.                         } elseif ('\\' === substr($line, -1)) {
  399.                             $previousLineWasNewline = false;
  400.                             $previousLineWasTerminatedWithBackslash = true;
  401.                         } else {
  402.                             $previousLineWasNewline = false;
  403.                             $previousLineWasTerminatedWithBackslash = false;
  404.                         }
  405.                     }
  406.                     try {
  407.                         return Inline::parse(trim($value));
  408.                     } catch (ParseException $e) {
  409.                         // fall-through to the ParseException thrown below
  410.                     }
  411.                 }
  412.                 throw new ParseException('Unable to parse.', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
  413.             }
  414.         } while ($this->moveToNextLine());
  415.         if (null !== $tag) {
  416.             $data = new TaggedValue($tag, $data);
  417.         }
  418.         if (Yaml::PARSE_OBJECT_FOR_MAP & $flags && 'mapping' === $context && !\is_object($data)) {
  419.             $object = new \stdClass();
  420.             foreach ($data as $key => $value) {
  421.                 $object->$key = $value;
  422.             }
  423.             $data = $object;
  424.         }
  425.         return empty($data) ? null : $data;
  426.     }
  427.     private function parseBlock(int $offset, string $yaml, int $flags)
  428.     {
  429.         $skippedLineNumbers = $this->skippedLineNumbers;
  430.         foreach ($this->locallySkippedLineNumbers as $lineNumber) {
  431.             if ($lineNumber < $offset) {
  432.                 continue;
  433.             }
  434.             $skippedLineNumbers[] = $lineNumber;
  435.         }
  436.         $parser = new self();
  437.         $parser->offset = $offset;
  438.         $parser->totalNumberOfLines = $this->totalNumberOfLines;
  439.         $parser->skippedLineNumbers = $skippedLineNumbers;
  440.         $parser->refs = &$this->refs;
  441.         $parser->refsBeingParsed = $this->refsBeingParsed;
  442.         return $parser->doParse($yaml, $flags);
  443.     }
  444.     /**
  445.      * Returns the current line number (takes the offset into account).
  446.      *
  447.      * @internal
  448.      */
  449.     public function getRealCurrentLineNb(): int
  450.     {
  451.         $realCurrentLineNumber = $this->currentLineNb + $this->offset;
  452.         foreach ($this->skippedLineNumbers as $skippedLineNumber) {
  453.             if ($skippedLineNumber > $realCurrentLineNumber) {
  454.                 break;
  455.             }
  456.             ++$realCurrentLineNumber;
  457.         }
  458.         return $realCurrentLineNumber;
  459.     }
  460.     private function getCurrentLineIndentation(): int
  461.     {
  462.         if (' ' !== ($this->currentLine[0] ?? '')) {
  463.             return 0;
  464.         }
  465.         return \strlen($this->currentLine) - \strlen(ltrim($this->currentLine, ' '));
  466.     }
  467.     /**
  468.      * Returns the next embed block of YAML.
  469.      *
  470.      * @param int|null $indentation The indent level at which the block is to be read, or null for default
  471.      * @param bool     $inSequence  True if the enclosing data structure is a sequence
  472.      *
  473.      * @throws ParseException When indentation problem are detected
  474.      */
  475.     private function getNextEmbedBlock(int $indentation = null, bool $inSequence = false): string
  476.     {
  477.         $oldLineIndentation = $this->getCurrentLineIndentation();
  478.         if (!$this->moveToNextLine()) {
  479.             return '';
  480.         }
  481.         if (null === $indentation) {
  482.             $newIndent = null;
  483.             $movements = 0;
  484.             do {
  485.                 $EOF = false;
  486.                 // empty and comment-like lines do not influence the indentation depth
  487.                 if ($this->isCurrentLineEmpty() || $this->isCurrentLineComment()) {
  488.                     $EOF = !$this->moveToNextLine();
  489.                     if (!$EOF) {
  490.                         ++$movements;
  491.                     }
  492.                 } else {
  493.                     $newIndent = $this->getCurrentLineIndentation();
  494.                 }
  495.             } while (!$EOF && null === $newIndent);
  496.             for ($i = 0; $i < $movements; ++$i) {
  497.                 $this->moveToPreviousLine();
  498.             }
  499.             $unindentedEmbedBlock = $this->isStringUnIndentedCollectionItem();
  500.             if (!$this->isCurrentLineEmpty() && 0 === $newIndent && !$unindentedEmbedBlock) {
  501.                 throw new ParseException('Indentation problem.', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
  502.             }
  503.         } else {
  504.             $newIndent = $indentation;
  505.         }
  506.         $data = [];
  507.         if ($this->getCurrentLineIndentation() >= $newIndent) {
  508.             $data[] = substr($this->currentLine, $newIndent ?? 0);
  509.         } elseif ($this->isCurrentLineEmpty() || $this->isCurrentLineComment()) {
  510.             $data[] = $this->currentLine;
  511.         } else {
  512.             $this->moveToPreviousLine();
  513.             return '';
  514.         }
  515.         if ($inSequence && $oldLineIndentation === $newIndent && isset($data[0][0]) && '-' === $data[0][0]) {
  516.             // the previous line contained a dash but no item content, this line is a sequence item with the same indentation
  517.             // and therefore no nested list or mapping
  518.             $this->moveToPreviousLine();
  519.             return '';
  520.         }
  521.         $isItUnindentedCollection = $this->isStringUnIndentedCollectionItem();
  522.         $isItComment = $this->isCurrentLineComment();
  523.         while ($this->moveToNextLine()) {
  524.             if ($isItComment && !$isItUnindentedCollection) {
  525.                 $isItUnindentedCollection = $this->isStringUnIndentedCollectionItem();
  526.                 $isItComment = $this->isCurrentLineComment();
  527.             }
  528.             $indent = $this->getCurrentLineIndentation();
  529.             if ($isItUnindentedCollection && !$this->isCurrentLineEmpty() && !$this->isStringUnIndentedCollectionItem() && $newIndent === $indent) {
  530.                 $this->moveToPreviousLine();
  531.                 break;
  532.             }
  533.             if ($this->isCurrentLineBlank()) {
  534.                 $data[] = substr($this->currentLine, $newIndent);
  535.                 continue;
  536.             }
  537.             if ($indent >= $newIndent) {
  538.                 $data[] = substr($this->currentLine, $newIndent);
  539.             } elseif ($this->isCurrentLineComment()) {
  540.                 $data[] = $this->currentLine;
  541.             } elseif (0 == $indent) {
  542.                 $this->moveToPreviousLine();
  543.                 break;
  544.             } else {
  545.                 throw new ParseException('Indentation problem.', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename);
  546.             }
  547.         }
  548.         return implode("\n", $data);
  549.     }
  550.     private function hasMoreLines(): bool
  551.     {
  552.         return (\count($this->lines) - 1) > $this->currentLineNb;
  553.     }
  554.     /**
  555.      * Moves the parser to the next line.
  556.      */
  557.     private function moveToNextLine(): bool
  558.     {
  559.         if ($this->currentLineNb >= $this->numberOfParsedLines - 1) {
  560.             return false;
  561.         }
  562.         $this->currentLine = $this->lines[++$this->currentLineNb];
  563.         return true;
  564.     }
  565.     /**
  566.      * Moves the parser to the previous line.
  567.      */
  568.     private function moveToPreviousLine(): bool
  569.     {
  570.         if ($this->currentLineNb < 1) {
  571.             return false;
  572.         }
  573.         $this->currentLine = $this->lines[--$this->currentLineNb];
  574.         return true;
  575.     }
  576.     /**
  577.      * Parses a YAML value.
  578.      *
  579.      * @param string $value   A YAML value
  580.      * @param int    $flags   A bit field of PARSE_* constants to customize the YAML parser behavior
  581.      * @param string $context The parser context (either sequence or mapping)
  582.      *
  583.      * @throws ParseException When reference does not exist
  584.      */
  585.     private function parseValue(string $value, int $flags, string $context): mixed
  586.     {
  587.         if (0 === strpos($value, '*')) {
  588.             if (false !== $pos = strpos($value, '#')) {
  589.                 $value = substr($value, 1, $pos - 2);
  590.             } else {
  591.                 $value = substr($value, 1);
  592.             }
  593.             if (!\array_key_exists($value, $this->refs)) {
  594.                 if (false !== $pos = array_search($value, $this->refsBeingParsed, true)) {
  595.                     throw new ParseException(sprintf('Circular reference [%s] detected for reference "%s".', implode(', ', array_merge(\array_slice($this->refsBeingParsed, $pos), [$value])), $value), $this->currentLineNb + 1, $this->currentLine, $this->filename);
  596.                 }
  597.                 throw new ParseException(sprintf('Reference "%s" does not exist.', $value), $this->currentLineNb + 1, $this->currentLine, $this->filename);
  598.             }
  599.             return $this->refs[$value];
  600.         }
  601.         if (\in_array($value[0], ['!', '|', '>'], true) && self::preg_match('/^(?:'.self::TAG_PATTERN.' +)?'.self::BLOCK_SCALAR_HEADER_PATTERN.'$/', $value, $matches)) {
  602.             $modifiers = $matches['modifiers'] ?? '';
  603.             $data = $this->parseBlockScalar($matches['separator'], preg_replace('#\d+#', '', $modifiers), abs((int) $modifiers));
  604.             if ('' !== $matches['tag'] && '!' !== $matches['tag']) {
  605.                 if ('!!binary' === $matches['tag']) {
  606.                     return Inline::evaluateBinaryScalar($data);
  607.                 }
  608.                 return new TaggedValue(substr($matches['tag'], 1), $data);
  609.             }
  610.             return $data;
  611.         }
  612.         try {
  613.             if ('' !== $value && '{' === $value[0]) {
  614.                 $cursor = \strlen(rtrim($this->currentLine)) - \strlen(rtrim($value));
  615.                 return Inline::parse($this->lexInlineMapping($cursor), $flags, $this->refs);
  616.             } elseif ('' !== $value && '[' === $value[0]) {
  617.                 $cursor = \strlen(rtrim($this->currentLine)) - \strlen(rtrim($value));
  618.                 return Inline::parse($this->lexInlineSequence($cursor), $flags, $this->refs);
  619.             }
  620.             switch ($value[0] ?? '') {
  621.                 case '"':
  622.                 case "'":
  623.                     $cursor = \strlen(rtrim($this->currentLine)) - \strlen(rtrim($value));
  624.                     $parsedValue = Inline::parse($this->lexInlineQuotedString($cursor), $flags, $this->refs);
  625.                     if (isset($this->currentLine[$cursor]) && preg_replace('/\s*(#.*)?$/A', '', substr($this->currentLine, $cursor))) {
  626.                         throw new ParseException(sprintf('Unexpected characters near "%s".', substr($this->currentLine, $cursor)));
  627.                     }
  628.                     return $parsedValue;
  629.                 default:
  630.                     $lines = [];
  631.                     while ($this->moveToNextLine()) {
  632.                         // unquoted strings end before the first unindented line
  633.                         if (0 === $this->getCurrentLineIndentation()) {
  634.                             $this->moveToPreviousLine();
  635.                             break;
  636.                         }
  637.                         $lines[] = trim($this->currentLine);
  638.                     }
  639.                     for ($i = 0, $linesCount = \count($lines), $previousLineBlank = false; $i < $linesCount; ++$i) {
  640.                         if ('' === $lines[$i]) {
  641.                             $value .= "\n";
  642.                             $previousLineBlank = true;
  643.                         } elseif ($previousLineBlank) {
  644.                             $value .= $lines[$i];
  645.                             $previousLineBlank = false;
  646.                         } else {
  647.                             $value .= ' '.$lines[$i];
  648.                             $previousLineBlank = false;
  649.                         }
  650.                     }
  651.                     Inline::$parsedLineNumber = $this->getRealCurrentLineNb();
  652.                     $parsedValue = Inline::parse($value, $flags, $this->refs);
  653.                     if ('mapping' === $context && \is_string($parsedValue) && '"' !== $value[0] && "'" !== $value[0] && '[' !== $value[0] && '{' !== $value[0] && '!' !== $value[0] && false !== strpos($parsedValue, ': ')) {
  654.                         throw new ParseException('A colon cannot be used in an unquoted mapping value.', $this->getRealCurrentLineNb() + 1, $value, $this->filename);
  655.                     }
  656.                     return $parsedValue;
  657.             }
  658.         } catch (ParseException $e) {
  659.             $e->setParsedLine($this->getRealCurrentLineNb() + 1);
  660.             $e->setSnippet($this->currentLine);
  661.             throw $e;
  662.         }
  663.     }
  664.     /**
  665.      * Parses a block scalar.
  666.      *
  667.      * @param string $style       The style indicator that was used to begin this block scalar (| or >)
  668.      * @param string $chomping    The chomping indicator that was used to begin this block scalar (+ or -)
  669.      * @param int    $indentation The indentation indicator that was used to begin this block scalar
  670.      */
  671.     private function parseBlockScalar(string $style, string $chomping = '', int $indentation = 0): string
  672.     {
  673.         $notEOF = $this->moveToNextLine();
  674.         if (!$notEOF) {
  675.             return '';
  676.         }
  677.         $isCurrentLineBlank = $this->isCurrentLineBlank();
  678.         $blockLines = [];
  679.         // leading blank lines are consumed before determining indentation
  680.         while ($notEOF && $isCurrentLineBlank) {
  681.             // newline only if not EOF
  682.             if ($notEOF = $this->moveToNextLine()) {
  683.                 $blockLines[] = '';
  684.                 $isCurrentLineBlank = $this->isCurrentLineBlank();
  685.             }
  686.         }
  687.         // determine indentation if not specified
  688.         if (0 === $indentation) {
  689.             $currentLineLength = \strlen($this->currentLine);
  690.             for ($i = 0; $i < $currentLineLength && ' ' === $this->currentLine[$i]; ++$i) {
  691.                 ++$indentation;
  692.             }
  693.         }
  694.         if ($indentation > 0) {
  695.             $pattern = sprintf('/^ {%d}(.*)$/', $indentation);
  696.             while (
  697.                 $notEOF && (
  698.                     $isCurrentLineBlank ||
  699.                     self::preg_match($pattern, $this->currentLine, $matches)
  700.                 )
  701.             ) {
  702.                 if ($isCurrentLineBlank && \strlen($this->currentLine) > $indentation) {
  703.                     $blockLines[] = substr($this->currentLine, $indentation);
  704.                 } elseif ($isCurrentLineBlank) {
  705.                     $blockLines[] = '';
  706.                 } else {
  707.                     $blockLines[] = $matches[1];
  708.                 }
  709.                 // newline only if not EOF
  710.                 if ($notEOF = $this->moveToNextLine()) {
  711.                     $isCurrentLineBlank = $this->isCurrentLineBlank();
  712.                 }
  713.             }
  714.         } elseif ($notEOF) {
  715.             $blockLines[] = '';
  716.         }
  717.         if ($notEOF) {
  718.             $blockLines[] = '';
  719.             $this->moveToPreviousLine();
  720.         } elseif (!$notEOF && !$this->isCurrentLineLastLineInDocument()) {
  721.             $blockLines[] = '';
  722.         }
  723.         // folded style
  724.         if ('>' === $style) {
  725.             $text = '';
  726.             $previousLineIndented = false;
  727.             $previousLineBlank = false;
  728.             for ($i = 0, $blockLinesCount = \count($blockLines); $i < $blockLinesCount; ++$i) {
  729.                 if ('' === $blockLines[$i]) {
  730.                     $text .= "\n";
  731.                     $previousLineIndented = false;
  732.                     $previousLineBlank = true;
  733.                 } elseif (' ' === $blockLines[$i][0]) {
  734.                     $text .= "\n".$blockLines[$i];
  735.                     $previousLineIndented = true;
  736.                     $previousLineBlank = false;
  737.                 } elseif ($previousLineIndented) {
  738.                     $text .= "\n".$blockLines[$i];
  739.                     $previousLineIndented = false;
  740.                     $previousLineBlank = false;
  741.                 } elseif ($previousLineBlank || 0 === $i) {
  742.                     $text .= $blockLines[$i];
  743.                     $previousLineIndented = false;
  744.                     $previousLineBlank = false;
  745.                 } else {
  746.                     $text .= ' '.$blockLines[$i];
  747.                     $previousLineIndented = false;
  748.                     $previousLineBlank = false;
  749.                 }
  750.             }
  751.         } else {
  752.             $text = implode("\n", $blockLines);
  753.         }
  754.         // deal with trailing newlines
  755.         if ('' === $chomping) {
  756.             $text = preg_replace('/\n+$/', "\n", $text);
  757.         } elseif ('-' === $chomping) {
  758.             $text = preg_replace('/\n+$/', '', $text);
  759.         }
  760.         return $text;
  761.     }
  762.     /**
  763.      * Returns true if the next line is indented.
  764.      */
  765.     private function isNextLineIndented(): bool
  766.     {
  767.         $currentIndentation = $this->getCurrentLineIndentation();
  768.         $movements = 0;
  769.         do {
  770.             $EOF = !$this->moveToNextLine();
  771.             if (!$EOF) {
  772.                 ++$movements;
  773.             }
  774.         } while (!$EOF && ($this->isCurrentLineEmpty() || $this->isCurrentLineComment()));
  775.         if ($EOF) {
  776.             return false;
  777.         }
  778.         $ret = $this->getCurrentLineIndentation() > $currentIndentation;
  779.         for ($i = 0; $i < $movements; ++$i) {
  780.             $this->moveToPreviousLine();
  781.         }
  782.         return $ret;
  783.     }
  784.     private function isCurrentLineEmpty(): bool
  785.     {
  786.         return $this->isCurrentLineBlank() || $this->isCurrentLineComment();
  787.     }
  788.     private function isCurrentLineBlank(): bool
  789.     {
  790.         return '' === $this->currentLine || '' === trim($this->currentLine, ' ');
  791.     }
  792.     private function isCurrentLineComment(): bool
  793.     {
  794.         //checking explicitly the first char of the trim is faster than loops or strpos
  795.         $ltrimmedLine = '' !== $this->currentLine && ' ' === $this->currentLine[0] ? ltrim($this->currentLine, ' ') : $this->currentLine;
  796.         return '' !== $ltrimmedLine && '#' === $ltrimmedLine[0];
  797.     }
  798.     private function isCurrentLineLastLineInDocument(): bool
  799.     {
  800.         return ($this->offset + $this->currentLineNb) >= ($this->totalNumberOfLines - 1);
  801.     }
  802.     private function cleanup(string $value): string
  803.     {
  804.         $value = str_replace(["\r\n", "\r"], "\n", $value);
  805.         // strip YAML header
  806.         $count = 0;
  807.         $value = preg_replace('#^\%YAML[: ][\d\.]+.*\n#u', '', $value, -1, $count);
  808.         $this->offset += $count;
  809.         // remove leading comments
  810.         $trimmedValue = preg_replace('#^(\#.*?\n)+#s', '', $value, -1, $count);
  811.         if (1 === $count) {
  812.             // items have been removed, update the offset
  813.             $this->offset += substr_count($value, "\n") - substr_count($trimmedValue, "\n");
  814.             $value = $trimmedValue;
  815.         }
  816.         // remove start of the document marker (---)
  817.         $trimmedValue = preg_replace('#^\-\-\-.*?\n#s', '', $value, -1, $count);
  818.         if (1 === $count) {
  819.             // items have been removed, update the offset
  820.             $this->offset += substr_count($value, "\n") - substr_count($trimmedValue, "\n");
  821.             $value = $trimmedValue;
  822.             // remove end of the document marker (...)
  823.             $value = preg_replace('#\.\.\.\s*$#', '', $value);
  824.         }
  825.         return $value;
  826.     }
  827.     private function isNextLineUnIndentedCollection(): bool
  828.     {
  829.         $currentIndentation = $this->getCurrentLineIndentation();
  830.         $movements = 0;
  831.         do {
  832.             $EOF = !$this->moveToNextLine();
  833.             if (!$EOF) {
  834.                 ++$movements;
  835.             }
  836.         } while (!$EOF && ($this->isCurrentLineEmpty() || $this->isCurrentLineComment()));
  837.         if ($EOF) {
  838.             return false;
  839.         }
  840.         $ret = $this->getCurrentLineIndentation() === $currentIndentation && $this->isStringUnIndentedCollectionItem();
  841.         for ($i = 0; $i < $movements; ++$i) {
  842.             $this->moveToPreviousLine();
  843.         }
  844.         return $ret;
  845.     }
  846.     private function isStringUnIndentedCollectionItem(): bool
  847.     {
  848.         return '-' === rtrim($this->currentLine) || 0 === strpos($this->currentLine, '- ');
  849.     }
  850.     /**
  851.      * A local wrapper for "preg_match" which will throw a ParseException if there
  852.      * is an internal error in the PCRE engine.
  853.      *
  854.      * This avoids us needing to check for "false" every time PCRE is used
  855.      * in the YAML engine
  856.      *
  857.      * @throws ParseException on a PCRE internal error
  858.      *
  859.      * @see preg_last_error()
  860.      *
  861.      * @internal
  862.      */
  863.     public static function preg_match(string $pattern, string $subject, array &$matches = null, int $flags = 0, int $offset = 0): int
  864.     {
  865.         if (false === $ret = preg_match($pattern, $subject, $matches, $flags, $offset)) {
  866.             switch (preg_last_error()) {
  867.                 case \PREG_INTERNAL_ERROR:
  868.                     $error = 'Internal PCRE error.';
  869.                     break;
  870.                 case \PREG_BACKTRACK_LIMIT_ERROR:
  871.                     $error = 'pcre.backtrack_limit reached.';
  872.                     break;
  873.                 case \PREG_RECURSION_LIMIT_ERROR:
  874.                     $error = 'pcre.recursion_limit reached.';
  875.                     break;
  876.                 case \PREG_BAD_UTF8_ERROR:
  877.                     $error = 'Malformed UTF-8 data.';
  878.                     break;
  879.                 case \PREG_BAD_UTF8_OFFSET_ERROR:
  880.                     $error = 'Offset doesn\'t correspond to the begin of a valid UTF-8 code point.';
  881.                     break;
  882.                 default:
  883.                     $error = 'Error.';
  884.             }
  885.             throw new ParseException($error);
  886.         }
  887.         return $ret;
  888.     }
  889.     /**
  890.      * Trim the tag on top of the value.
  891.      *
  892.      * Prevent values such as "!foo {quz: bar}" to be considered as
  893.      * a mapping block.
  894.      */
  895.     private function trimTag(string $value): string
  896.     {
  897.         if ('!' === $value[0]) {
  898.             return ltrim(substr($value, 1, strcspn($value, " \r\n", 1)), ' ');
  899.         }
  900.         return $value;
  901.     }
  902.     private function getLineTag(string $value, int $flags, bool $nextLineCheck = true): ?string
  903.     {
  904.         if ('' === $value || '!' !== $value[0] || 1 !== self::preg_match('/^'.self::TAG_PATTERN.' *( +#.*)?$/', $value, $matches)) {
  905.             return null;
  906.         }
  907.         if ($nextLineCheck && !$this->isNextLineIndented()) {
  908.             return null;
  909.         }
  910.         $tag = substr($matches['tag'], 1);
  911.         // Built-in tags
  912.         if ($tag && '!' === $tag[0]) {
  913.             throw new ParseException(sprintf('The built-in tag "!%s" is not implemented.', $tag), $this->getRealCurrentLineNb() + 1, $value, $this->filename);
  914.         }
  915.         if (Yaml::PARSE_CUSTOM_TAGS & $flags) {
  916.             return $tag;
  917.         }
  918.         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);
  919.     }
  920.     private function lexInlineQuotedString(int &$cursor = 0): string
  921.     {
  922.         $quotation = $this->currentLine[$cursor];
  923.         $value = $quotation;
  924.         ++$cursor;
  925.         $previousLineWasNewline = true;
  926.         $previousLineWasTerminatedWithBackslash = false;
  927.         $lineNumber = 0;
  928.         do {
  929.             if (++$lineNumber > 1) {
  930.                 $cursor += strspn($this->currentLine, ' ', $cursor);
  931.             }
  932.             if ($this->isCurrentLineBlank()) {
  933.                 $value .= "\n";
  934.             } elseif (!$previousLineWasNewline && !$previousLineWasTerminatedWithBackslash) {
  935.                 $value .= ' ';
  936.             }
  937.             for (; \strlen($this->currentLine) > $cursor; ++$cursor) {
  938.                 switch ($this->currentLine[$cursor]) {
  939.                     case '\\':
  940.                         if ("'" === $quotation) {
  941.                             $value .= '\\';
  942.                         } elseif (isset($this->currentLine[++$cursor])) {
  943.                             $value .= '\\'.$this->currentLine[$cursor];
  944.                         }
  945.                         break;
  946.                     case $quotation:
  947.                         ++$cursor;
  948.                         if ("'" === $quotation && isset($this->currentLine[$cursor]) && "'" === $this->currentLine[$cursor]) {
  949.                             $value .= "''";
  950.                             break;
  951.                         }
  952.                         return $value.$quotation;
  953.                     default:
  954.                         $value .= $this->currentLine[$cursor];
  955.                 }
  956.             }
  957.             if ($this->isCurrentLineBlank()) {
  958.                 $previousLineWasNewline = true;
  959.                 $previousLineWasTerminatedWithBackslash = false;
  960.             } elseif ('\\' === $this->currentLine[-1]) {
  961.                 $previousLineWasNewline = false;
  962.                 $previousLineWasTerminatedWithBackslash = true;
  963.             } else {
  964.                 $previousLineWasNewline = false;
  965.                 $previousLineWasTerminatedWithBackslash = false;
  966.             }
  967.             if ($this->hasMoreLines()) {
  968.                 $cursor = 0;
  969.             }
  970.         } while ($this->moveToNextLine());
  971.         throw new ParseException('Malformed inline YAML string.');
  972.     }
  973.     private function lexUnquotedString(int &$cursor): string
  974.     {
  975.         $offset = $cursor;
  976.         $cursor += strcspn($this->currentLine, '[]{},: ', $cursor);
  977.         if ($cursor === $offset) {
  978.             throw new ParseException('Malformed unquoted YAML string.');
  979.         }
  980.         return substr($this->currentLine, $offset, $cursor - $offset);
  981.     }
  982.     private function lexInlineMapping(int &$cursor = 0): string
  983.     {
  984.         return $this->lexInlineStructure($cursor, '}');
  985.     }
  986.     private function lexInlineSequence(int &$cursor = 0): string
  987.     {
  988.         return $this->lexInlineStructure($cursor, ']');
  989.     }
  990.     private function lexInlineStructure(int &$cursor, string $closingTag): string
  991.     {
  992.         $value = $this->currentLine[$cursor];
  993.         ++$cursor;
  994.         do {
  995.             $this->consumeWhitespaces($cursor);
  996.             while (isset($this->currentLine[$cursor])) {
  997.                 switch ($this->currentLine[$cursor]) {
  998.                     case '"':
  999.                     case "'":
  1000.                         $value .= $this->lexInlineQuotedString($cursor);
  1001.                         break;
  1002.                     case ':':
  1003.                     case ',':
  1004.                         $value .= $this->currentLine[$cursor];
  1005.                         ++$cursor;
  1006.                         break;
  1007.                     case '{':
  1008.                         $value .= $this->lexInlineMapping($cursor);
  1009.                         break;
  1010.                     case '[':
  1011.                         $value .= $this->lexInlineSequence($cursor);
  1012.                         break;
  1013.                     case $closingTag:
  1014.                         $value .= $this->currentLine[$cursor];
  1015.                         ++$cursor;
  1016.                         return $value;
  1017.                     case '#':
  1018.                         break 2;
  1019.                     default:
  1020.                         $value .= $this->lexUnquotedString($cursor);
  1021.                 }
  1022.                 if ($this->consumeWhitespaces($cursor)) {
  1023.                     $value .= ' ';
  1024.                 }
  1025.             }
  1026.             if ($this->hasMoreLines()) {
  1027.                 $cursor = 0;
  1028.             }
  1029.         } while ($this->moveToNextLine());
  1030.         throw new ParseException('Malformed inline YAML string.');
  1031.     }
  1032.     private function consumeWhitespaces(int &$cursor): bool
  1033.     {
  1034.         $whitespacesConsumed = 0;
  1035.         do {
  1036.             $whitespaceOnlyTokenLength = strspn($this->currentLine, ' ', $cursor);
  1037.             $whitespacesConsumed += $whitespaceOnlyTokenLength;
  1038.             $cursor += $whitespaceOnlyTokenLength;
  1039.             if (isset($this->currentLine[$cursor])) {
  1040.                 return 0 < $whitespacesConsumed;
  1041.             }
  1042.             if ($this->hasMoreLines()) {
  1043.                 $cursor = 0;
  1044.             }
  1045.         } while ($this->moveToNextLine());
  1046.         return 0 < $whitespacesConsumed;
  1047.     }
  1048. }