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

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