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 $flags, int $parsedLineNumber = null, string $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 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 = null, int $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, $flags, null, $i, null === $tag, $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, $value, self::$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 $value, int $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_NUMERIC, 0);
  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 (false === strpos($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.             case Parser::preg_match('{^[0-9]+[_0-9]*$}', $value):
  157.             case Parser::preg_match(self::getHexRegex(), $value):
  158.             case Parser::preg_match(self::getTimestampRegex(), $value):
  159.                 return Escaper::escapeWithSingleQuotes($value);
  160.             default:
  161.                 return $value;
  162.         }
  163.     }
  164.     /**
  165.      * Check if given array is hash or just normal indexed array.
  166.      */
  167.     public static function isHash(array|\ArrayObject|\stdClass $value): bool
  168.     {
  169.         if ($value instanceof \stdClass || $value instanceof \ArrayObject) {
  170.             return true;
  171.         }
  172.         $expectedKey = 0;
  173.         foreach ($value as $key => $val) {
  174.             if ($key !== $expectedKey++) {
  175.                 return true;
  176.             }
  177.         }
  178.         return false;
  179.     }
  180.     /**
  181.      * Dumps a PHP array to a YAML string.
  182.      *
  183.      * @param array $value The PHP array to dump
  184.      * @param int   $flags A bit field of Yaml::DUMP_* constants to customize the dumped YAML string
  185.      */
  186.     private static function dumpArray(array $value, int $flags): string
  187.     {
  188.         // array
  189.         if (($value || Yaml::DUMP_EMPTY_ARRAY_AS_SEQUENCE & $flags) && !self::isHash($value)) {
  190.             $output = [];
  191.             foreach ($value as $val) {
  192.                 $output[] = self::dump($val, $flags);
  193.             }
  194.             return sprintf('[%s]', implode(', ', $output));
  195.         }
  196.         // hash
  197.         $output = [];
  198.         foreach ($value as $key => $val) {
  199.             $output[] = sprintf('%s: %s', self::dump($key, $flags), self::dump($val, $flags));
  200.         }
  201.         return sprintf('{ %s }', implode(', ', $output));
  202.     }
  203.     private static function dumpNull(int $flags): string
  204.     {
  205.         if (Yaml::DUMP_NULL_AS_TILDE & $flags) {
  206.             return '~';
  207.         }
  208.         return 'null';
  209.     }
  210.     /**
  211.      * Parses a YAML scalar.
  212.      *
  213.      * @throws ParseException When malformed inline YAML string is parsed
  214.      */
  215.     public static function parseScalar(string $scalar, int $flags = 0, array $delimiters = null, int &$i = 0, bool $evaluate = true, array &$references = [], bool &$isQuoted = null): mixed
  216.     {
  217.         if (\in_array($scalar[$i], ['"', "'"], true)) {
  218.             // quoted scalar
  219.             $isQuoted = true;
  220.             $output = self::parseQuotedScalar($scalar, $i);
  221.             if (null !== $delimiters) {
  222.                 $tmp = ltrim(substr($scalar, $i), " \n");
  223.                 if ('' === $tmp) {
  224.                     throw new ParseException(sprintf('Unexpected end of line, expected one of "%s".', implode('', $delimiters)), self::$parsedLineNumber + 1, $scalar, self::$parsedFilename);
  225.                 }
  226.                 if (!\in_array($tmp[0], $delimiters)) {
  227.                     throw new ParseException(sprintf('Unexpected characters (%s).', substr($scalar, $i)), self::$parsedLineNumber + 1, $scalar, self::$parsedFilename);
  228.                 }
  229.             }
  230.         } else {
  231.             // "normal" string
  232.             $isQuoted = false;
  233.             if (!$delimiters) {
  234.                 $output = substr($scalar, $i);
  235.                 $i += \strlen($output);
  236.                 // remove comments
  237.                 if (Parser::preg_match('/[ \t]+#/', $output, $match, \PREG_OFFSET_CAPTURE)) {
  238.                     $output = substr($output, 0, $match[0][1]);
  239.                 }
  240.             } elseif (Parser::preg_match('/^(.*?)('.implode('|', $delimiters).')/', substr($scalar, $i), $match)) {
  241.                 $output = $match[1];
  242.                 $i += \strlen($output);
  243.                 $output = trim($output);
  244.             } else {
  245.                 throw new ParseException(sprintf('Malformed inline YAML string: "%s".', $scalar), self::$parsedLineNumber + 1, null, self::$parsedFilename);
  246.             }
  247.             // a non-quoted string cannot start with @ or ` (reserved) nor with a scalar indicator (| or >)
  248.             if ($output && ('@' === $output[0] || '`' === $output[0] || '|' === $output[0] || '>' === $output[0] || '%' === $output[0])) {
  249.                 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);
  250.             }
  251.             if ($evaluate) {
  252.                 $output = self::evaluateScalar($output, $flags, $references, $isQuoted);
  253.             }
  254.         }
  255.         return $output;
  256.     }
  257.     /**
  258.      * Parses a YAML quoted scalar.
  259.      *
  260.      * @throws ParseException When malformed inline YAML string is parsed
  261.      */
  262.     private static function parseQuotedScalar(string $scalar, int &$i = 0): string
  263.     {
  264.         if (!Parser::preg_match('/'.self::REGEX_QUOTED_STRING.'/Au', substr($scalar, $i), $match)) {
  265.             throw new ParseException(sprintf('Malformed inline YAML string: "%s".', substr($scalar, $i)), self::$parsedLineNumber + 1, $scalar, self::$parsedFilename);
  266.         }
  267.         $output = substr($match[0], 1, -1);
  268.         $unescaper = new Unescaper();
  269.         if ('"' == $scalar[$i]) {
  270.             $output = $unescaper->unescapeDoubleQuotedString($output);
  271.         } else {
  272.             $output = $unescaper->unescapeSingleQuotedString($output);
  273.         }
  274.         $i += \strlen($match[0]);
  275.         return $output;
  276.     }
  277.     /**
  278.      * Parses a YAML sequence.
  279.      *
  280.      * @throws ParseException When malformed inline YAML string is parsed
  281.      */
  282.     private static function parseSequence(string $sequence, int $flags, int &$i = 0, array &$references = []): array
  283.     {
  284.         $output = [];
  285.         $len = \strlen($sequence);
  286.         ++$i;
  287.         // [foo, bar, ...]
  288.         while ($i < $len) {
  289.             if (']' === $sequence[$i]) {
  290.                 return $output;
  291.             }
  292.             if (',' === $sequence[$i] || ' ' === $sequence[$i]) {
  293.                 ++$i;
  294.                 continue;
  295.             }
  296.             $tag = self::parseTag($sequence, $i, $flags);
  297.             switch ($sequence[$i]) {
  298.                 case '[':
  299.                     // nested sequence
  300.                     $value = self::parseSequence($sequence, $flags, $i, $references);
  301.                     break;
  302.                 case '{':
  303.                     // nested mapping
  304.                     $value = self::parseMapping($sequence, $flags, $i, $references);
  305.                     break;
  306.                 default:
  307.                     $value = self::parseScalar($sequence, $flags, [',', ']'], $i, null === $tag, $references, $isQuoted);
  308.                     // the value can be an array if a reference has been resolved to an array var
  309.                     if (\is_string($value) && !$isQuoted && false !== strpos($value, ': ')) {
  310.                         // embedded mapping?
  311.                         try {
  312.                             $pos = 0;
  313.                             $value = self::parseMapping('{'.$value.'}', $flags, $pos, $references);
  314.                         } catch (\InvalidArgumentException $e) {
  315.                             // no, it's not
  316.                         }
  317.                     }
  318.                     if (!$isQuoted && \is_string($value) && '' !== $value && '&' === $value[0] && Parser::preg_match(Parser::REFERENCE_PATTERN, $value, $matches)) {
  319.                         $references[$matches['ref']] = $matches['value'];
  320.                         $value = $matches['value'];
  321.                     }
  322.                     --$i;
  323.             }
  324.             if (null !== $tag && '' !== $tag) {
  325.                 $value = new TaggedValue($tag, $value);
  326.             }
  327.             $output[] = $value;
  328.             ++$i;
  329.         }
  330.         throw new ParseException(sprintf('Malformed inline YAML string: "%s".', $sequence), self::$parsedLineNumber + 1, null, self::$parsedFilename);
  331.     }
  332.     /**
  333.      * Parses a YAML mapping.
  334.      *
  335.      * @throws ParseException When malformed inline YAML string is parsed
  336.      */
  337.     private static function parseMapping(string $mapping, int $flags, int &$i = 0, array &$references = []): array|\stdClass
  338.     {
  339.         $output = [];
  340.         $len = \strlen($mapping);
  341.         ++$i;
  342.         $allowOverwrite = false;
  343.         // {foo: bar, bar:foo, ...}
  344.         while ($i < $len) {
  345.             switch ($mapping[$i]) {
  346.                 case ' ':
  347.                 case ',':
  348.                 case "\n":
  349.                     ++$i;
  350.                     continue 2;
  351.                 case '}':
  352.                     if (self::$objectForMap) {
  353.                         return (object) $output;
  354.                     }
  355.                     return $output;
  356.             }
  357.             // key
  358.             $offsetBeforeKeyParsing = $i;
  359.             $isKeyQuoted = \in_array($mapping[$i], ['"', "'"], true);
  360.             $key = self::parseScalar($mapping, $flags, [':', ' '], $i, false);
  361.             if ($offsetBeforeKeyParsing === $i) {
  362.                 throw new ParseException('Missing mapping key.', self::$parsedLineNumber + 1, $mapping);
  363.             }
  364.             if ('!php/const' === $key) {
  365.                 $key .= ' '.self::parseScalar($mapping, $flags, [':'], $i, false);
  366.                 $key = self::evaluateScalar($key, $flags);
  367.             }
  368.             if (false === $i = strpos($mapping, ':', $i)) {
  369.                 break;
  370.             }
  371.             if (!$isKeyQuoted) {
  372.                 $evaluatedKey = self::evaluateScalar($key, $flags, $references);
  373.                 if ('' !== $key && $evaluatedKey !== $key && !\is_string($evaluatedKey) && !\is_int($evaluatedKey)) {
  374.                     throw new ParseException('Implicit casting of incompatible mapping keys to strings is not supported. Quote your evaluable mapping keys instead.', self::$parsedLineNumber + 1, $mapping);
  375.                 }
  376.             }
  377.             if (!$isKeyQuoted && (!isset($mapping[$i + 1]) || !\in_array($mapping[$i + 1], [' ', ',', '[', ']', '{', '}', "\n"], true))) {
  378.                 throw new ParseException('Colons must be followed by a space or an indication character (i.e. " ", ",", "[", "]", "{", "}").', self::$parsedLineNumber + 1, $mapping);
  379.             }
  380.             if ('<<' === $key) {
  381.                 $allowOverwrite = true;
  382.             }
  383.             while ($i < $len) {
  384.                 if (':' === $mapping[$i] || ' ' === $mapping[$i] || "\n" === $mapping[$i]) {
  385.                     ++$i;
  386.                     continue;
  387.                 }
  388.                 $tag = self::parseTag($mapping, $i, $flags);
  389.                 switch ($mapping[$i]) {
  390.                     case '[':
  391.                         // nested sequence
  392.                         $value = self::parseSequence($mapping, $flags, $i, $references);
  393.                         // Spec: Keys MUST be unique; first one wins.
  394.                         // Parser cannot abort this mapping earlier, since lines
  395.                         // are processed sequentially.
  396.                         // But overwriting is allowed when a merge node is used in current block.
  397.                         if ('<<' === $key) {
  398.                             foreach ($value as $parsedValue) {
  399.                                 $output += $parsedValue;
  400.                             }
  401.                         } elseif ($allowOverwrite || !isset($output[$key])) {
  402.                             if (null !== $tag) {
  403.                                 $output[$key] = new TaggedValue($tag, $value);
  404.                             } else {
  405.                                 $output[$key] = $value;
  406.                             }
  407.                         } elseif (isset($output[$key])) {
  408.                             throw new ParseException(sprintf('Duplicate key "%s" detected.', $key), self::$parsedLineNumber + 1, $mapping);
  409.                         }
  410.                         break;
  411.                     case '{':
  412.                         // nested mapping
  413.                         $value = self::parseMapping($mapping, $flags, $i, $references);
  414.                         // Spec: Keys MUST be unique; first one wins.
  415.                         // Parser cannot abort this mapping earlier, since lines
  416.                         // are processed sequentially.
  417.                         // But overwriting is allowed when a merge node is used in current block.
  418.                         if ('<<' === $key) {
  419.                             $output += $value;
  420.                         } elseif ($allowOverwrite || !isset($output[$key])) {
  421.                             if (null !== $tag) {
  422.                                 $output[$key] = new TaggedValue($tag, $value);
  423.                             } else {
  424.                                 $output[$key] = $value;
  425.                             }
  426.                         } elseif (isset($output[$key])) {
  427.                             throw new ParseException(sprintf('Duplicate key "%s" detected.', $key), self::$parsedLineNumber + 1, $mapping);
  428.                         }
  429.                         break;
  430.                     default:
  431.                         $value = self::parseScalar($mapping, $flags, [',', '}', "\n"], $i, null === $tag, $references, $isValueQuoted);
  432.                         // Spec: Keys MUST be unique; first one wins.
  433.                         // Parser cannot abort this mapping earlier, since lines
  434.                         // are processed sequentially.
  435.                         // But overwriting is allowed when a merge node is used in current block.
  436.                         if ('<<' === $key) {
  437.                             $output += $value;
  438.                         } elseif ($allowOverwrite || !isset($output[$key])) {
  439.                             if (!$isValueQuoted && \is_string($value) && '' !== $value && '&' === $value[0] && Parser::preg_match(Parser::REFERENCE_PATTERN, $value, $matches)) {
  440.                                 $references[$matches['ref']] = $matches['value'];
  441.                                 $value = $matches['value'];
  442.                             }
  443.                             if (null !== $tag) {
  444.                                 $output[$key] = new TaggedValue($tag, $value);
  445.                             } else {
  446.                                 $output[$key] = $value;
  447.                             }
  448.                         } elseif (isset($output[$key])) {
  449.                             throw new ParseException(sprintf('Duplicate key "%s" detected.', $key), self::$parsedLineNumber + 1, $mapping);
  450.                         }
  451.                         --$i;
  452.                 }
  453.                 ++$i;
  454.                 continue 2;
  455.             }
  456.         }
  457.         throw new ParseException(sprintf('Malformed inline YAML string: "%s".', $mapping), self::$parsedLineNumber + 1, null, self::$parsedFilename);
  458.     }
  459.     /**
  460.      * Evaluates scalars and replaces magic values.
  461.      *
  462.      * @throws ParseException when object parsing support was disabled and the parser detected a PHP object or when a reference could not be resolved
  463.      */
  464.     private static function evaluateScalar(string $scalar, int $flags, array &$references = [], bool &$isQuotedString = null): mixed
  465.     {
  466.         $isQuotedString = false;
  467.         $scalar = trim($scalar);
  468.         if (0 === strpos($scalar, '*')) {
  469.             if (false !== $pos = strpos($scalar, '#')) {
  470.                 $value = substr($scalar, 1, $pos - 2);
  471.             } else {
  472.                 $value = substr($scalar, 1);
  473.             }
  474.             // an unquoted *
  475.             if (false === $value || '' === $value) {
  476.                 throw new ParseException('A reference must contain at least one character.', self::$parsedLineNumber + 1, $value, self::$parsedFilename);
  477.             }
  478.             if (!\array_key_exists($value, $references)) {
  479.                 throw new ParseException(sprintf('Reference "%s" does not exist.', $value), self::$parsedLineNumber + 1, $value, self::$parsedFilename);
  480.             }
  481.             return $references[$value];
  482.         }
  483.         $scalarLower = strtolower($scalar);
  484.         switch (true) {
  485.             case 'null' === $scalarLower:
  486.             case '' === $scalar:
  487.             case '~' === $scalar:
  488.                 return null;
  489.             case 'true' === $scalarLower:
  490.                 return true;
  491.             case 'false' === $scalarLower:
  492.                 return false;
  493.             case '!' === $scalar[0]:
  494.                 switch (true) {
  495.                     case 0 === strpos($scalar, '!!str '):
  496.                         $s = (string) substr($scalar, 6);
  497.                         if (\in_array($s[0] ?? '', ['"', "'"], true)) {
  498.                             $isQuotedString = true;
  499.                             $s = self::parseQuotedScalar($s);
  500.                         }
  501.                         return $s;
  502.                     case 0 === strpos($scalar, '! '):
  503.                         return substr($scalar, 2);
  504.                     case 0 === strpos($scalar, '!php/object'):
  505.                         if (self::$objectSupport) {
  506.                             if (!isset($scalar[12])) {
  507.                                 throw new ParseException('Missing value for tag "!php/object".', self::$parsedLineNumber + 1, $scalar, self::$parsedFilename);
  508.                             }
  509.                             return unserialize(self::parseScalar(substr($scalar, 12)));
  510.                         }
  511.                         if (self::$exceptionOnInvalidType) {
  512.                             throw new ParseException('Object support when parsing a YAML file has been disabled.', self::$parsedLineNumber + 1, $scalar, self::$parsedFilename);
  513.                         }
  514.                         return null;
  515.                     case 0 === strpos($scalar, '!php/const'):
  516.                         if (self::$constantSupport) {
  517.                             if (!isset($scalar[11])) {
  518.                                 throw new ParseException('Missing value for tag "!php/const".', self::$parsedLineNumber + 1, $scalar, self::$parsedFilename);
  519.                             }
  520.                             $i = 0;
  521.                             if (\defined($const = self::parseScalar(substr($scalar, 11), 0, null, $i, false))) {
  522.                                 return \constant($const);
  523.                             }
  524.                             throw new ParseException(sprintf('The constant "%s" is not defined.', $const), self::$parsedLineNumber + 1, $scalar, self::$parsedFilename);
  525.                         }
  526.                         if (self::$exceptionOnInvalidType) {
  527.                             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);
  528.                         }
  529.                         return null;
  530.                     case 0 === strpos($scalar, '!!float '):
  531.                         return (float) substr($scalar, 8);
  532.                     case 0 === strpos($scalar, '!!binary '):
  533.                         return self::evaluateBinaryScalar(substr($scalar, 9));
  534.                     default:
  535.                         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);
  536.                 }
  537.                 // no break
  538.             case preg_match('/^(?:\+|-)?0o(?P<value>[0-7_]++)$/', $scalar, $matches):
  539.                 $value = str_replace('_', '', $matches['value']);
  540.                 if ('-' === $scalar[0]) {
  541.                     return -octdec($value);
  542.                 } else {
  543.                     return octdec($value);
  544.                 }
  545.             // Optimize for returning strings.
  546.             // no break
  547.             case \in_array($scalar[0], ['+', '-', '.'], true) || is_numeric($scalar[0]):
  548.                 if (Parser::preg_match('{^[+-]?[0-9][0-9_]*$}', $scalar)) {
  549.                     $scalar = str_replace('_', '', $scalar);
  550.                 }
  551.                 switch (true) {
  552.                     case ctype_digit($scalar):
  553.                     case '-' === $scalar[0] && ctype_digit(substr($scalar, 1)):
  554.                         $cast = (int) $scalar;
  555.                         return ($scalar === (string) $cast) ? $cast : $scalar;
  556.                     case is_numeric($scalar):
  557.                     case Parser::preg_match(self::getHexRegex(), $scalar):
  558.                         $scalar = str_replace('_', '', $scalar);
  559.                         return '0x' === $scalar[0].$scalar[1] ? hexdec($scalar) : (float) $scalar;
  560.                     case '.inf' === $scalarLower:
  561.                     case '.nan' === $scalarLower:
  562.                         return -log(0);
  563.                     case '-.inf' === $scalarLower:
  564.                         return log(0);
  565.                     case Parser::preg_match('/^(-|\+)?[0-9][0-9_]*(\.[0-9_]+)?$/', $scalar):
  566.                         return (float) str_replace('_', '', $scalar);
  567.                     case Parser::preg_match(self::getTimestampRegex(), $scalar):
  568.                         // When no timezone is provided in the parsed date, YAML spec says we must assume UTC.
  569.                         $time = new \DateTime($scalar, new \DateTimeZone('UTC'));
  570.                         if (Yaml::PARSE_DATETIME & $flags) {
  571.                             return $time;
  572.                         }
  573.                         try {
  574.                             if (false !== $scalar = $time->getTimestamp()) {
  575.                                 return $scalar;
  576.                             }
  577.                         } catch (\ValueError $e) {
  578.                             // no-op
  579.                         }
  580.                         return $time->format('U');
  581.                 }
  582.         }
  583.         return (string) $scalar;
  584.     }
  585.     private static function parseTag(string $value, int &$i, int $flags): ?string
  586.     {
  587.         if ('!' !== $value[$i]) {
  588.             return null;
  589.         }
  590.         $tagLength = strcspn($value, " \t\n[]{},", $i + 1);
  591.         $tag = substr($value, $i + 1, $tagLength);
  592.         $nextOffset = $i + $tagLength + 1;
  593.         $nextOffset += strspn($value, ' ', $nextOffset);
  594.         if ('' === $tag && (!isset($value[$nextOffset]) || \in_array($value[$nextOffset], [']', '}', ','], true))) {
  595.             throw new ParseException('Using the unquoted scalar value "!" is not supported. You must quote it.', self::$parsedLineNumber + 1, $value, self::$parsedFilename);
  596.         }
  597.         // Is followed by a scalar and is a built-in tag
  598.         if ('' !== $tag && (!isset($value[$nextOffset]) || !\in_array($value[$nextOffset], ['[', '{'], true)) && ('!' === $tag[0] || 'str' === $tag || 'php/const' === $tag || 'php/object' === $tag)) {
  599.             // Manage in {@link self::evaluateScalar()}
  600.             return null;
  601.         }
  602.         $i = $nextOffset;
  603.         // Built-in tags
  604.         if ('' !== $tag && '!' === $tag[0]) {
  605.             throw new ParseException(sprintf('The built-in tag "!%s" is not implemented.', $tag), self::$parsedLineNumber + 1, $value, self::$parsedFilename);
  606.         }
  607.         if ('' !== $tag && !isset($value[$i])) {
  608.             throw new ParseException(sprintf('Missing value for tag "%s".', $tag), self::$parsedLineNumber + 1, $value, self::$parsedFilename);
  609.         }
  610.         if ('' === $tag || Yaml::PARSE_CUSTOM_TAGS & $flags) {
  611.             return $tag;
  612.         }
  613.         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);
  614.     }
  615.     public static function evaluateBinaryScalar(string $scalar): string
  616.     {
  617.         $parsedBinaryData = self::parseScalar(preg_replace('/\s/', '', $scalar));
  618.         if (0 !== (\strlen($parsedBinaryData) % 4)) {
  619.             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);
  620.         }
  621.         if (!Parser::preg_match('#^[A-Z0-9+/]+={0,2}$#i', $parsedBinaryData)) {
  622.             throw new ParseException(sprintf('The base64 encoded data (%s) contains invalid characters.', $parsedBinaryData), self::$parsedLineNumber + 1, $scalar, self::$parsedFilename);
  623.         }
  624.         return base64_decode($parsedBinaryData, true);
  625.     }
  626.     private static function isBinaryString(string $value): bool
  627.     {
  628.         return !preg_match('//u', $value) || preg_match('/[^\x00\x07-\x0d\x1B\x20-\xff]/', $value);
  629.     }
  630.     /**
  631.      * Gets a regex that matches a YAML date.
  632.      *
  633.      * @see http://www.yaml.org/spec/1.2/spec.html#id2761573
  634.      */
  635.     private static function getTimestampRegex(): string
  636.     {
  637.         return <<<EOF
  638.         ~^
  639.         (?P<year>[0-9][0-9][0-9][0-9])
  640.         -(?P<month>[0-9][0-9]?)
  641.         -(?P<day>[0-9][0-9]?)
  642.         (?:(?:[Tt]|[ \t]+)
  643.         (?P<hour>[0-9][0-9]?)
  644.         :(?P<minute>[0-9][0-9])
  645.         :(?P<second>[0-9][0-9])
  646.         (?:\.(?P<fraction>[0-9]*))?
  647.         (?:[ \t]*(?P<tz>Z|(?P<tz_sign>[-+])(?P<tz_hour>[0-9][0-9]?)
  648.         (?::(?P<tz_minute>[0-9][0-9]))?))?)?
  649.         $~x
  650. EOF;
  651.     }
  652.     /**
  653.      * Gets a regex that matches a YAML number in hexadecimal notation.
  654.      */
  655.     private static function getHexRegex(): string
  656.     {
  657.         return '~^0x[0-9a-f_]++$~i';
  658.     }
  659. }