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