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

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