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

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