DebugClassLoader.php 41 KB

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