You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1094 lines
42 KiB

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