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

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.             || 'Test\Symfony\Component\Debug\Tests' === $refl->getNamespaceName()
  355.         ) {
  356.             return [];
  357.         }
  358.         $deprecations = [];
  359.         $className = isset($class[15]) && "\0" === $class[15] && === strpos($class"class@anonymous\x00") ? get_parent_class($class).'@anonymous' $class;
  360.         // Don't trigger deprecations for classes in the same vendor
  361.         if ($class !== $className) {
  362.             $vendor preg_match('/^namespace ([^;\\\\\s]++)[;\\\\]/m', @file_get_contents($refl->getFileName()), $vendor) ? $vendor[1].'\\' '';
  363.             $vendorLen = \strlen($vendor);
  364.         } elseif ($vendorLen + (strpos($class'\\') ?: strpos($class'_'))) {
  365.             $vendorLen 0;
  366.             $vendor '';
  367.         } else {
  368.             $vendor str_replace('_''\\'substr($class0$vendorLen));
  369.         }
  370.         // Detect annotations on the class
  371.         if (false !== $doc $refl->getDocComment()) {
  372.             foreach (['final''deprecated''internal'] as $annotation) {
  373.                 if (false !== strpos($doc$annotation) && preg_match('#\n\s+\* @'.$annotation.'(?:( .+?)\.?)?\r?\n\s+\*(?: @|/$|\r?\n)#s'$doc$notice)) {
  374.                     self::${$annotation}[$class] = isset($notice[1]) ? preg_replace('#\.?\r?\n( \*)? *(?= |\r?\n|$)#'''$notice[1]) : '';
  375.                 }
  376.             }
  377.             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)) {
  378.                 foreach ($notice as $method) {
  379.                     $static '' !== $method[1];
  380.                     $name $method[2];
  381.                     $description $method[3] ?? null;
  382.                     if (false === strpos($name'(')) {
  383.                         $name .= '()';
  384.                     }
  385.                     if (null !== $description) {
  386.                         $description trim($description);
  387.                         if (!isset($method[4])) {
  388.                             $description .= '.';
  389.                         }
  390.                     }
  391.                     self::$method[$class][] = [$class$name$static$description];
  392.                 }
  393.             }
  394.         }
  395.         $parent get_parent_class($class) ?: null;
  396.         $parentAndOwnInterfaces $this->getOwnInterfaces($class$parent);
  397.         if ($parent) {
  398.             $parentAndOwnInterfaces[$parent] = $parent;
  399.             if (!isset(self::$checkedClasses[$parent])) {
  400.                 $this->checkClass($parent);
  401.             }
  402.             if (isset(self::$final[$parent])) {
  403.                 $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);
  404.             }
  405.         }
  406.         // Detect if the parent is annotated
  407.         foreach ($parentAndOwnInterfaces class_uses($classfalse) as $use) {
  408.             if (!isset(self::$checkedClasses[$use])) {
  409.                 $this->checkClass($use);
  410.             }
  411.             if (isset(self::$deprecated[$use]) && strncmp($vendorstr_replace('_''\\'$use), $vendorLen) && !isset(self::$deprecated[$class])) {
  412.                 $type class_exists($classfalse) ? 'class' : (interface_exists($classfalse) ? 'interface' 'trait');
  413.                 $verb class_exists($usefalse) || interface_exists($classfalse) ? 'extends' : (interface_exists($usefalse) ? 'implements' 'uses');
  414.                 $deprecations[] = sprintf('The "%s" %s %s "%s" that is deprecated%s.'$className$type$verb$useself::$deprecated[$use]);
  415.             }
  416.             if (isset(self::$internal[$use]) && strncmp($vendorstr_replace('_''\\'$use), $vendorLen)) {
  417.                 $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);
  418.             }
  419.             if (isset(self::$method[$use])) {
  420.                 if ($refl->isAbstract()) {
  421.                     if (isset(self::$method[$class])) {
  422.                         self::$method[$class] = array_merge(self::$method[$class], self::$method[$use]);
  423.                     } else {
  424.                         self::$method[$class] = self::$method[$use];
  425.                     }
  426.                 } elseif (!$refl->isInterface()) {
  427.                     $hasCall $refl->hasMethod('__call');
  428.                     $hasStaticCall $refl->hasMethod('__callStatic');
  429.                     foreach (self::$method[$use] as $method) {
  430.                         list($interface$name$static$description) = $method;
  431.                         if ($static $hasStaticCall $hasCall) {
  432.                             continue;
  433.                         }
  434.                         $realName substr($name0strpos($name'('));
  435.                         if (!$refl->hasMethod($realName) || !($methodRefl $refl->getMethod($realName))->isPublic() || ($static && !$methodRefl->isStatic()) || (!$static && $methodRefl->isStatic())) {
  436.                             $deprecations[] = sprintf('Class "%s" should implement method "%s::%s"%s'$className, ($static 'static ' '').$interface$namenull == $description '.' ': '.$description);
  437.                         }
  438.                     }
  439.                 }
  440.             }
  441.         }
  442.         if (trait_exists($class)) {
  443.             $file $refl->getFileName();
  444.             foreach ($refl->getMethods() as $method) {
  445.                 if ($method->getFileName() === $file) {
  446.                     self::$methodTraits[$file][$method->getStartLine()] = $class;
  447.                 }
  448.             }
  449.             return $deprecations;
  450.         }
  451.         // Inherit @final, @internal, @param and @return annotations for methods
  452.         self::$finalMethods[$class] = [];
  453.         self::$internalMethods[$class] = [];
  454.         self::$annotatedParameters[$class] = [];
  455.         self::$returnTypes[$class] = [];
  456.         foreach ($parentAndOwnInterfaces as $use) {
  457.             foreach (['finalMethods''internalMethods''annotatedParameters''returnTypes'] as $property) {
  458.                 if (isset(self::${$property}[$use])) {
  459.                     self::${$property}[$class] = self::${$property}[$class] ? self::${$property}[$use] + self::${$property}[$class] : self::${$property}[$use];
  460.                 }
  461.             }
  462.             if (null !== (self::INTERNAL_TYPES[$use] ?? null)) {
  463.                 foreach (self::INTERNAL_TYPES[$use] as $method => $returnType) {
  464.                     if ('void' !== $returnType) {
  465.                         self::$returnTypes[$class] += [$method => [$returnType$returnType$class'']];
  466.                     }
  467.                 }
  468.             }
  469.         }
  470.         foreach ($refl->getMethods() as $method) {
  471.             if ($method->class !== $class) {
  472.                 continue;
  473.             }
  474.             if (null === $ns self::$methodTraits[$method->getFileName()][$method->getStartLine()] ?? null) {
  475.                 $ns $vendor;
  476.                 $len $vendorLen;
  477.             } elseif ($len + (strpos($ns'\\') ?: strpos($ns'_'))) {
  478.                 $len 0;
  479.                 $ns '';
  480.             } else {
  481.                 $ns str_replace('_''\\'substr($ns0$len));
  482.             }
  483.             if ($parent && isset(self::$finalMethods[$parent][$method->name])) {
  484.                 list($declaringClass$message) = self::$finalMethods[$parent][$method->name];
  485.                 $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);
  486.             }
  487.             if (isset(self::$internalMethods[$class][$method->name])) {
  488.                 list($declaringClass$message) = self::$internalMethods[$class][$method->name];
  489.                 if (strncmp($ns$declaringClass$len)) {
  490.                     $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);
  491.                 }
  492.             }
  493.             // To read method annotations
  494.             $doc $method->getDocComment();
  495.             if (isset(self::$annotatedParameters[$class][$method->name])) {
  496.                 $definedParameters = [];
  497.                 foreach ($method->getParameters() as $parameter) {
  498.                     $definedParameters[$parameter->name] = true;
  499.                 }
  500.                 foreach (self::$annotatedParameters[$class][$method->name] as $parameterName => $deprecation) {
  501.                     if (!isset($definedParameters[$parameterName]) && !($doc && preg_match("/\\n\\s+\\* @param +((?(?!callable *\().*?|callable *\(.*\).*?))(?<= )\\\${$parameterName}\\b/"$doc))) {
  502.                         $deprecations[] = sprintf($deprecation$className);
  503.                     }
  504.                 }
  505.             }
  506.             $forcePatchTypes $this->patchTypes['force'];
  507.             if ($canAddReturnType null !== $forcePatchTypes && false === strpos($method->getFileName(), \DIRECTORY_SEPARATOR.'vendor'.\DIRECTORY_SEPARATOR)) {
  508.                 if ('void' !== (self::MAGIC_METHODS[$method->name] ?? 'void')) {
  509.                     $this->patchTypes['force'] = $forcePatchTypes ?: 'docblock';
  510.                 }
  511.                 $canAddReturnType false !== strpos($refl->getFileName(), \DIRECTORY_SEPARATOR.'Tests'.\DIRECTORY_SEPARATOR)
  512.                     || $refl->isFinal()
  513.                     || $method->isFinal()
  514.                     || $method->isPrivate()
  515.                     || ('' === (self::$internal[$class] ?? null) && !$refl->isAbstract())
  516.                     || '' === (self::$final[$class] ?? null)
  517.                     || preg_match('/@(final|internal)$/m'$doc)
  518.                 ;
  519.             }
  520.             if (null !== ($returnType self::$returnTypes[$class][$method->name] ?? self::MAGIC_METHODS[$method->name] ?? null) && !$method->hasReturnType() && !($doc && preg_match('/\n\s+\* @return +(\S+)/'$doc))) {
  521.                 list($normalizedType$returnType$declaringClass$declaringFile) = \is_string($returnType) ? [$returnType$returnType''''] : $returnType;
  522.                 if ('void' === $normalizedType) {
  523.                     $canAddReturnType false;
  524.                 }
  525.                 if ($canAddReturnType && 'docblock' !== $this->patchTypes['force']) {
  526.                     $this->patchMethod($method$returnType$declaringFile$normalizedType);
  527.                 }
  528.                 if (strncmp($ns$declaringClass$len)) {
  529.                     if ($canAddReturnType && 'docblock' === $this->patchTypes['force'] && false === strpos($method->getFileName(), \DIRECTORY_SEPARATOR.'vendor'.\DIRECTORY_SEPARATOR)) {
  530.                         $this->patchMethod($method$returnType$declaringFile$normalizedType);
  531.                     } elseif ('' !== $declaringClass && $this->patchTypes['deprecations']) {
  532.                         $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);
  533.                     }
  534.                 }
  535.             }
  536.             if (!$doc) {
  537.                 $this->patchTypes['force'] = $forcePatchTypes;
  538.                 continue;
  539.             }
  540.             $matches = [];
  541.             if (!$method->hasReturnType() && ((false !== strpos($doc'@return') && preg_match('/\n\s+\* @return +(\S+)/'$doc$matches)) || 'void' !== (self::MAGIC_METHODS[$method->name] ?? 'void'))) {
  542.                 $matches $matches ?: [=> self::MAGIC_METHODS[$method->name]];
  543.                 $this->setReturnType($matches[1], $method$parent);
  544.                 if (isset(self::$returnTypes[$class][$method->name][0]) && $canAddReturnType) {
  545.                     $this->fixReturnStatements($methodself::$returnTypes[$class][$method->name][0]);
  546.                 }
  547.                 if ($method->isPrivate()) {
  548.                     unset(self::$returnTypes[$class][$method->name]);
  549.                 }
  550.             }
  551.             $this->patchTypes['force'] = $forcePatchTypes;
  552.             if ($method->isPrivate()) {
  553.                 continue;
  554.             }
  555.             $finalOrInternal false;
  556.             foreach (['final''internal'] as $annotation) {
  557.                 if (false !== strpos($doc$annotation) && preg_match('#\n\s+\* @'.$annotation.'(?:( .+?)\.?)?\r?\n\s+\*(?: @|/$|\r?\n)#s'$doc$notice)) {
  558.                     $message = isset($notice[1]) ? preg_replace('#\.?\r?\n( \*)? *(?= |\r?\n|$)#'''$notice[1]) : '';
  559.                     self::${$annotation.'Methods'}[$class][$method->name] = [$class$message];
  560.                     $finalOrInternal true;
  561.                 }
  562.             }
  563.             if ($finalOrInternal || $method->isConstructor() || false === strpos($doc'@param') || StatelessInvocation::class === $class) {
  564.                 continue;
  565.             }
  566.             if (!preg_match_all('#\n\s+\* @param +((?(?!callable *\().*?|callable *\(.*\).*?))(?<= )\$([a-zA-Z0-9_\x7f-\xff]++)#'$doc$matchesPREG_SET_ORDER)) {
  567.                 continue;
  568.             }
  569.             if (!isset(self::$annotatedParameters[$class][$method->name])) {
  570.                 $definedParameters = [];
  571.                 foreach ($method->getParameters() as $parameter) {
  572.                     $definedParameters[$parameter->name] = true;
  573.                 }
  574.             }
  575.             foreach ($matches as list(, $parameterType$parameterName)) {
  576.                 if (!isset($definedParameters[$parameterName])) {
  577.                     $parameterType trim($parameterType);
  578.                     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);
  579.                 }
  580.             }
  581.         }
  582.         return $deprecations;
  583.     }
  584.     public function checkCase(\ReflectionClass $reflstring $filestring $class): ?array
  585.     {
  586.         $real explode('\\'$class.strrchr($file'.'));
  587.         $tail explode(\DIRECTORY_SEPARATORstr_replace('/', \DIRECTORY_SEPARATOR$file));
  588.         $i = \count($tail) - 1;
  589.         $j = \count($real) - 1;
  590.         while (isset($tail[$i], $real[$j]) && $tail[$i] === $real[$j]) {
  591.             --$i;
  592.             --$j;
  593.         }
  594.         array_splice($tail0$i 1);
  595.         if (!$tail) {
  596.             return null;
  597.         }
  598.         $tail = \DIRECTORY_SEPARATOR.implode(\DIRECTORY_SEPARATOR$tail);
  599.         $tailLen = \strlen($tail);
  600.         $real $refl->getFileName();
  601.         if (=== self::$caseCheck) {
  602.             $real $this->darwinRealpath($real);
  603.         }
  604.         if (=== substr_compare($real$tail, -$tailLen$tailLentrue)
  605.             && !== substr_compare($real$tail, -$tailLen$tailLenfalse)
  606.         ) {
  607.             return [substr($tail, -$tailLen 1), substr($real, -$tailLen 1), substr($real0, -$tailLen 1)];
  608.         }
  609.         return null;
  610.     }
  611.     /**
  612.      * `realpath` on MacOSX doesn't normalize the case of characters.
  613.      */
  614.     private function darwinRealpath(string $real): string
  615.     {
  616.         $i strrpos($real'/');
  617.         $file substr($real$i);
  618.         $real substr($real0$i);
  619.         if (isset(self::$darwinCache[$real])) {
  620.             $kDir $real;
  621.         } else {
  622.             $kDir strtolower($real);
  623.             if (isset(self::$darwinCache[$kDir])) {
  624.                 $real self::$darwinCache[$kDir][0];
  625.             } else {
  626.                 $dir getcwd();
  627.                 if (!@chdir($real)) {
  628.                     return $real.$file;
  629.                 }
  630.                 $real getcwd().'/';
  631.                 chdir($dir);
  632.                 $dir $real;
  633.                 $k $kDir;
  634.                 $i = \strlen($dir) - 1;
  635.                 while (!isset(self::$darwinCache[$k])) {
  636.                     self::$darwinCache[$k] = [$dir, []];
  637.                     self::$darwinCache[$dir] = &self::$darwinCache[$k];
  638.                     while ('/' !== $dir[--$i]) {
  639.                     }
  640.                     $k substr($k0, ++$i);
  641.                     $dir substr($dir0$i--);
  642.                 }
  643.             }
  644.         }
  645.         $dirFiles self::$darwinCache[$kDir][1];
  646.         if (!isset($dirFiles[$file]) && ') : eval()\'d code' === substr($file, -17)) {
  647.             // Get the file name from "file_name.php(123) : eval()'d code"
  648.             $file substr($file0strrpos($file'(', -17));
  649.         }
  650.         if (isset($dirFiles[$file])) {
  651.             return $real .= $dirFiles[$file];
  652.         }
  653.         $kFile strtolower($file);
  654.         if (!isset($dirFiles[$kFile])) {
  655.             foreach (scandir($real2) as $f) {
  656.                 if ('.' !== $f[0]) {
  657.                     $dirFiles[$f] = $f;
  658.                     if ($f === $file) {
  659.                         $kFile $k $file;
  660.                     } elseif ($f !== $k strtolower($f)) {
  661.                         $dirFiles[$k] = $f;
  662.                     }
  663.                 }
  664.             }
  665.             self::$darwinCache[$kDir][1] = $dirFiles;
  666.         }
  667.         return $real .= $dirFiles[$kFile];
  668.     }
  669.     /**
  670.      * `class_implements` includes interfaces from the parents so we have to manually exclude them.
  671.      *
  672.      * @return string[]
  673.      */
  674.     private function getOwnInterfaces(string $class, ?string $parent): array
  675.     {
  676.         $ownInterfaces class_implements($classfalse);
  677.         if ($parent) {
  678.             foreach (class_implements($parentfalse) as $interface) {
  679.                 unset($ownInterfaces[$interface]);
  680.             }
  681.         }
  682.         foreach ($ownInterfaces as $interface) {
  683.             foreach (class_implements($interface) as $interface) {
  684.                 unset($ownInterfaces[$interface]);
  685.             }
  686.         }
  687.         return $ownInterfaces;
  688.     }
  689.     private function setReturnType(string $types, \ReflectionMethod $method, ?string $parent): void
  690.     {
  691.         $nullable false;
  692.         $typesMap = [];
  693.         foreach (explode('|'$types) as $t) {
  694.             $typesMap[$this->normalizeType($t$method->class$parent)] = $t;
  695.         }
  696.         if (isset($typesMap['array'])) {
  697.             if (isset($typesMap['Traversable']) || isset($typesMap['\Traversable'])) {
  698.                 $typesMap['iterable'] = 'array' !== $typesMap['array'] ? $typesMap['array'] : 'iterable';
  699.                 unset($typesMap['array'], $typesMap['Traversable'], $typesMap['\Traversable']);
  700.             } elseif ('array' !== $typesMap['array'] && isset(self::$returnTypes[$method->class][$method->name])) {
  701.                 return;
  702.             }
  703.         }
  704.         if (isset($typesMap['array']) && isset($typesMap['iterable'])) {
  705.             if ('[]' === substr($typesMap['array'], -2)) {
  706.                 $typesMap['iterable'] = $typesMap['array'];
  707.             }
  708.             unset($typesMap['array']);
  709.         }
  710.         $iterable $object true;
  711.         foreach ($typesMap as $n => $t) {
  712.             if ('null' !== $n) {
  713.                 $iterable $iterable && (\in_array($n, ['array''iterable']) || false !== strpos($n'Iterator'));
  714.                 $object $object && (\in_array($n, ['callable''object''$this''static']) || !isset(self::SPECIAL_RETURN_TYPES[$n]));
  715.             }
  716.         }
  717.         $normalizedType key($typesMap);
  718.         $returnType current($typesMap);
  719.         foreach ($typesMap as $n => $t) {
  720.             if ('null' === $n) {
  721.                 $nullable true;
  722.             } elseif ('null' === $normalizedType) {
  723.                 $normalizedType $t;
  724.                 $returnType $t;
  725.             } 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)) {
  726.                 if ($iterable) {
  727.                     $normalizedType $returnType 'iterable';
  728.                 } elseif ($object && 'object' === $this->patchTypes['force']) {
  729.                     $normalizedType $returnType 'object';
  730.                 } else {
  731.                     // ignore multi-types return declarations
  732.                     return;
  733.                 }
  734.             }
  735.         }
  736.         if ('void' === $normalizedType) {
  737.             $nullable false;
  738.         } elseif (!isset(self::BUILTIN_RETURN_TYPES[$normalizedType]) && isset(self::SPECIAL_RETURN_TYPES[$normalizedType])) {
  739.             // ignore other special return types
  740.             return;
  741.         }
  742.         if ($nullable) {
  743.             $normalizedType '?'.$normalizedType;
  744.             $returnType .= '|null';
  745.         }
  746.         self::$returnTypes[$method->class][$method->name] = [$normalizedType$returnType$method->class$method->getFileName()];
  747.     }
  748.     private function normalizeType(string $typestring $class, ?string $parent): string
  749.     {
  750.         if (isset(self::SPECIAL_RETURN_TYPES[$lcType strtolower($type)])) {
  751.             if ('parent' === $lcType self::SPECIAL_RETURN_TYPES[$lcType]) {
  752.                 $lcType null !== $parent '\\'.$parent 'parent';
  753.             } elseif ('self' === $lcType) {
  754.                 $lcType '\\'.$class;
  755.             }
  756.             return $lcType;
  757.         }
  758.         if ('[]' === substr($type, -2)) {
  759.             return 'array';
  760.         }
  761.         if (preg_match('/^(array|iterable|callable) *[<(]/'$lcType$m)) {
  762.             return $m[1];
  763.         }
  764.         // We could resolve "use" statements to return the FQDN
  765.         // but this would be too expensive for a runtime checker
  766.         return $type;
  767.     }
  768.     /**
  769.      * Utility method to add @return annotations to the Symfony code-base where it triggers a self-deprecations.
  770.      */
  771.     private function patchMethod(\ReflectionMethod $methodstring $returnTypestring $declaringFilestring $normalizedType)
  772.     {
  773.         static $patchedMethods = [];
  774.         static $useStatements = [];
  775.         if (!file_exists($file $method->getFileName()) || isset($patchedMethods[$file][$startLine $method->getStartLine()])) {
  776.             return;
  777.         }
  778.         $patchedMethods[$file][$startLine] = true;
  779.         $fileOffset self::$fileOffsets[$file] ?? 0;
  780.         $startLine += $fileOffset 2;
  781.         $nullable '?' === $normalizedType[0] ? '?' '';
  782.         $normalizedType ltrim($normalizedType'?');
  783.         $returnType explode('|'$returnType);
  784.         $code file($file);
  785.         foreach ($returnType as $i => $type) {
  786.             if (preg_match('/((?:\[\])+)$/'$type$m)) {
  787.                 $type substr($type0, -\strlen($m[1]));
  788.                 $format '%s'.$m[1];
  789.             } elseif (preg_match('/^(array|iterable)<([^,>]++)>$/'$type$m)) {
  790.                 $type $m[2];
  791.                 $format $m[1].'<%s>';
  792.             } else {
  793.                 $format null;
  794.             }
  795.             if (isset(self::SPECIAL_RETURN_TYPES[$type]) || ('\\' === $type[0] && !$p strrpos($type'\\'1))) {
  796.                 continue;
  797.             }
  798.             list($namespace$useOffset$useMap) = $useStatements[$file] ?? $useStatements[$file] = self::getUseStatements($file);
  799.             if ('\\' !== $type[0]) {
  800.                 list($declaringNamespace, , $declaringUseMap) = $useStatements[$declaringFile] ?? $useStatements[$declaringFile] = self::getUseStatements($declaringFile);
  801.                 $p strpos($type'\\'1);
  802.                 $alias $p substr($type0$p) : $type;
  803.                 if (isset($declaringUseMap[$alias])) {
  804.                     $type '\\'.$declaringUseMap[$alias].($p substr($type$p) : '');
  805.                 } else {
  806.                     $type '\\'.$declaringNamespace.$type;
  807.                 }
  808.                 $p strrpos($type'\\'1);
  809.             }
  810.             $alias substr($type$p);
  811.             $type substr($type1);
  812.             if (!isset($useMap[$alias]) && (class_exists($c $namespace.$alias) || interface_exists($c) || trait_exists($c))) {
  813.                 $useMap[$alias] = $c;
  814.             }
  815.             if (!isset($useMap[$alias])) {
  816.                 $useStatements[$file][2][$alias] = $type;
  817.                 $code[$useOffset] = "use $type;\n".$code[$useOffset];
  818.                 ++$fileOffset;
  819.             } elseif ($useMap[$alias] !== $type) {
  820.                 $alias .= 'FIXME';
  821.                 $useStatements[$file][2][$alias] = $type;
  822.                 $code[$useOffset] = "use $type as $alias;\n".$code[$useOffset];
  823.                 ++$fileOffset;
  824.             }
  825.             $returnType[$i] = null !== $format sprintf($format$alias) : $alias;
  826.             if (!isset(self::SPECIAL_RETURN_TYPES[$normalizedType]) && !isset(self::SPECIAL_RETURN_TYPES[$returnType[$i]])) {
  827.                 $normalizedType $returnType[$i];
  828.             }
  829.         }
  830.         if ('docblock' === $this->patchTypes['force'] || ('object' === $normalizedType && '7.1' === $this->patchTypes['php'])) {
  831.             $returnType implode('|'$returnType);
  832.             if ($method->getDocComment()) {
  833.                 $code[$startLine] = "     * @return $returnType\n".$code[$startLine];
  834.             } else {
  835.                 $code[$startLine] .= <<<EOTXT
  836.     /**
  837.      * @return $returnType
  838.      */
  839. EOTXT;
  840.             }
  841.             $fileOffset += substr_count($code[$startLine], "\n") - 1;
  842.         }
  843.         self::$fileOffsets[$file] = $fileOffset;
  844.         file_put_contents($file$code);
  845.         $this->fixReturnStatements($method$nullable.$normalizedType);
  846.     }
  847.     private static function getUseStatements(string $file): array
  848.     {
  849.         $namespace '';
  850.         $useMap = [];
  851.         $useOffset 0;
  852.         if (!file_exists($file)) {
  853.             return [$namespace$useOffset$useMap];
  854.         }
  855.         $file file($file);
  856.         for ($i 0$i < \count($file); ++$i) {
  857.             if (preg_match('/^(class|interface|trait|abstract) /'$file[$i])) {
  858.                 break;
  859.             }
  860.             if (=== strpos($file[$i], 'namespace ')) {
  861.                 $namespace substr($file[$i], \strlen('namespace '), -2).'\\';
  862.                 $useOffset $i 2;
  863.             }
  864.             if (=== strpos($file[$i], 'use ')) {
  865.                 $useOffset $i;
  866.                 for (; === strpos($file[$i], 'use '); ++$i) {
  867.                     $u explode(' as 'substr($file[$i], 4, -2), 2);
  868.                     if (=== \count($u)) {
  869.                         $p strrpos($u[0], '\\');
  870.                         $useMap[substr($u[0], false !== $p $p 0)] = $u[0];
  871.                     } else {
  872.                         $useMap[$u[1]] = $u[0];
  873.                     }
  874.                 }
  875.                 break;
  876.             }
  877.         }
  878.         return [$namespace$useOffset$useMap];
  879.     }
  880.     private function fixReturnStatements(\ReflectionMethod $methodstring $returnType)
  881.     {
  882.         if ('7.1' === $this->patchTypes['php'] && 'object' === ltrim($returnType'?') && 'docblock' !== $this->patchTypes['force']) {
  883.             return;
  884.         }
  885.         if (!file_exists($file $method->getFileName())) {
  886.             return;
  887.         }
  888.         $fixedCode $code file($file);
  889.         $i = (self::$fileOffsets[$file] ?? 0) + $method->getStartLine();
  890.         if ('?' !== $returnType && 'docblock' !== $this->patchTypes['force']) {
  891.             $fixedCode[$i 1] = preg_replace('/\)(;?\n)/'"): $returnType\\1"$code[$i 1]);
  892.         }
  893.         $end $method->isGenerator() ? $i $method->getEndLine();
  894.         for (; $i $end; ++$i) {
  895.             if ('void' === $returnType) {
  896.                 $fixedCode[$i] = str_replace('    return null;''    return;'$code[$i]);
  897.             } elseif ('mixed' === $returnType || '?' === $returnType[0]) {
  898.                 $fixedCode[$i] = str_replace('    return;''    return null;'$code[$i]);
  899.             } else {
  900.                 $fixedCode[$i] = str_replace('    return;'"    return $returnType!?;"$code[$i]);
  901.             }
  902.         }
  903.         if ($fixedCode !== $code) {
  904.             file_put_contents($file$fixedCode);
  905.         }
  906.     }
  907. }