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

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