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

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