DebugClassLoader.php 49 KB

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