Debian Codegraph @

vendor/symfony/yaml/Inline.php

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