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
12namespace Symfony\Component\Yaml;
13
14use Symfony\Component\Yaml\Exception\DumpException;
15use Symfony\Component\Yaml\Exception\ParseException;
16use Symfony\Component\Yaml\Tag\TaggedValue;
17
18/**
19 * Inline implements a YAML parser/dumper for the YAML inline syntax.
20 *
21 * @author Fabien Potencier <fabien@symfony.com>
22 *
23 * @internal
24 */
25class Inline
26{
27    public const REGEX_QUOTED_STRING = '(?:"([^"\\\\]*+(?:\\\\.[^"\\\\]*+)*+)"|\'([^\']*+(?:\'\'[^\']*+)*+)\')';
28
29    public static $parsedLineNumber = -1;
30    public static $parsedFilename;
31
32    private static $exceptionOnInvalidType = false;
33    private static $objectSupport = false;
34    private static $objectForMap = false;
35    private static $constantSupport = false;
36
37    public static function initialize(int $flags, int $parsedLineNumber = null, string $parsedFilename = null)
38    {
39        self::$exceptionOnInvalidType = (bool) (Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE & $flags);
40        self::$objectSupport = (bool) (Yaml::PARSE_OBJECT & $flags);
41        self::$objectForMap = (bool) (Yaml::PARSE_OBJECT_FOR_MAP & $flags);
42        self::$constantSupport = (bool) (Yaml::PARSE_CONSTANT & $flags);
43        self::$parsedFilename = $parsedFilename;
44
45        if (null !== $parsedLineNumber) {
46            self::$parsedLineNumber = $parsedLineNumber;
47        }
48    }
49
50    /**
51     * Converts a YAML string to a PHP value.
52     *
53     * @param string $value      A YAML string
54     * @param int    $flags      A bit field of PARSE_* constants to customize the YAML parser behavior
55     * @param array  $references Mapping of variable names to values
56     *
57     * @return mixed A PHP value
58     *
59     * @throws ParseException
60     */
61    public static function parse(string $value = null, int $flags = 0, array &$references = [])
62    {
63        self::initialize($flags);
64
65        $value = trim($value);
66
67        if ('' === $value) {
68            return '';
69        }
70
71        if (2 /* MB_OVERLOAD_STRING */ & (int) \ini_get('mbstring.func_overload')) {
72            $mbEncoding = mb_internal_encoding();
73            mb_internal_encoding('ASCII');
74        }
75
76        try {
77            $i = 0;
78            $tag = self::parseTag($value, $i, $flags);
79            switch ($value[$i]) {
80                case '[':
81                    $result = self::parseSequence($value, $flags, $i, $references);
82                    ++$i;
83                    break;
84                case '{':
85                    $result = self::parseMapping($value, $flags, $i, $references);
86                    ++$i;
87                    break;
88                default:
89                    $result = self::parseScalar($value, $flags, null, $i, null === $tag, $references);
90            }
91
92            // some comments are allowed at the end
93            if (preg_replace('/\s*#.*$/A', '', substr($value, $i))) {
94                throw new ParseException(sprintf('Unexpected characters near "%s".', substr($value, $i)), self::$parsedLineNumber + 1, $value, self::$parsedFilename);
95            }
96
97            if (null !== $tag && '' !== $tag) {
98                return new TaggedValue($tag, $result);
99            }
100
101            return $result;
102        } finally {
103            if (isset($mbEncoding)) {
104                mb_internal_encoding($mbEncoding);
105            }
106        }
107    }
108
109    /**
110     * Dumps a given PHP variable to a YAML string.
111     *
112     * @param mixed $value The PHP variable to convert
113     * @param int   $flags A bit field of Yaml::DUMP_* constants to customize the dumped YAML string
114     *
115     * @return string The YAML string representing the PHP value
116     *
117     * @throws DumpException When trying to dump PHP resource
118     */
119    public static function dump($value, int $flags = 0): string
120    {
121        switch (true) {
122            case \is_resource($value):
123                if (Yaml::DUMP_EXCEPTION_ON_INVALID_TYPE & $flags) {
124                    throw new DumpException(sprintf('Unable to dump PHP resources in a YAML file ("%s").', get_resource_type($value)));
125                }
126
127                return self::dumpNull($flags);
128            case $value instanceof \DateTimeInterface:
129                return $value->format('c');
130            case $value instanceof \UnitEnum:
131                return sprintf('!php/const %s::%s', \get_class($value), $value->name);
132            case \is_object($value):
133                if ($value instanceof TaggedValue) {
134                    return '!'.$value->getTag().' '.self::dump($value->getValue(), $flags);
135                }
136
137                if (Yaml::DUMP_OBJECT & $flags) {
138                    return '!php/object '.self::dump(serialize($value));
139                }
140
141                if (Yaml::DUMP_OBJECT_AS_MAP & $flags && ($value instanceof \stdClass || $value instanceof \ArrayObject)) {
142                    $output = [];
143
144                    foreach ($value as $key => $val) {
145                        $output[] = sprintf('%s: %s', self::dump($key, $flags), self::dump($val, $flags));
146                    }
147
148                    return sprintf('{ %s }', implode(', ', $output));
149                }
150
151                if (Yaml::DUMP_EXCEPTION_ON_INVALID_TYPE & $flags) {
152                    throw new DumpException('Object support when dumping a YAML file has been disabled.');
153                }
154
155                return self::dumpNull($flags);
156            case \is_array($value):
157                return self::dumpArray($value, $flags);
158            case null === $value:
159                return self::dumpNull($flags);
160            case true === $value:
161                return 'true';
162            case false === $value:
163                return 'false';
164            case \is_int($value):
165                return $value;
166            case is_numeric($value) && false === strpbrk($value, "\f\n\r\t\v"):
167                $locale = setlocale(\LC_NUMERIC, 0);
168                if (false !== $locale) {
169                    setlocale(\LC_NUMERIC, 'C');
170                }
171                if (\is_float($value)) {
172                    $repr = (string) $value;
173                    if (is_infinite($value)) {
174                        $repr = str_ireplace('INF', '.Inf', $repr);
175                    } elseif (floor($value) == $value && $repr == $value) {
176                        // Preserve float data type since storing a whole number will result in integer value.
177                        $repr = '!!float '.$repr;
178                    }
179                } else {
180                    $repr = \is_string($value) ? "'$value'" : (string) $value;
181                }
182                if (false !== $locale) {
183                    setlocale(\LC_NUMERIC, $locale);
184                }
185
186                return $repr;
187            case '' == $value:
188                return "''";
189            case self::isBinaryString($value):
190                return '!!binary '.base64_encode($value);
191            case Escaper::requiresDoubleQuoting($value):
192                return Escaper::escapeWithDoubleQuotes($value);
193            case Escaper::requiresSingleQuoting($value):
194            case Parser::preg_match('{^[0-9]+[_0-9]*$}', $value):
195            case Parser::preg_match(self::getHexRegex(), $value):
196            case Parser::preg_match(self::getTimestampRegex(), $value):
197                return Escaper::escapeWithSingleQuotes($value);
198            default:
199                return $value;
200        }
201    }
202
203    /**
204     * Check if given array is hash or just normal indexed array.
205     *
206     * @param array|\ArrayObject|\stdClass $value The PHP array or array-like object to check
207     *
208     * @return bool true if value is hash array, false otherwise
209     */
210    public static function isHash($value): bool
211    {
212        if ($value instanceof \stdClass || $value instanceof \ArrayObject) {
213            return true;
214        }
215
216        $expectedKey = 0;
217
218        foreach ($value as $key => $val) {
219            if ($key !== $expectedKey++) {
220                return true;
221            }
222        }
223
224        return false;
225    }
226
227    /**
228     * Dumps a PHP array to a YAML string.
229     *
230     * @param array $value The PHP array to dump
231     * @param int   $flags A bit field of Yaml::DUMP_* constants to customize the dumped YAML string
232     *
233     * @return string The YAML string representing the PHP array
234     */
235    private static function dumpArray(array $value, int $flags): string
236    {
237        // array
238        if (($value || Yaml::DUMP_EMPTY_ARRAY_AS_SEQUENCE & $flags) && !self::isHash($value)) {
239            $output = [];
240            foreach ($value as $val) {
241                $output[] = self::dump($val, $flags);
242            }
243
244            return sprintf('[%s]', implode(', ', $output));
245        }
246
247        // hash
248        $output = [];
249        foreach ($value as $key => $val) {
250            $output[] = sprintf('%s: %s', self::dump($key, $flags), self::dump($val, $flags));
251        }
252
253        return sprintf('{ %s }', implode(', ', $output));
254    }
255
256    private static function dumpNull(int $flags): string
257    {
258        if (Yaml::DUMP_NULL_AS_TILDE & $flags) {
259            return '~';
260        }
261
262        return 'null';
263    }
264
265    /**
266     * Parses a YAML scalar.
267     *
268     * @return mixed
269     *
270     * @throws ParseException When malformed inline YAML string is parsed
271     */
272    public static function parseScalar(string $scalar, int $flags = 0, array $delimiters = null, int &$i = 0, bool $evaluate = true, array &$references = [], bool &$isQuoted = null)
273    {
274        if (\in_array($scalar[$i], ['"', "'"])) {
275            // quoted scalar
276            $isQuoted = true;
277            $output = self::parseQuotedScalar($scalar, $i);
278
279            if (null !== $delimiters) {
280                $tmp = ltrim(substr($scalar, $i), " \n");
281                if ('' === $tmp) {
282                    throw new ParseException(sprintf('Unexpected end of line, expected one of "%s".', implode('', $delimiters)), self::$parsedLineNumber + 1, $scalar, self::$parsedFilename);
283                }
284                if (!\in_array($tmp[0], $delimiters)) {
285                    throw new ParseException(sprintf('Unexpected characters (%s).', substr($scalar, $i)), self::$parsedLineNumber + 1, $scalar, self::$parsedFilename);
286                }
287            }
288        } else {
289            // "normal" string
290            $isQuoted = false;
291
292            if (!$delimiters) {
293                $output = substr($scalar, $i);
294                $i += \strlen($output);
295
296                // remove comments
297                if (Parser::preg_match('/[ \t]+#/', $output, $match, \PREG_OFFSET_CAPTURE)) {
298                    $output = substr($output, 0, $match[0][1]);
299                }
300            } elseif (Parser::preg_match('/^(.*?)('.implode('|', $delimiters).')/', substr($scalar, $i), $match)) {
301                $output = $match[1];
302                $i += \strlen($output);
303                $output = trim($output);
304            } else {
305                throw new ParseException(sprintf('Malformed inline YAML string: "%s".', $scalar), self::$parsedLineNumber + 1, null, self::$parsedFilename);
306            }
307
308            // a non-quoted string cannot start with @ or ` (reserved) nor with a scalar indicator (| or >)
309            if ($output && ('@' === $output[0] || '`' === $output[0] || '|' === $output[0] || '>' === $output[0] || '%' === $output[0])) {
310                throw new ParseException(sprintf('The reserved indicator "%s" cannot start a plain scalar; you need to quote the scalar.', $output[0]), self::$parsedLineNumber + 1, $output, self::$parsedFilename);
311            }
312
313            if ($evaluate) {
314                $output = self::evaluateScalar($output, $flags, $references, $isQuoted);
315            }
316        }
317
318        return $output;
319    }
320
321    /**
322     * Parses a YAML quoted scalar.
323     *
324     * @throws ParseException When malformed inline YAML string is parsed
325     */
326    private static function parseQuotedScalar(string $scalar, int &$i = 0): string
327    {
328        if (!Parser::preg_match('/'.self::REGEX_QUOTED_STRING.'/Au', substr($scalar, $i), $match)) {
329            throw new ParseException(sprintf('Malformed inline YAML string: "%s".', substr($scalar, $i)), self::$parsedLineNumber + 1, $scalar, self::$parsedFilename);
330        }
331
332        $output = substr($match[0], 1, \strlen($match[0]) - 2);
333
334        $unescaper = new Unescaper();
335        if ('"' == $scalar[$i]) {
336            $output = $unescaper->unescapeDoubleQuotedString($output);
337        } else {
338            $output = $unescaper->unescapeSingleQuotedString($output);
339        }
340
341        $i += \strlen($match[0]);
342
343        return $output;
344    }
345
346    /**
347     * Parses a YAML sequence.
348     *
349     * @throws ParseException When malformed inline YAML string is parsed
350     */
351    private static function parseSequence(string $sequence, int $flags, int &$i = 0, array &$references = []): array
352    {
353        $output = [];
354        $len = \strlen($sequence);
355        ++$i;
356
357        // [foo, bar, ...]
358        while ($i < $len) {
359            if (']' === $sequence[$i]) {
360                return $output;
361            }
362            if (',' === $sequence[$i] || ' ' === $sequence[$i]) {
363                ++$i;
364
365                continue;
366            }
367
368            $tag = self::parseTag($sequence, $i, $flags);
369            switch ($sequence[$i]) {
370                case '[':
371                    // nested sequence
372                    $value = self::parseSequence($sequence, $flags, $i, $references);
373                    break;
374                case '{':
375                    // nested mapping
376                    $value = self::parseMapping($sequence, $flags, $i, $references);
377                    break;
378                default:
379                    $value = self::parseScalar($sequence, $flags, [',', ']'], $i, null === $tag, $references, $isQuoted);
380
381                    // the value can be an array if a reference has been resolved to an array var
382                    if (\is_string($value) && !$isQuoted && false !== strpos($value, ': ')) {
383                        // embedded mapping?
384                        try {
385                            $pos = 0;
386                            $value = self::parseMapping('{'.$value.'}', $flags, $pos, $references);
387                        } catch (\InvalidArgumentException $e) {
388                            // no, it's not
389                        }
390                    }
391
392                    if (!$isQuoted && \is_string($value) && '' !== $value && '&' === $value[0] && Parser::preg_match(Parser::REFERENCE_PATTERN, $value, $matches)) {
393                        $references[$matches['ref']] = $matches['value'];
394                        $value = $matches['value'];
395                    }
396
397                    --$i;
398            }
399
400            if (null !== $tag && '' !== $tag) {
401                $value = new TaggedValue($tag, $value);
402            }
403
404            $output[] = $value;
405
406            ++$i;
407        }
408
409        throw new ParseException(sprintf('Malformed inline YAML string: "%s".', $sequence), self::$parsedLineNumber + 1, null, self::$parsedFilename);
410    }
411
412    /**
413     * Parses a YAML mapping.
414     *
415     * @return array|\stdClass
416     *
417     * @throws ParseException When malformed inline YAML string is parsed
418     */
419    private static function parseMapping(string $mapping, int $flags, int &$i = 0, array &$references = [])
420    {
421        $output = [];
422        $len = \strlen($mapping);
423        ++$i;
424        $allowOverwrite = false;
425
426        // {foo: bar, bar:foo, ...}
427        while ($i < $len) {
428            switch ($mapping[$i]) {
429                case ' ':
430                case ',':
431                case "\n":
432                    ++$i;
433                    continue 2;
434                case '}':
435                    if (self::$objectForMap) {
436                        return (object) $output;
437                    }
438
439                    return $output;
440            }
441
442            // key
443            $offsetBeforeKeyParsing = $i;
444            $isKeyQuoted = \in_array($mapping[$i], ['"', "'"], true);
445            $key = self::parseScalar($mapping, $flags, [':', ' '], $i, false);
446
447            if ($offsetBeforeKeyParsing === $i) {
448                throw new ParseException('Missing mapping key.', self::$parsedLineNumber + 1, $mapping);
449            }
450
451            if ('!php/const' === $key) {
452                $key .= ' '.self::parseScalar($mapping, $flags, [':'], $i, false);
453                $key = self::evaluateScalar($key, $flags);
454            }
455
456            if (false === $i = strpos($mapping, ':', $i)) {
457                break;
458            }
459
460            if (!$isKeyQuoted) {
461                $evaluatedKey = self::evaluateScalar($key, $flags, $references);
462
463                if ('' !== $key && $evaluatedKey !== $key && !\is_string($evaluatedKey) && !\is_int($evaluatedKey)) {
464                    throw new ParseException('Implicit casting of incompatible mapping keys to strings is not supported. Quote your evaluable mapping keys instead.', self::$parsedLineNumber + 1, $mapping);
465                }
466            }
467
468            if (!$isKeyQuoted && (!isset($mapping[$i + 1]) || !\in_array($mapping[$i + 1], [' ', ',', '[', ']', '{', '}', "\n"], true))) {
469                throw new ParseException('Colons must be followed by a space or an indication character (i.e. " ", ",", "[", "]", "{", "}").', self::$parsedLineNumber + 1, $mapping);
470            }
471
472            if ('<<' === $key) {
473                $allowOverwrite = true;
474            }
475
476            while ($i < $len) {
477                if (':' === $mapping[$i] || ' ' === $mapping[$i] || "\n" === $mapping[$i]) {
478                    ++$i;
479
480                    continue;
481                }
482
483                $tag = self::parseTag($mapping, $i, $flags);
484                switch ($mapping[$i]) {
485                    case '[':
486                        // nested sequence
487                        $value = self::parseSequence($mapping, $flags, $i, $references);
488                        // Spec: Keys MUST be unique; first one wins.
489                        // Parser cannot abort this mapping earlier, since lines
490                        // are processed sequentially.
491                        // But overwriting is allowed when a merge node is used in current block.
492                        if ('<<' === $key) {
493                            foreach ($value as $parsedValue) {
494                                $output += $parsedValue;
495                            }
496                        } elseif ($allowOverwrite || !isset($output[$key])) {
497                            if (null !== $tag) {
498                                $output[$key] = new TaggedValue($tag, $value);
499                            } else {
500                                $output[$key] = $value;
501                            }
502                        } elseif (isset($output[$key])) {
503                            throw new ParseException(sprintf('Duplicate key "%s" detected.', $key), self::$parsedLineNumber + 1, $mapping);
504                        }
505                        break;
506                    case '{':
507                        // nested mapping
508                        $value = self::parseMapping($mapping, $flags, $i, $references);
509                        // Spec: Keys MUST be unique; first one wins.
510                        // Parser cannot abort this mapping earlier, since lines
511                        // are processed sequentially.
512                        // But overwriting is allowed when a merge node is used in current block.
513                        if ('<<' === $key) {
514                            $output += $value;
515                        } elseif ($allowOverwrite || !isset($output[$key])) {
516                            if (null !== $tag) {
517                                $output[$key] = new TaggedValue($tag, $value);
518                            } else {
519                                $output[$key] = $value;
520                            }
521                        } elseif (isset($output[$key])) {
522                            throw new ParseException(sprintf('Duplicate key "%s" detected.', $key), self::$parsedLineNumber + 1, $mapping);
523                        }
524                        break;
525                    default:
526                        $value = self::parseScalar($mapping, $flags, [',', '}', "\n"], $i, null === $tag, $references, $isValueQuoted);
527                        // Spec: Keys MUST be unique; first one wins.
528                        // Parser cannot abort this mapping earlier, since lines
529                        // are processed sequentially.
530                        // But overwriting is allowed when a merge node is used in current block.
531                        if ('<<' === $key) {
532                            $output += $value;
533                        } elseif ($allowOverwrite || !isset($output[$key])) {
534                            if (!$isValueQuoted && \is_string($value) && '' !== $value && '&' === $value[0] && Parser::preg_match(Parser::REFERENCE_PATTERN, $value, $matches)) {
535                                $references[$matches['ref']] = $matches['value'];
536                                $value = $matches['value'];
537                            }
538
539                            if (null !== $tag) {
540                                $output[$key] = new TaggedValue($tag, $value);
541                            } else {
542                                $output[$key] = $value;
543                            }
544                        } elseif (isset($output[$key])) {
545                            throw new ParseException(sprintf('Duplicate key "%s" detected.', $key), self::$parsedLineNumber + 1, $mapping);
546                        }
547                        --$i;
548                }
549                ++$i;
550
551                continue 2;
552            }
553        }
554
555        throw new ParseException(sprintf('Malformed inline YAML string: "%s".', $mapping), self::$parsedLineNumber + 1, null, self::$parsedFilename);
556    }
557
558    /**
559     * Evaluates scalars and replaces magic values.
560     *
561     * @return mixed The evaluated YAML string
562     *
563     * @throws ParseException when object parsing support was disabled and the parser detected a PHP object or when a reference could not be resolved
564     */
565    private static function evaluateScalar(string $scalar, int $flags, array &$references = [], bool &$isQuotedString = null)
566    {
567        $isQuotedString = false;
568        $scalar = trim($scalar);
569        $scalarLower = strtolower($scalar);
570
571        if (0 === strpos($scalar, '*')) {
572            if (false !== $pos = strpos($scalar, '#')) {
573                $value = substr($scalar, 1, $pos - 2);
574            } else {
575                $value = substr($scalar, 1);
576            }
577
578            // an unquoted *
579            if (false === $value || '' === $value) {
580                throw new ParseException('A reference must contain at least one character.', self::$parsedLineNumber + 1, $value, self::$parsedFilename);
581            }
582
583            if (!\array_key_exists($value, $references)) {
584                throw new ParseException(sprintf('Reference "%s" does not exist.', $value), self::$parsedLineNumber + 1, $value, self::$parsedFilename);
585            }
586
587            return $references[$value];
588        }
589
590        switch (true) {
591            case 'null' === $scalarLower:
592            case '' === $scalar:
593            case '~' === $scalar:
594                return null;
595            case 'true' === $scalarLower:
596                return true;
597            case 'false' === $scalarLower:
598                return false;
599            case '!' === $scalar[0]:
600                switch (true) {
601                    case 0 === strpos($scalar, '!!str '):
602                        $s = (string) substr($scalar, 6);
603
604                        if (\in_array($s[0] ?? '', ['"', "'"], true)) {
605                            $isQuotedString = true;
606                            $s = self::parseQuotedScalar($s);
607                        }
608
609                        return $s;
610                    case 0 === strpos($scalar, '! '):
611                        return substr($scalar, 2);
612                    case 0 === strpos($scalar, '!php/object'):
613                        if (self::$objectSupport) {
614                            if (!isset($scalar[12])) {
615                                return false;
616                            }
617
618                            return unserialize(self::parseScalar(substr($scalar, 12)));
619                        }
620
621                        if (self::$exceptionOnInvalidType) {
622                            throw new ParseException('Object support when parsing a YAML file has been disabled.', self::$parsedLineNumber + 1, $scalar, self::$parsedFilename);
623                        }
624
625                        return null;
626                    case 0 === strpos($scalar, '!php/const'):
627                        if (self::$constantSupport) {
628                            if (!isset($scalar[11])) {
629                                return '';
630                            }
631
632                            $i = 0;
633                            if (\defined($const = self::parseScalar(substr($scalar, 11), 0, null, $i, false))) {
634                                return \constant($const);
635                            }
636
637                            throw new ParseException(sprintf('The constant "%s" is not defined.', $const), self::$parsedLineNumber + 1, $scalar, self::$parsedFilename);
638                        }
639                        if (self::$exceptionOnInvalidType) {
640                            throw new ParseException(sprintf('The string "%s" could not be parsed as a constant. Did you forget to pass the "Yaml::PARSE_CONSTANT" flag to the parser?', $scalar), self::$parsedLineNumber + 1, $scalar, self::$parsedFilename);
641                        }
642
643                        return null;
644                    case 0 === strpos($scalar, '!!float '):
645                        return (float) substr($scalar, 8);
646                    case 0 === strpos($scalar, '!!binary '):
647                        return self::evaluateBinaryScalar(substr($scalar, 9));
648                    default:
649                        throw new ParseException(sprintf('The string "%s" could not be parsed as it uses an unsupported built-in tag.', $scalar), self::$parsedLineNumber, $scalar, self::$parsedFilename);
650                }
651
652            // Optimize for returning strings.
653            // no break
654            case '+' === $scalar[0] || '-' === $scalar[0] || '.' === $scalar[0] || is_numeric($scalar[0]):
655                if (Parser::preg_match('{^[+-]?[0-9][0-9_]*$}', $scalar)) {
656                    $scalar = str_replace('_', '', $scalar);
657                }
658
659                switch (true) {
660                    case ctype_digit($scalar):
661                        if (preg_match('/^0[0-7]+$/', $scalar)) {
662                            return octdec($scalar);
663                        }
664
665                        $cast = (int) $scalar;
666
667                        return ($scalar === (string) $cast) ? $cast : $scalar;
668                    case '-' === $scalar[0] && ctype_digit(substr($scalar, 1)):
669                        if (preg_match('/^-0[0-7]+$/', $scalar)) {
670                            return -octdec(substr($scalar, 1));
671                        }
672
673                        $cast = (int) $scalar;
674
675                        return ($scalar === (string) $cast) ? $cast : $scalar;
676                    case is_numeric($scalar):
677                    case Parser::preg_match(self::getHexRegex(), $scalar):
678                        $scalar = str_replace('_', '', $scalar);
679
680                        return '0x' === $scalar[0].$scalar[1] ? hexdec($scalar) : (float) $scalar;
681                    case '.inf' === $scalarLower:
682                    case '.nan' === $scalarLower:
683                        return -log(0);
684                    case '-.inf' === $scalarLower:
685                        return log(0);
686                    case Parser::preg_match('/^(-|\+)?[0-9][0-9_]*(\.[0-9_]+)?$/', $scalar):
687                        return (float) str_replace('_', '', $scalar);
688                    case Parser::preg_match(self::getTimestampRegex(), $scalar):
689                        // When no timezone is provided in the parsed date, YAML spec says we must assume UTC.
690                        $time = new \DateTime($scalar, new \DateTimeZone('UTC'));
691
692                        if (Yaml::PARSE_DATETIME & $flags) {
693                            return $time;
694                        }
695
696                        try {
697                            if (false !== $scalar = $time->getTimestamp()) {
698                                return $scalar;
699                            }
700                        } catch (\ValueError $e) {
701                            // no-op
702                        }
703
704                        return $time->format('U');
705                }
706        }
707
708        return (string) $scalar;
709    }
710
711    private static function parseTag(string $value, int &$i, int $flags): ?string
712    {
713        if ('!' !== $value[$i]) {
714            return null;
715        }
716
717        $tagLength = strcspn($value, " \t\n[]{},", $i + 1);
718        $tag = substr($value, $i + 1, $tagLength);
719
720        $nextOffset = $i + $tagLength + 1;
721        $nextOffset += strspn($value, ' ', $nextOffset);
722
723        if ('' === $tag && (!isset($value[$nextOffset]) || \in_array($value[$nextOffset], [']', '}', ','], true))) {
724            throw new ParseException('Using the unquoted scalar value "!" is not supported. You must quote it.', self::$parsedLineNumber + 1, $value, self::$parsedFilename);
725        }
726
727        // Is followed by a scalar and is a built-in tag
728        if ('' !== $tag && (!isset($value[$nextOffset]) || !\in_array($value[$nextOffset], ['[', '{'], true)) && ('!' === $tag[0] || 'str' === $tag || 'php/const' === $tag || 'php/object' === $tag)) {
729            // Manage in {@link self::evaluateScalar()}
730            return null;
731        }
732
733        $i = $nextOffset;
734
735        // Built-in tags
736        if ('' !== $tag && '!' === $tag[0]) {
737            throw new ParseException(sprintf('The built-in tag "!%s" is not implemented.', $tag), self::$parsedLineNumber + 1, $value, self::$parsedFilename);
738        }
739
740        if ('' !== $tag && !isset($value[$i])) {
741            throw new ParseException(sprintf('Missing value for tag "%s".', $tag), self::$parsedLineNumber + 1, $value, self::$parsedFilename);
742        }
743
744        if ('' === $tag || Yaml::PARSE_CUSTOM_TAGS & $flags) {
745            return $tag;
746        }
747
748        throw new ParseException(sprintf('Tags support is not enabled. Enable the "Yaml::PARSE_CUSTOM_TAGS" flag to use "!%s".', $tag), self::$parsedLineNumber + 1, $value, self::$parsedFilename);
749    }
750
751    public static function evaluateBinaryScalar(string $scalar): string
752    {
753        $parsedBinaryData = self::parseScalar(preg_replace('/\s/', '', $scalar));
754
755        if (0 !== (\strlen($parsedBinaryData) % 4)) {
756            throw new ParseException(sprintf('The normalized base64 encoded data (data without whitespace characters) length must be a multiple of four (%d bytes given).', \strlen($parsedBinaryData)), self::$parsedLineNumber + 1, $scalar, self::$parsedFilename);
757        }
758
759        if (!Parser::preg_match('#^[A-Z0-9+/]+={0,2}$#i', $parsedBinaryData)) {
760            throw new ParseException(sprintf('The base64 encoded data (%s) contains invalid characters.', $parsedBinaryData), self::$parsedLineNumber + 1, $scalar, self::$parsedFilename);
761        }
762
763        return base64_decode($parsedBinaryData, true);
764    }
765
766    private static function isBinaryString(string $value)
767    {
768        return !preg_match('//u', $value) || preg_match('/[^\x00\x07-\x0d\x1B\x20-\xff]/', $value);
769    }
770
771    /**
772     * Gets a regex that matches a YAML date.
773     *
774     * @return string The regular expression
775     *
776     * @see http://www.yaml.org/spec/1.2/spec.html#id2761573
777     */
778    private static function getTimestampRegex(): string
779    {
780        return <<<EOF
781        ~^
782        (?P<year>[0-9][0-9][0-9][0-9])
783        -(?P<month>[0-9][0-9]?)
784        -(?P<day>[0-9][0-9]?)
785        (?:(?:[Tt]|[ \t]+)
786        (?P<hour>[0-9][0-9]?)
787        :(?P<minute>[0-9][0-9])
788        :(?P<second>[0-9][0-9])
789        (?:\.(?P<fraction>[0-9]*))?
790        (?:[ \t]*(?P<tz>Z|(?P<tz_sign>[-+])(?P<tz_hour>[0-9][0-9]?)
791        (?::(?P<tz_minute>[0-9][0-9]))?))?)?
792        $~x
793EOF;
794    }
795
796    /**
797     * Gets a regex that matches a YAML number in hexadecimal notation.
798     */
799    private static function getHexRegex(): string
800    {
801        return '~^0x[0-9a-f_]++$~i';
802    }
803}
804