DebugClassLoader.php 42 KB

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