DebugClassLoader.php 41 KB

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