vendor/symfony/error-handler/DebugClassLoader.php line 338

  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\ErrorHandler;
  11. use Composer\InstalledVersions;
  12. use Doctrine\Common\Persistence\Proxy as LegacyProxy;
  13. use Doctrine\Persistence\Proxy;
  14. use Mockery\MockInterface;
  15. use Phake\IMock;
  16. use PHPUnit\Framework\MockObject\Matcher\StatelessInvocation;
  17. use PHPUnit\Framework\MockObject\MockObject;
  18. use Prophecy\Prophecy\ProphecySubjectInterface;
  19. use ProxyManager\Proxy\ProxyInterface;
  20. use Symfony\Component\ErrorHandler\Internal\TentativeTypes;
  21. use Symfony\Component\HttpClient\HttplugClient;
  22. use Symfony\Component\VarExporter\LazyObjectInterface;
  23. /**
  24.  * Autoloader checking if the class is really defined in the file found.
  25.  *
  26.  * The ClassLoader will wrap all registered autoloaders
  27.  * and will throw an exception if a file is found but does
  28.  * not declare the class.
  29.  *
  30.  * It can also patch classes to turn docblocks into actual return types.
  31.  * This behavior is controlled by the SYMFONY_PATCH_TYPE_DECLARATIONS env var,
  32.  * which is a url-encoded array with the follow parameters:
  33.  *  - "force": any value enables deprecation notices - can be any of:
  34.  *      - "phpdoc" to patch only docblock annotations
  35.  *      - "2" to add all possible return types
  36.  *      - "1" to add return types but only to tests/final/internal/private methods
  37.  *  - "php": the target version of PHP - e.g. "7.1" doesn't generate "object" types
  38.  *  - "deprecations": "1" to trigger a deprecation notice when a child class misses a
  39.  *                    return type while the parent declares an "@return" annotation
  40.  *
  41.  * Note that patching doesn't care about any coding style so you'd better to run
  42.  * php-cs-fixer after, with rules "phpdoc_trim_consecutive_blank_line_separation"
  43.  * and "no_superfluous_phpdoc_tags" enabled typically.
  44.  *
  45.  * @author Fabien Potencier <fabien@symfony.com>
  46.  * @author Christophe Coevoet <stof@notk.org>
  47.  * @author Nicolas Grekas <p@tchwork.com>
  48.  * @author Guilhem Niot <guilhem.niot@gmail.com>
  49.  */
  50. class DebugClassLoader
  51. {
  52.     private const SPECIAL_RETURN_TYPES = [
  53.         'void' => 'void',
  54.         'null' => 'null',
  55.         'resource' => 'resource',
  56.         'boolean' => 'bool',
  57.         'true' => 'true',
  58.         'false' => 'false',
  59.         'integer' => 'int',
  60.         'array' => 'array',
  61.         'bool' => 'bool',
  62.         'callable' => 'callable',
  63.         'float' => 'float',
  64.         'int' => 'int',
  65.         'iterable' => 'iterable',
  66.         'object' => 'object',
  67.         'string' => 'string',
  68.         'self' => 'self',
  69.         'parent' => 'parent',
  70.         'mixed' => 'mixed',
  71.         'static' => 'static',
  72.         '$this' => 'static',
  73.         'list' => 'array',
  74.         'class-string' => 'string',
  75.         'never' => 'never',
  76.     ];
  77.     private const BUILTIN_RETURN_TYPES = [
  78.         'void' => true,
  79.         'array' => true,
  80.         'false' => true,
  81.         'bool' => true,
  82.         'callable' => true,
  83.         'float' => true,
  84.         'int' => true,
  85.         'iterable' => true,
  86.         'object' => true,
  87.         'string' => true,
  88.         'self' => true,
  89.         'parent' => true,
  90.         'mixed' => true,
  91.         'static' => true,
  92.         'null' => true,
  93.         'true' => true,
  94.         'never' => true,
  95.     ];
  96.     private const MAGIC_METHODS = [
  97.         '__isset' => 'bool',
  98.         '__sleep' => 'array',
  99.         '__toString' => 'string',
  100.         '__debugInfo' => 'array',
  101.         '__serialize' => 'array',
  102.     ];
  103.     /**
  104.      * @var callable
  105.      */
  106.     private $classLoader;
  107.     private bool $isFinder;
  108.     private array $loaded = [];
  109.     private array $patchTypes = [];
  110.     private static int $caseCheck;
  111.     private static array $checkedClasses = [];
  112.     private static array $final = [];
  113.     private static array $finalMethods = [];
  114.     private static array $finalProperties = [];
  115.     private static array $finalConstants = [];
  116.     private static array $deprecated = [];
  117.     private static array $internal = [];
  118.     private static array $internalMethods = [];
  119.     private static array $annotatedParameters = [];
  120.     private static array $darwinCache = ['/' => ['/', []]];
  121.     private static array $method = [];
  122.     private static array $returnTypes = [];
  123.     private static array $methodTraits = [];
  124.     private static array $fileOffsets = [];
  125.     public function __construct(callable $classLoader)
  126.     {
  127.         $this->classLoader = $classLoader;
  128.         $this->isFinder = \is_array($classLoader) && method_exists($classLoader[0], 'findFile');
  129.         parse_str(getenv('SYMFONY_PATCH_TYPE_DECLARATIONS') ?: '', $this->patchTypes);
  130.         $this->patchTypes += [
  131.             'force' => null,
  132.             'php' => \PHP_MAJOR_VERSION.'.'.\PHP_MINOR_VERSION,
  133.             'deprecations' => true,
  134.         ];
  135.         if ('phpdoc' === $this->patchTypes['force']) {
  136.             $this->patchTypes['force'] = 'docblock';
  137.         }
  138.         if (!isset(self::$caseCheck)) {
  139.             $file = is_file(__FILE__) ? __FILE__ : rtrim(realpath('.'), \DIRECTORY_SEPARATOR);
  140.             $i = strrpos($file, \DIRECTORY_SEPARATOR);
  141.             $dir = substr($file, 0, 1 + $i);
  142.             $file = substr($file, 1 + $i);
  143.             $test = strtoupper($file) === $file ? strtolower($file) : strtoupper($file);
  144.             $test = realpath($dir.$test);
  145.             if (false === $test || false === $i) {
  146.                 // filesystem is case sensitive
  147.                 self::$caseCheck = 0;
  148.             } elseif (str_ends_with($test, $file)) {
  149.                 // filesystem is case insensitive and realpath() normalizes the case of characters
  150.                 self::$caseCheck = 1;
  151.             } elseif ('Darwin' === \PHP_OS_FAMILY) {
  152.                 // on MacOSX, HFS+ is case insensitive but realpath() doesn't normalize the case of characters
  153.                 self::$caseCheck = 2;
  154.             } else {
  155.                 // filesystem case checks failed, fallback to disabling them
  156.                 self::$caseCheck = 0;
  157.             }
  158.         }
  159.     }
  160.     public function getClassLoader(): callable
  161.     {
  162.         return $this->classLoader;
  163.     }
  164.     /**
  165.      * Wraps all autoloaders.
  166.      */
  167.     public static function enable(): void
  168.     {
  169.         // Ensures we don't hit https://bugs.php.net/42098
  170.         class_exists(\Symfony\Component\ErrorHandler\ErrorHandler::class);
  171.         class_exists(\Psr\Log\LogLevel::class);
  172.         if (!\is_array($functions = spl_autoload_functions())) {
  173.             return;
  174.         }
  175.         foreach ($functions as $function) {
  176.             spl_autoload_unregister($function);
  177.         }
  178.         foreach ($functions as $function) {
  179.             if (!\is_array($function) || !$function[0] instanceof self) {
  180.                 $function = [new static($function), 'loadClass'];
  181.             }
  182.             spl_autoload_register($function);
  183.         }
  184.     }
  185.     /**
  186.      * Disables the wrapping.
  187.      */
  188.     public static function disable(): void
  189.     {
  190.         if (!\is_array($functions = spl_autoload_functions())) {
  191.             return;
  192.         }
  193.         foreach ($functions as $function) {
  194.             spl_autoload_unregister($function);
  195.         }
  196.         foreach ($functions as $function) {
  197.             if (\is_array($function) && $function[0] instanceof self) {
  198.                 $function = $function[0]->getClassLoader();
  199.             }
  200.             spl_autoload_register($function);
  201.         }
  202.     }
  203.     public static function checkClasses(): bool
  204.     {
  205.         if (!\is_array($functions = spl_autoload_functions())) {
  206.             return false;
  207.         }
  208.         $loader = null;
  209.         foreach ($functions as $function) {
  210.             if (\is_array($function) && $function[0] instanceof self) {
  211.                 $loader = $function[0];
  212.                 break;
  213.             }
  214.         }
  215.         if (null === $loader) {
  216.             return false;
  217.         }
  218.         static $offsets = [
  219.             'get_declared_interfaces' => 0,
  220.             'get_declared_traits' => 0,
  221.             'get_declared_classes' => 0,
  222.         ];
  223.         foreach ($offsets as $getSymbols => $i) {
  224.             $symbols = $getSymbols();
  225.             for (; $i < \count($symbols); ++$i) {
  226.                 if (!is_subclass_of($symbols[$i], MockObject::class)
  227.                     && !is_subclass_of($symbols[$i], ProphecySubjectInterface::class)
  228.                     && !is_subclass_of($symbols[$i], Proxy::class)
  229.                     && !is_subclass_of($symbols[$i], ProxyInterface::class)
  230.                     && !is_subclass_of($symbols[$i], LazyObjectInterface::class)
  231.                     && !is_subclass_of($symbols[$i], LegacyProxy::class)
  232.                     && !is_subclass_of($symbols[$i], MockInterface::class)
  233.                     && !is_subclass_of($symbols[$i], IMock::class)
  234.                 ) {
  235.                     $loader->checkClass($symbols[$i]);
  236.                 }
  237.             }
  238.             $offsets[$getSymbols] = $i;
  239.         }
  240.         return true;
  241.     }
  242.     public function findFile(string $class): ?string
  243.     {
  244.         return $this->isFinder ? ($this->classLoader[0]->findFile($class) ?: null) : null;
  245.     }
  246.     /**
  247.      * Loads the given class or interface.
  248.      *
  249.      * @throws \RuntimeException
  250.      */
  251.     public function loadClass(string $class): void
  252.     {
  253.         $e = error_reporting(error_reporting() | \E_PARSE | \E_ERROR | \E_CORE_ERROR | \E_COMPILE_ERROR);
  254.         try {
  255.             if ($this->isFinder && !isset($this->loaded[$class])) {
  256.                 $this->loaded[$class] = true;
  257.                 if (!$file = $this->classLoader[0]->findFile($class) ?: '') {
  258.                     // no-op
  259.                 } elseif (\function_exists('opcache_is_script_cached') && @opcache_is_script_cached($file)) {
  260.                     include $file;
  261.                     return;
  262.                 } elseif (false === include $file) {
  263.                     return;
  264.                 }
  265.             } else {
  266.                 ($this->classLoader)($class);
  267.                 $file = '';
  268.             }
  269.         } finally {
  270.             error_reporting($e);
  271.         }
  272.         $this->checkClass($class, $file);
  273.     }
  274.     private function checkClass(string $class, string $file = null): void
  275.     {
  276.         $exists = null === $file || class_exists($class, false) || interface_exists($class, false) || trait_exists($class, false);
  277.         if (null !== $file && $class && '\\' === $class[0]) {
  278.             $class = substr($class, 1);
  279.         }
  280.         if ($exists) {
  281.             if (isset(self::$checkedClasses[$class])) {
  282.                 return;
  283.             }
  284.             self::$checkedClasses[$class] = true;
  285.             $refl = new \ReflectionClass($class);
  286.             if (null === $file && $refl->isInternal()) {
  287.                 return;
  288.             }
  289.             $name = $refl->getName();
  290.             if ($name !== $class && 0 === strcasecmp($name, $class)) {
  291.                 throw new \RuntimeException(sprintf('Case mismatch between loaded and declared class names: "%s" vs "%s".', $class, $name));
  292.             }
  293.             $deprecations = $this->checkAnnotations($refl, $name);
  294.             foreach ($deprecations as $message) {
  295.                 @trigger_error($message, \E_USER_DEPRECATED);
  296.             }
  297.         }
  298.         if (!$file) {
  299.             return;
  300.         }
  301.         if (!$exists) {
  302.             if (str_contains($class, '/')) {
  303.                 throw new \RuntimeException(sprintf('Trying to autoload a class with an invalid name "%s". Be careful that the namespace separator is "\" in PHP, not "/".', $class));
  304.             }
  305.             throw new \RuntimeException(sprintf('The autoloader expected class "%s" to be defined in file "%s". The file was found but the class was not in it, the class name or namespace probably has a typo.', $class, $file));
  306.         }
  307.         if (self::$caseCheck && $message = $this->checkCase($refl, $file, $class)) {
  308.             throw new \RuntimeException(sprintf('Case mismatch between class and real file names: "%s" vs "%s" in "%s".', $message[0], $message[1], $message[2]));
  309.         }
  310.     }
  311.     public function checkAnnotations(\ReflectionClass $refl, string $class): array
  312.     {
  313.         if (
  314.             'Symfony\Bridge\PhpUnit\Legacy\SymfonyTestsListenerForV7' === $class
  315.             || 'Symfony\Bridge\PhpUnit\Legacy\SymfonyTestsListenerForV6' === $class
  316.         ) {
  317.             return [];
  318.         }
  319.         $deprecations = [];
  320.         $className = str_contains($class, "@anonymous\0") ? (get_parent_class($class) ?: key(class_implements($class)) ?: 'class').'@anonymous' : $class;
  321.         // Don't trigger deprecations for classes in the same vendor
  322.         if ($class !== $className) {
  323.             $vendor = preg_match('/^namespace ([^;\\\\\s]++)[;\\\\]/m', @file_get_contents($refl->getFileName()), $vendor) ? $vendor[1].'\\' : '';
  324.             $vendorLen = \strlen($vendor);
  325.         } elseif (2 > $vendorLen = 1 + (strpos($class, '\\') ?: strpos($class, '_'))) {
  326.             $vendorLen = 0;
  327.             $vendor = '';
  328.         } else {
  329.             $vendor = str_replace('_', '\\', substr($class, 0, $vendorLen));
  330.         }
  331.         $parent = get_parent_class($class) ?: null;
  332.         self::$returnTypes[$class] = [];
  333.         $classIsTemplate = false;
  334.         // Detect annotations on the class
  335.         if ($doc = $this->parsePhpDoc($refl)) {
  336.             $classIsTemplate = isset($doc['template']);
  337.             foreach (['final', 'deprecated', 'internal'] as $annotation) {
  338.                 if (null !== $description = $doc[$annotation][0] ?? null) {
  339.                     self::${$annotation}[$class] = '' !== $description ? ' '.$description.(preg_match('/[.!]$/', $description) ? '' : '.') : '.';
  340.                 }
  341.             }
  342.             if ($refl->isInterface() && isset($doc['method'])) {
  343.                 foreach ($doc['method'] as $name => [$static, $returnType, $signature, $description]) {
  344.                     self::$method[$class][] = [$class, $static, $returnType, $name.$signature, $description];
  345.                     if ('' !== $returnType) {
  346.                         $this->setReturnType($returnType, $refl->name, $name, $refl->getFileName(), $parent);
  347.                     }
  348.                 }
  349.             }
  350.         }
  351.         $parentAndOwnInterfaces = $this->getOwnInterfaces($class, $parent);
  352.         if ($parent) {
  353.             $parentAndOwnInterfaces[$parent] = $parent;
  354.             if (!isset(self::$checkedClasses[$parent])) {
  355.                 $this->checkClass($parent);
  356.             }
  357.             if (isset(self::$final[$parent])) {
  358.                 $deprecations[] = sprintf('The "%s" class is considered final%s It may change without further notice as of its next major version. You should not extend it from "%s".', $parent, self::$final[$parent], $className);
  359.             }
  360.         }
  361.         // Detect if the parent is annotated
  362.         foreach ($parentAndOwnInterfaces + class_uses($class, false) as $use) {
  363.             if (!isset(self::$checkedClasses[$use])) {
  364.                 $this->checkClass($use);
  365.             }
  366.             if (isset(self::$deprecated[$use]) && strncmp($vendor, str_replace('_', '\\', $use), $vendorLen) && !isset(self::$deprecated[$class])
  367.                 && !(HttplugClient::class === $class && \in_array($use, [\Http\Client\HttpClient::class, \Http\Message\RequestFactory::class, \Http\Message\StreamFactory::class, \Http\Message\UriFactory::class], true))
  368.             ) {
  369.                 $type = class_exists($class, false) ? 'class' : (interface_exists($class, false) ? 'interface' : 'trait');
  370.                 $verb = class_exists($use, false) || interface_exists($class, false) ? 'extends' : (interface_exists($use, false) ? 'implements' : 'uses');
  371.                 $deprecations[] = sprintf('The "%s" %s %s "%s" that is deprecated%s', $className, $type, $verb, $use, self::$deprecated[$use]);
  372.             }
  373.             if (isset(self::$internal[$use]) && strncmp($vendor, str_replace('_', '\\', $use), $vendorLen)) {
  374.                 $deprecations[] = sprintf('The "%s" %s is considered internal%s It may change without further notice. You should not use it from "%s".', $use, class_exists($use, false) ? 'class' : (interface_exists($use, false) ? 'interface' : 'trait'), self::$internal[$use], $className);
  375.             }
  376.             if (isset(self::$method[$use])) {
  377.                 if ($refl->isAbstract()) {
  378.                     if (isset(self::$method[$class])) {
  379.                         self::$method[$class] = array_merge(self::$method[$class], self::$method[$use]);
  380.                     } else {
  381.                         self::$method[$class] = self::$method[$use];
  382.                     }
  383.                 } elseif (!$refl->isInterface()) {
  384.                     if (!strncmp($vendor, str_replace('_', '\\', $use), $vendorLen)
  385.                         && str_starts_with($className, 'Symfony\\')
  386.                         && (!class_exists(InstalledVersions::class)
  387.                             || 'symfony/symfony' !== InstalledVersions::getRootPackage()['name'])
  388.                     ) {
  389.                         // skip "same vendor" @method deprecations for Symfony\* classes unless symfony/symfony is being tested
  390.                         continue;
  391.                     }
  392.                     $hasCall = $refl->hasMethod('__call');
  393.                     $hasStaticCall = $refl->hasMethod('__callStatic');
  394.                     foreach (self::$method[$use] as [$interface, $static, $returnType, $name, $description]) {
  395.                         if ($static ? $hasStaticCall : $hasCall) {
  396.                             continue;
  397.                         }
  398.                         $realName = substr($name, 0, strpos($name, '('));
  399.                         if (!$refl->hasMethod($realName) || !($methodRefl = $refl->getMethod($realName))->isPublic() || ($static && !$methodRefl->isStatic()) || (!$static && $methodRefl->isStatic())) {
  400.                             $deprecations[] = sprintf('Class "%s" should implement method "%s::%s%s"%s', $className, ($static ? 'static ' : '').$interface, $name, $returnType ? ': '.$returnType : '', null === $description ? '.' : ': '.$description);
  401.                         }
  402.                     }
  403.                 }
  404.             }
  405.         }
  406.         if (trait_exists($class)) {
  407.             $file = $refl->getFileName();
  408.             foreach ($refl->getMethods() as $method) {
  409.                 if ($method->getFileName() === $file) {
  410.                     self::$methodTraits[$file][$method->getStartLine()] = $class;
  411.                 }
  412.             }
  413.             return $deprecations;
  414.         }
  415.         // Inherit @final, @internal, @param and @return annotations for methods
  416.         self::$finalMethods[$class] = [];
  417.         self::$internalMethods[$class] = [];
  418.         self::$annotatedParameters[$class] = [];
  419.         self::$finalProperties[$class] = [];
  420.         self::$finalConstants[$class] = [];
  421.         foreach ($parentAndOwnInterfaces as $use) {
  422.             foreach (['finalMethods', 'internalMethods', 'annotatedParameters', 'returnTypes', 'finalProperties', 'finalConstants'] as $property) {
  423.                 if (isset(self::${$property}[$use])) {
  424.                     self::${$property}[$class] = self::${$property}[$class] ? self::${$property}[$use] + self::${$property}[$class] : self::${$property}[$use];
  425.                 }
  426.             }
  427.             if (null !== (TentativeTypes::RETURN_TYPES[$use] ?? null)) {
  428.                 foreach (TentativeTypes::RETURN_TYPES[$use] as $method => $returnType) {
  429.                     $returnType = explode('|', $returnType);
  430.                     foreach ($returnType as $i => $t) {
  431.                         if ('?' !== $t && !isset(self::BUILTIN_RETURN_TYPES[$t])) {
  432.                             $returnType[$i] = '\\'.$t;
  433.                         }
  434.                     }
  435.                     $returnType = implode('|', $returnType);
  436.                     self::$returnTypes[$class] += [$method => [$returnType, str_starts_with($returnType, '?') ? substr($returnType, 1).'|null' : $returnType, $use, '']];
  437.                 }
  438.             }
  439.         }
  440.         foreach ($refl->getMethods() as $method) {
  441.             if ($method->class !== $class) {
  442.                 continue;
  443.             }
  444.             if (null === $ns = self::$methodTraits[$method->getFileName()][$method->getStartLine()] ?? null) {
  445.                 $ns = $vendor;
  446.                 $len = $vendorLen;
  447.             } elseif (2 > $len = 1 + (strpos($ns, '\\') ?: strpos($ns, '_'))) {
  448.                 $len = 0;
  449.                 $ns = '';
  450.             } else {
  451.                 $ns = str_replace('_', '\\', substr($ns, 0, $len));
  452.             }
  453.             if ($parent && isset(self::$finalMethods[$parent][$method->name])) {
  454.                 [$declaringClass, $message] = self::$finalMethods[$parent][$method->name];
  455.                 $deprecations[] = sprintf('The "%s::%s()" method is considered final%s It may change without further notice as of its next major version. You should not extend it from "%s".', $declaringClass, $method->name, $message, $className);
  456.             }
  457.             if (isset(self::$internalMethods[$class][$method->name])) {
  458.                 [$declaringClass, $message] = self::$internalMethods[$class][$method->name];
  459.                 if (strncmp($ns, $declaringClass, $len)) {
  460.                     $deprecations[] = sprintf('The "%s::%s()" method is considered internal%s It may change without further notice. You should not extend it from "%s".', $declaringClass, $method->name, $message, $className);
  461.                 }
  462.             }
  463.             // To read method annotations
  464.             $doc = $this->parsePhpDoc($method);
  465.             if (($classIsTemplate || isset($doc['template'])) && $method->hasReturnType()) {
  466.                 unset($doc['return']);
  467.             }
  468.             if (isset(self::$annotatedParameters[$class][$method->name])) {
  469.                 $definedParameters = [];
  470.                 foreach ($method->getParameters() as $parameter) {
  471.                     $definedParameters[$parameter->name] = true;
  472.                 }
  473.                 foreach (self::$annotatedParameters[$class][$method->name] as $parameterName => $deprecation) {
  474.                     if (!isset($definedParameters[$parameterName]) && !isset($doc['param'][$parameterName])) {
  475.                         $deprecations[] = sprintf($deprecation, $className);
  476.                     }
  477.                 }
  478.             }
  479.             $forcePatchTypes = $this->patchTypes['force'];
  480.             if ($canAddReturnType = null !== $forcePatchTypes && !str_contains($method->getFileName(), \DIRECTORY_SEPARATOR.'vendor'.\DIRECTORY_SEPARATOR)) {
  481.                 if ('void' !== (self::MAGIC_METHODS[$method->name] ?? 'void')) {
  482.                     $this->patchTypes['force'] = $forcePatchTypes ?: 'docblock';
  483.                 }
  484.                 $canAddReturnType = 2 === (int) $forcePatchTypes
  485.                     || false !== stripos($method->getFileName(), \DIRECTORY_SEPARATOR.'Tests'.\DIRECTORY_SEPARATOR)
  486.                     || $refl->isFinal()
  487.                     || $method->isFinal()
  488.                     || $method->isPrivate()
  489.                     || ('.' === (self::$internal[$class] ?? null) && !$refl->isAbstract())
  490.                     || '.' === (self::$final[$class] ?? null)
  491.                     || '' === ($doc['final'][0] ?? null)
  492.                     || '' === ($doc['internal'][0] ?? null)
  493.                 ;
  494.             }
  495.             if (null !== ($returnType = self::$returnTypes[$class][$method->name] ?? null) && 'docblock' === $this->patchTypes['force'] && !$method->hasReturnType() && isset(TentativeTypes::RETURN_TYPES[$returnType[2]][$method->name])) {
  496.                 $this->patchReturnTypeWillChange($method);
  497.             }
  498.             if (null !== ($returnType ??= self::MAGIC_METHODS[$method->name] ?? null) && !$method->hasReturnType() && !isset($doc['return'])) {
  499.                 [$normalizedType, $returnType, $declaringClass, $declaringFile] = \is_string($returnType) ? [$returnType, $returnType, '', ''] : $returnType;
  500.                 if ($canAddReturnType && 'docblock' !== $this->patchTypes['force']) {
  501.                     $this->patchMethod($method, $returnType, $declaringFile, $normalizedType);
  502.                 }
  503.                 if (!isset($doc['deprecated']) && strncmp($ns, $declaringClass, $len)) {
  504.                     if ('docblock' === $this->patchTypes['force']) {
  505.                         $this->patchMethod($method, $returnType, $declaringFile, $normalizedType);
  506.                     } elseif ('' !== $declaringClass && $this->patchTypes['deprecations']) {
  507.                         $deprecations[] = sprintf('Method "%s::%s()" might add "%s" as a native return type declaration in the future. Do the same in %s "%s" now to avoid errors or add an explicit @return annotation to suppress this message.', $declaringClass, $method->name, $normalizedType, interface_exists($declaringClass) ? 'implementation' : 'child class', $className);
  508.                     }
  509.                 }
  510.             }
  511.             if (!$doc) {
  512.                 $this->patchTypes['force'] = $forcePatchTypes;
  513.                 continue;
  514.             }
  515.             if (isset($doc['return']) || 'void' !== (self::MAGIC_METHODS[$method->name] ?? 'void')) {
  516.                 $this->setReturnType($doc['return'] ?? self::MAGIC_METHODS[$method->name], $method->class, $method->name, $method->getFileName(), $parent, $method->getReturnType());
  517.                 if (isset(self::$returnTypes[$class][$method->name][0]) && $canAddReturnType) {
  518.                     $this->fixReturnStatements($method, self::$returnTypes[$class][$method->name][0]);
  519.                 }
  520.                 if ($method->isPrivate()) {
  521.                     unset(self::$returnTypes[$class][$method->name]);
  522.                 }
  523.             }
  524.             $this->patchTypes['force'] = $forcePatchTypes;
  525.             if ($method->isPrivate()) {
  526.                 continue;
  527.             }
  528.             $finalOrInternal = false;
  529.             foreach (['final', 'internal'] as $annotation) {
  530.                 if (null !== $description = $doc[$annotation][0] ?? null) {
  531.                     self::${$annotation.'Methods'}[$class][$method->name] = [$class, '' !== $description ? ' '.$description.(preg_match('/[[:punct:]]$/', $description) ? '' : '.') : '.'];
  532.                     $finalOrInternal = true;
  533.                 }
  534.             }
  535.             if ($finalOrInternal || $method->isConstructor() || !isset($doc['param']) || StatelessInvocation::class === $class) {
  536.                 continue;
  537.             }
  538.             if (!isset(self::$annotatedParameters[$class][$method->name])) {
  539.                 $definedParameters = [];
  540.                 foreach ($method->getParameters() as $parameter) {
  541.                     $definedParameters[$parameter->name] = true;
  542.                 }
  543.             }
  544.             foreach ($doc['param'] as $parameterName => $parameterType) {
  545.                 if (!isset($definedParameters[$parameterName])) {
  546.                     self::$annotatedParameters[$class][$method->name][$parameterName] = sprintf('The "%%s::%s()" method will require a new "%s$%s" argument in the next major version of its %s "%s", not defining it is deprecated.', $method->name, $parameterType ? $parameterType.' ' : '', $parameterName, interface_exists($className) ? 'interface' : 'parent class', $className);
  547.                 }
  548.             }
  549.         }
  550.         $finals = isset(self::$final[$class]) || $refl->isFinal() ? [] : [
  551.             'finalConstants' => $refl->getReflectionConstants(\ReflectionClassConstant::IS_PUBLIC | \ReflectionClassConstant::IS_PROTECTED),
  552.             'finalProperties' => $refl->getProperties(\ReflectionProperty::IS_PUBLIC | \ReflectionProperty::IS_PROTECTED),
  553.         ];
  554.         foreach ($finals as $type => $reflectors) {
  555.             foreach ($reflectors as $r) {
  556.                 if ($r->class !== $class) {
  557.                     continue;
  558.                 }
  559.                 $doc = $this->parsePhpDoc($r);
  560.                 foreach ($parentAndOwnInterfaces as $use) {
  561.                     if (isset(self::${$type}[$use][$r->name]) && !isset($doc['deprecated']) && ('finalConstants' === $type || substr($use, 0, strrpos($use, '\\')) !== substr($use, 0, strrpos($class, '\\')))) {
  562.                         $msg = 'finalConstants' === $type ? '%s" constant' : '$%s" property';
  563.                         $deprecations[] = sprintf('The "%s::'.$msg.' is considered final. You should not override it in "%s".', self::${$type}[$use][$r->name], $r->name, $class);
  564.                     }
  565.                 }
  566.                 if (isset($doc['final']) || ('finalProperties' === $type && str_starts_with($class, 'Symfony\\') && !$r->hasType())) {
  567.                     self::${$type}[$class][$r->name] = $class;
  568.                 }
  569.             }
  570.         }
  571.         return $deprecations;
  572.     }
  573.     public function checkCase(\ReflectionClass $refl, string $file, string $class): ?array
  574.     {
  575.         $real = explode('\\', $class.strrchr($file, '.'));
  576.         $tail = explode(\DIRECTORY_SEPARATOR, str_replace('/', \DIRECTORY_SEPARATOR, $file));
  577.         $i = \count($tail) - 1;
  578.         $j = \count($real) - 1;
  579.         while (isset($tail[$i], $real[$j]) && $tail[$i] === $real[$j]) {
  580.             --$i;
  581.             --$j;
  582.         }
  583.         array_splice($tail, 0, $i + 1);
  584.         if (!$tail) {
  585.             return null;
  586.         }
  587.         $tail = \DIRECTORY_SEPARATOR.implode(\DIRECTORY_SEPARATOR, $tail);
  588.         $tailLen = \strlen($tail);
  589.         $real = $refl->getFileName();
  590.         if (2 === self::$caseCheck) {
  591.             $real = $this->darwinRealpath($real);
  592.         }
  593.         if (0 === substr_compare($real, $tail, -$tailLen, $tailLen, true)
  594.             && 0 !== substr_compare($real, $tail, -$tailLen, $tailLen, false)
  595.         ) {
  596.             return [substr($tail, -$tailLen + 1), substr($real, -$tailLen + 1), substr($real, 0, -$tailLen + 1)];
  597.         }
  598.         return null;
  599.     }
  600.     /**
  601.      * `realpath` on MacOSX doesn't normalize the case of characters.
  602.      */
  603.     private function darwinRealpath(string $real): string
  604.     {
  605.         $i = 1 + strrpos($real, '/');
  606.         $file = substr($real, $i);
  607.         $real = substr($real, 0, $i);
  608.         if (isset(self::$darwinCache[$real])) {
  609.             $kDir = $real;
  610.         } else {
  611.             $kDir = strtolower($real);
  612.             if (isset(self::$darwinCache[$kDir])) {
  613.                 $real = self::$darwinCache[$kDir][0];
  614.             } else {
  615.                 $dir = getcwd();
  616.                 if (!@chdir($real)) {
  617.                     return $real.$file;
  618.                 }
  619.                 $real = getcwd().'/';
  620.                 chdir($dir);
  621.                 $dir = $real;
  622.                 $k = $kDir;
  623.                 $i = \strlen($dir) - 1;
  624.                 while (!isset(self::$darwinCache[$k])) {
  625.                     self::$darwinCache[$k] = [$dir, []];
  626.                     self::$darwinCache[$dir] = &self::$darwinCache[$k];
  627.                     while ('/' !== $dir[--$i]) {
  628.                     }
  629.                     $k = substr($k, 0, ++$i);
  630.                     $dir = substr($dir, 0, $i--);
  631.                 }
  632.             }
  633.         }
  634.         $dirFiles = self::$darwinCache[$kDir][1];
  635.         if (!isset($dirFiles[$file]) && str_ends_with($file, ') : eval()\'d code')) {
  636.             // Get the file name from "file_name.php(123) : eval()'d code"
  637.             $file = substr($file, 0, strrpos($file, '(', -17));
  638.         }
  639.         if (isset($dirFiles[$file])) {
  640.             return $real.$dirFiles[$file];
  641.         }
  642.         $kFile = strtolower($file);
  643.         if (!isset($dirFiles[$kFile])) {
  644.             foreach (scandir($real, 2) as $f) {
  645.                 if ('.' !== $f[0]) {
  646.                     $dirFiles[$f] = $f;
  647.                     if ($f === $file) {
  648.                         $kFile = $k = $file;
  649.                     } elseif ($f !== $k = strtolower($f)) {
  650.                         $dirFiles[$k] = $f;
  651.                     }
  652.                 }
  653.             }
  654.             self::$darwinCache[$kDir][1] = $dirFiles;
  655.         }
  656.         return $real.$dirFiles[$kFile];
  657.     }
  658.     /**
  659.      * `class_implements` includes interfaces from the parents so we have to manually exclude them.
  660.      *
  661.      * @return string[]
  662.      */
  663.     private function getOwnInterfaces(string $class, ?string $parent): array
  664.     {
  665.         $ownInterfaces = class_implements($class, false);
  666.         if ($parent) {
  667.             foreach (class_implements($parent, false) as $interface) {
  668.                 unset($ownInterfaces[$interface]);
  669.             }
  670.         }
  671.         foreach ($ownInterfaces as $interface) {
  672.             foreach (class_implements($interface) as $interface) {
  673.                 unset($ownInterfaces[$interface]);
  674.             }
  675.         }
  676.         return $ownInterfaces;
  677.     }
  678.     private function setReturnType(string $types, string $class, string $method, string $filename, ?string $parent, \ReflectionType $returnType = null): void
  679.     {
  680.         if ('__construct' === $method) {
  681.             return;
  682.         }
  683.         if ('null' === $types) {
  684.             self::$returnTypes[$class][$method] = ['null', 'null', $class, $filename];
  685.             return;
  686.         }
  687.         if ($nullable = str_starts_with($types, 'null|')) {
  688.             $types = substr($types, 5);
  689.         } elseif ($nullable = str_ends_with($types, '|null')) {
  690.             $types = substr($types, 0, -5);
  691.         }
  692.         $arrayType = ['array' => 'array'];
  693.         $typesMap = [];
  694.         $glue = str_contains($types, '&') ? '&' : '|';
  695.         foreach (explode($glue, $types) as $t) {
  696.             $t = self::SPECIAL_RETURN_TYPES[strtolower($t)] ?? $t;
  697.             $typesMap[$this->normalizeType($t, $class, $parent, $returnType)][$t] = $t;
  698.         }
  699.         if (isset($typesMap['array'])) {
  700.             if (isset($typesMap['Traversable']) || isset($typesMap['\Traversable'])) {
  701.                 $typesMap['iterable'] = $arrayType !== $typesMap['array'] ? $typesMap['array'] : ['iterable'];
  702.                 unset($typesMap['array'], $typesMap['Traversable'], $typesMap['\Traversable']);
  703.             } elseif ($arrayType !== $typesMap['array'] && isset(self::$returnTypes[$class][$method]) && !$returnType) {
  704.                 return;
  705.             }
  706.         }
  707.         if (isset($typesMap['array']) && isset($typesMap['iterable'])) {
  708.             if ($arrayType !== $typesMap['array']) {
  709.                 $typesMap['iterable'] = $typesMap['array'];
  710.             }
  711.             unset($typesMap['array']);
  712.         }
  713.         $iterable = $object = true;
  714.         foreach ($typesMap as $n => $t) {
  715.             if ('null' !== $n) {
  716.                 $iterable = $iterable && (\in_array($n, ['array', 'iterable']) || str_contains($n, 'Iterator'));
  717.                 $object = $object && (\in_array($n, ['callable', 'object', '$this', 'static']) || !isset(self::SPECIAL_RETURN_TYPES[$n]));
  718.             }
  719.         }
  720.         $phpTypes = [];
  721.         $docTypes = [];
  722.         foreach ($typesMap as $n => $t) {
  723.             if ('null' === $n) {
  724.                 $nullable = true;
  725.                 continue;
  726.             }
  727.             $docTypes[] = $t;
  728.             if ('mixed' === $n || 'void' === $n) {
  729.                 $nullable = false;
  730.                 $phpTypes = ['' => $n];
  731.                 continue;
  732.             }
  733.             if ('resource' === $n) {
  734.                 // there is no native type for "resource"
  735.                 return;
  736.             }
  737.             if (!preg_match('/^(?:\\\\?[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*)+$/', $n)) {
  738.                 // exclude any invalid PHP class name (e.g. `Cookie::SAMESITE_*`)
  739.                 continue;
  740.             }
  741.             if (!isset($phpTypes[''])) {
  742.                 $phpTypes[] = $n;
  743.             }
  744.         }
  745.         $docTypes = array_merge([], ...$docTypes);
  746.         if (!$phpTypes) {
  747.             return;
  748.         }
  749.         if (1 < \count($phpTypes)) {
  750.             if ($iterable && '8.0' > $this->patchTypes['php']) {
  751.                 $phpTypes = $docTypes = ['iterable'];
  752.             } elseif ($object && 'object' === $this->patchTypes['force']) {
  753.                 $phpTypes = $docTypes = ['object'];
  754.             } elseif ('8.0' > $this->patchTypes['php']) {
  755.                 // ignore multi-types return declarations
  756.                 return;
  757.             }
  758.         }
  759.         $phpType = sprintf($nullable ? (1 < \count($phpTypes) ? '%s|null' : '?%s') : '%s', implode($glue, $phpTypes));
  760.         $docType = sprintf($nullable ? '%s|null' : '%s', implode($glue, $docTypes));
  761.         self::$returnTypes[$class][$method] = [$phpType, $docType, $class, $filename];
  762.     }
  763.     private function normalizeType(string $type, string $class, ?string $parent, ?\ReflectionType $returnType): string
  764.     {
  765.         if (isset(self::SPECIAL_RETURN_TYPES[$lcType = strtolower($type)])) {
  766.             if ('parent' === $lcType = self::SPECIAL_RETURN_TYPES[$lcType]) {
  767.                 $lcType = null !== $parent ? '\\'.$parent : 'parent';
  768.             } elseif ('self' === $lcType) {
  769.                 $lcType = '\\'.$class;
  770.             }
  771.             return $lcType;
  772.         }
  773.         // We could resolve "use" statements to return the FQDN
  774.         // but this would be too expensive for a runtime checker
  775.         if (!str_ends_with($type, '[]')) {
  776.             return $type;
  777.         }
  778.         if ($returnType instanceof \ReflectionNamedType) {
  779.             $type = $returnType->getName();
  780.             if ('mixed' !== $type) {
  781.                 return isset(self::SPECIAL_RETURN_TYPES[$type]) ? $type : '\\'.$type;
  782.             }
  783.         }
  784.         return 'array';
  785.     }
  786.     /**
  787.      * Utility method to add #[ReturnTypeWillChange] where php triggers deprecations.
  788.      */
  789.     private function patchReturnTypeWillChange(\ReflectionMethod $method)
  790.     {
  791.         if (\count($method->getAttributes(\ReturnTypeWillChange::class))) {
  792.             return;
  793.         }
  794.         if (!is_file($file = $method->getFileName())) {
  795.             return;
  796.         }
  797.         $fileOffset = self::$fileOffsets[$file] ?? 0;
  798.         $code = file($file);
  799.         $startLine = $method->getStartLine() + $fileOffset - 2;
  800.         if (false !== stripos($code[$startLine], 'ReturnTypeWillChange')) {
  801.             return;
  802.         }
  803.         $code[$startLine] .= "    #[\\ReturnTypeWillChange]\n";
  804.         self::$fileOffsets[$file] = 1 + $fileOffset;
  805.         file_put_contents($file, $code);
  806.     }
  807.     /**
  808.      * Utility method to add @return annotations to the Symfony code-base where it triggers self-deprecations.
  809.      */
  810.     private function patchMethod(\ReflectionMethod $method, string $returnType, string $declaringFile, string $normalizedType)
  811.     {
  812.         static $patchedMethods = [];
  813.         static $useStatements = [];
  814.         if (!is_file($file = $method->getFileName()) || isset($patchedMethods[$file][$startLine = $method->getStartLine()])) {
  815.             return;
  816.         }
  817.         $patchedMethods[$file][$startLine] = true;
  818.         $fileOffset = self::$fileOffsets[$file] ?? 0;
  819.         $startLine += $fileOffset - 2;
  820.         if ($nullable = str_ends_with($returnType, '|null')) {
  821.             $returnType = substr($returnType, 0, -5);
  822.         }
  823.         $glue = str_contains($returnType, '&') ? '&' : '|';
  824.         $returnType = explode($glue, $returnType);
  825.         $code = file($file);
  826.         foreach ($returnType as $i => $type) {
  827.             if (preg_match('/((?:\[\])+)$/', $type, $m)) {
  828.                 $type = substr($type, 0, -\strlen($m[1]));
  829.                 $format = '%s'.$m[1];
  830.             } else {
  831.                 $format = null;
  832.             }
  833.             if (isset(self::SPECIAL_RETURN_TYPES[$type]) || ('\\' === $type[0] && !$p = strrpos($type, '\\', 1))) {
  834.                 continue;
  835.             }
  836.             [$namespace, $useOffset, $useMap] = $useStatements[$file] ??= self::getUseStatements($file);
  837.             if ('\\' !== $type[0]) {
  838.                 [$declaringNamespace, , $declaringUseMap] = $useStatements[$declaringFile] ??= self::getUseStatements($declaringFile);
  839.                 $p = strpos($type, '\\', 1);
  840.                 $alias = $p ? substr($type, 0, $p) : $type;
  841.                 if (isset($declaringUseMap[$alias])) {
  842.                     $type = '\\'.$declaringUseMap[$alias].($p ? substr($type, $p) : '');
  843.                 } else {
  844.                     $type = '\\'.$declaringNamespace.$type;
  845.                 }
  846.                 $p = strrpos($type, '\\', 1);
  847.             }
  848.             $alias = substr($type, 1 + $p);
  849.             $type = substr($type, 1);
  850.             if (!isset($useMap[$alias]) && (class_exists($c = $namespace.$alias) || interface_exists($c) || trait_exists($c))) {
  851.                 $useMap[$alias] = $c;
  852.             }
  853.             if (!isset($useMap[$alias])) {
  854.                 $useStatements[$file][2][$alias] = $type;
  855.                 $code[$useOffset] = "use $type;\n".$code[$useOffset];
  856.                 ++$fileOffset;
  857.             } elseif ($useMap[$alias] !== $type) {
  858.                 $alias .= 'FIXME';
  859.                 $useStatements[$file][2][$alias] = $type;
  860.                 $code[$useOffset] = "use $type as $alias;\n".$code[$useOffset];
  861.                 ++$fileOffset;
  862.             }
  863.             $returnType[$i] = null !== $format ? sprintf($format, $alias) : $alias;
  864.         }
  865.         if ('docblock' === $this->patchTypes['force'] || ('object' === $normalizedType && '7.1' === $this->patchTypes['php'])) {
  866.             $returnType = implode($glue, $returnType).($nullable ? '|null' : '');
  867.             if (str_contains($code[$startLine], '#[')) {
  868.                 --$startLine;
  869.             }
  870.             if ($method->getDocComment()) {
  871.                 $code[$startLine] = "     * @return $returnType\n".$code[$startLine];
  872.             } else {
  873.                 $code[$startLine] .= <<<EOTXT
  874.     /**
  875.      * @return $returnType
  876.      */
  877. EOTXT;
  878.             }
  879.             $fileOffset += substr_count($code[$startLine], "\n") - 1;
  880.         }
  881.         self::$fileOffsets[$file] = $fileOffset;
  882.         file_put_contents($file, $code);
  883.         $this->fixReturnStatements($method, $normalizedType);
  884.     }
  885.     private static function getUseStatements(string $file): array
  886.     {
  887.         $namespace = '';
  888.         $useMap = [];
  889.         $useOffset = 0;
  890.         if (!is_file($file)) {
  891.             return [$namespace, $useOffset, $useMap];
  892.         }
  893.         $file = file($file);
  894.         for ($i = 0; $i < \count($file); ++$i) {
  895.             if (preg_match('/^(class|interface|trait|abstract) /', $file[$i])) {
  896.                 break;
  897.             }
  898.             if (str_starts_with($file[$i], 'namespace ')) {
  899.                 $namespace = substr($file[$i], \strlen('namespace '), -2).'\\';
  900.                 $useOffset = $i + 2;
  901.             }
  902.             if (str_starts_with($file[$i], 'use ')) {
  903.                 $useOffset = $i;
  904.                 for (; str_starts_with($file[$i], 'use '); ++$i) {
  905.                     $u = explode(' as ', substr($file[$i], 4, -2), 2);
  906.                     if (1 === \count($u)) {
  907.                         $p = strrpos($u[0], '\\');
  908.                         $useMap[substr($u[0], false !== $p ? 1 + $p : 0)] = $u[0];
  909.                     } else {
  910.                         $useMap[$u[1]] = $u[0];
  911.                     }
  912.                 }
  913.                 break;
  914.             }
  915.         }
  916.         return [$namespace, $useOffset, $useMap];
  917.     }
  918.     private function fixReturnStatements(\ReflectionMethod $method, string $returnType)
  919.     {
  920.         if ('docblock' !== $this->patchTypes['force']) {
  921.             if ('7.1' === $this->patchTypes['php'] && 'object' === ltrim($returnType, '?')) {
  922.                 return;
  923.             }
  924.             if ('7.4' > $this->patchTypes['php'] && $method->hasReturnType()) {
  925.                 return;
  926.             }
  927.             if ('8.0' > $this->patchTypes['php'] && (str_contains($returnType, '|') || \in_array($returnType, ['mixed', 'static'], true))) {
  928.                 return;
  929.             }
  930.             if ('8.1' > $this->patchTypes['php'] && str_contains($returnType, '&')) {
  931.                 return;
  932.             }
  933.         }
  934.         if (!is_file($file = $method->getFileName())) {
  935.             return;
  936.         }
  937.         $fixedCode = $code = file($file);
  938.         $i = (self::$fileOffsets[$file] ?? 0) + $method->getStartLine();
  939.         if ('?' !== $returnType && 'docblock' !== $this->patchTypes['force']) {
  940.             $fixedCode[$i - 1] = preg_replace('/\)(?::[^;\n]++)?(;?\n)/', "): $returnType\\1", $code[$i - 1]);
  941.         }
  942.         $end = $method->isGenerator() ? $i : $method->getEndLine();
  943.         $inClosure = false;
  944.         $braces = 0;
  945.         for (; $i < $end; ++$i) {
  946.             if (!$inClosure) {
  947.                 $inClosure = str_contains($code[$i], 'function (');
  948.             }
  949.             if ($inClosure) {
  950.                 $braces += substr_count($code[$i], '{') - substr_count($code[$i], '}');
  951.                 $inClosure = $braces > 0;
  952.                 continue;
  953.             }
  954.             if ('void' === $returnType) {
  955.                 $fixedCode[$i] = str_replace('    return null;', '    return;', $code[$i]);
  956.             } elseif ('mixed' === $returnType || '?' === $returnType[0]) {
  957.                 $fixedCode[$i] = str_replace('    return;', '    return null;', $code[$i]);
  958.             } else {
  959.                 $fixedCode[$i] = str_replace('    return;', "    return $returnType!?;", $code[$i]);
  960.             }
  961.         }
  962.         if ($fixedCode !== $code) {
  963.             file_put_contents($file, $fixedCode);
  964.         }
  965.     }
  966.     /**
  967.      * @param \ReflectionClass|\ReflectionMethod|\ReflectionProperty $reflector
  968.      */
  969.     private function parsePhpDoc(\Reflector $reflector): array
  970.     {
  971.         if (!$doc = $reflector->getDocComment()) {
  972.             return [];
  973.         }
  974.         $tagName = '';
  975.         $tagContent = '';
  976.         $tags = [];
  977.         foreach (explode("\n", substr($doc, 3, -2)) as $line) {
  978.             $line = ltrim($line);
  979.             $line = ltrim($line, '*');
  980.             if ('' === $line = trim($line)) {
  981.                 if ('' !== $tagName) {
  982.                     $tags[$tagName][] = $tagContent;
  983.                 }
  984.                 $tagName = $tagContent = '';
  985.                 continue;
  986.             }
  987.             if ('@' === $line[0]) {
  988.                 if ('' !== $tagName) {
  989.                     $tags[$tagName][] = $tagContent;
  990.                     $tagContent = '';
  991.                 }
  992.                 if (preg_match('{^@([-a-zA-Z0-9_:]++)(\s|$)}', $line, $m)) {
  993.                     $tagName = $m[1];
  994.                     $tagContent = str_replace("\t", ' ', ltrim(substr($line, 2 + \strlen($tagName))));
  995.                 } else {
  996.                     $tagName = '';
  997.                 }
  998.             } elseif ('' !== $tagName) {
  999.                 $tagContent .= ' '.str_replace("\t", ' ', $line);
  1000.             }
  1001.         }
  1002.         if ('' !== $tagName) {
  1003.             $tags[$tagName][] = $tagContent;
  1004.         }
  1005.         foreach ($tags['method'] ?? [] as $i => $method) {
  1006.             unset($tags['method'][$i]);
  1007.             $parts = preg_split('{(\s++|\((?:[^()]*+|(?R))*\)(?: *: *[^ ]++)?|<(?:[^<>]*+|(?R))*>|\{(?:[^{}]*+|(?R))*\})}', $method, -1, \PREG_SPLIT_DELIM_CAPTURE);
  1008.             $returnType = '';
  1009.             $static = 'static' === $parts[0];
  1010.             for ($i = $static ? 2 : 0; null !== $p = $parts[$i] ?? null; $i += 2) {
  1011.                 if (\in_array($p, ['', '|', '&', 'callable'], true) || \in_array(substr($returnType, -1), ['|', '&'], true)) {
  1012.                     $returnType .= trim($parts[$i - 1] ?? '').$p;
  1013.                     continue;
  1014.                 }
  1015.                 $signature = '(' === ($parts[$i + 1][0] ?? '(') ? $parts[$i + 1] ?? '()' : null;
  1016.                 if (null === $signature && '' === $returnType) {
  1017.                     $returnType = $p;
  1018.                     continue;
  1019.                 }
  1020.                 if ($static && 2 === $i) {
  1021.                     $static = false;
  1022.                     $returnType = 'static';
  1023.                 }
  1024.                 if (\in_array($description = trim(implode('', \array_slice($parts, 2 + $i))), ['', '.'], true)) {
  1025.                     $description = null;
  1026.                 } elseif (!preg_match('/[.!]$/', $description)) {
  1027.                     $description .= '.';
  1028.                 }
  1029.                 $tags['method'][$p] = [$static, $returnType, $signature ?? '()', $description];
  1030.                 break;
  1031.             }
  1032.         }
  1033.         foreach ($tags['param'] ?? [] as $i => $param) {
  1034.             unset($tags['param'][$i]);
  1035.             if (\strlen($param) !== strcspn($param, '<{(')) {
  1036.                 $param = preg_replace('{\(([^()]*+|(?R))*\)(?: *: *[^ ]++)?|<([^<>]*+|(?R))*>|\{([^{}]*+|(?R))*\}}', '', $param);
  1037.             }
  1038.             if (false === $i = strpos($param, '$')) {
  1039.                 continue;
  1040.             }
  1041.             $type = 0 === $i ? '' : rtrim(substr($param, 0, $i), ' &');
  1042.             $param = substr($param, 1 + $i, (strpos($param, ' ', $i) ?: (1 + $i + \strlen($param))) - $i - 1);
  1043.             $tags['param'][$param] = $type;
  1044.         }
  1045.         foreach (['var', 'return'] as $k) {
  1046.             if (null === $v = $tags[$k][0] ?? null) {
  1047.                 continue;
  1048.             }
  1049.             if (\strlen($v) !== strcspn($v, '<{(')) {
  1050.                 $v = preg_replace('{\(([^()]*+|(?R))*\)(?: *: *[^ ]++)?|<([^<>]*+|(?R))*>|\{([^{}]*+|(?R))*\}}', '', $v);
  1051.             }
  1052.             $tags[$k] = substr($v, 0, strpos($v, ' ') ?: \strlen($v)) ?: null;
  1053.         }
  1054.         return $tags;
  1055.     }
  1056. }