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

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