vendor/symfony/yaml/Inline.php line 314

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