DebugClassLoader.php 50 KB

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