Aucune description

DebugClassLoader.php 42KB

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