DebugClassLoader.php 48 KB

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