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

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