vendor/symfony/error-handler/DebugClassLoader.php line 307

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