DebugClassLoader.php 52 KB

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