Debian Codegraph @

vendor/symfony/yaml/Parser.php

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