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

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