vendor/symfony/yaml/Inline.php line 58

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