Subversion-Projekte lars-tiefland.laravel_shop

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

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