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

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