DebugClassLoader.php 45 KB

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