DebugClassLoader.php 41 KB

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