DebugClassLoader.php 45 KB

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