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

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