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

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