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