DebugClassLoader.php 48 KB

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