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