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

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