DebugClassLoader.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  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\Debug;
  11. use PHPUnit\Framework\MockObject\Matcher\StatelessInvocation;
  12. /**
  13. * Autoloader checking if the class is really defined in the file found.
  14. *
  15. * The ClassLoader will wrap all registered autoloaders
  16. * and will throw an exception if a file is found but does
  17. * not declare the class.
  18. *
  19. * @author Fabien Potencier <fabien@symfony.com>
  20. * @author Christophe Coevoet <stof@notk.org>
  21. * @author Nicolas Grekas <p@tchwork.com>
  22. * @author Guilhem Niot <guilhem.niot@gmail.com>
  23. */
  24. class DebugClassLoader
  25. {
  26. private $classLoader;
  27. private $isFinder;
  28. private $loaded = [];
  29. private static $caseCheck;
  30. private static $checkedClasses = [];
  31. private static $final = [];
  32. private static $finalMethods = [];
  33. private static $deprecated = [];
  34. private static $internal = [];
  35. private static $internalMethods = [];
  36. private static $annotatedParameters = [];
  37. private static $darwinCache = ['/' => ['/', []]];
  38. public function __construct(callable $classLoader)
  39. {
  40. $this->classLoader = $classLoader;
  41. $this->isFinder = \is_array($classLoader) && method_exists($classLoader[0], 'findFile');
  42. if (!isset(self::$caseCheck)) {
  43. $file = file_exists(__FILE__) ? __FILE__ : rtrim(realpath('.'), \DIRECTORY_SEPARATOR);
  44. $i = strrpos($file, \DIRECTORY_SEPARATOR);
  45. $dir = substr($file, 0, 1 + $i);
  46. $file = substr($file, 1 + $i);
  47. $test = strtoupper($file) === $file ? strtolower($file) : strtoupper($file);
  48. $test = realpath($dir.$test);
  49. if (false === $test || false === $i) {
  50. // filesystem is case sensitive
  51. self::$caseCheck = 0;
  52. } elseif (substr($test, -\strlen($file)) === $file) {
  53. // filesystem is case insensitive and realpath() normalizes the case of characters
  54. self::$caseCheck = 1;
  55. } elseif (false !== stripos(PHP_OS, 'darwin')) {
  56. // on MacOSX, HFS+ is case insensitive but realpath() doesn't normalize the case of characters
  57. self::$caseCheck = 2;
  58. } else {
  59. // filesystem case checks failed, fallback to disabling them
  60. self::$caseCheck = 0;
  61. }
  62. }
  63. }
  64. /**
  65. * Gets the wrapped class loader.
  66. *
  67. * @return callable The wrapped class loader
  68. */
  69. public function getClassLoader()
  70. {
  71. return $this->classLoader;
  72. }
  73. /**
  74. * Wraps all autoloaders.
  75. */
  76. public static function enable()
  77. {
  78. // Ensures we don't hit https://bugs.php.net/42098
  79. class_exists('Symfony\Component\Debug\ErrorHandler');
  80. class_exists('Psr\Log\LogLevel');
  81. if (!\is_array($functions = spl_autoload_functions())) {
  82. return;
  83. }
  84. foreach ($functions as $function) {
  85. spl_autoload_unregister($function);
  86. }
  87. foreach ($functions as $function) {
  88. if (!\is_array($function) || !$function[0] instanceof self) {
  89. $function = [new static($function), 'loadClass'];
  90. }
  91. spl_autoload_register($function);
  92. }
  93. }
  94. /**
  95. * Disables the wrapping.
  96. */
  97. public static function disable()
  98. {
  99. if (!\is_array($functions = spl_autoload_functions())) {
  100. return;
  101. }
  102. foreach ($functions as $function) {
  103. spl_autoload_unregister($function);
  104. }
  105. foreach ($functions as $function) {
  106. if (\is_array($function) && $function[0] instanceof self) {
  107. $function = $function[0]->getClassLoader();
  108. }
  109. spl_autoload_register($function);
  110. }
  111. }
  112. /**
  113. * @return string|null
  114. */
  115. public function findFile($class)
  116. {
  117. return $this->isFinder ? $this->classLoader[0]->findFile($class) ?: null : null;
  118. }
  119. /**
  120. * Loads the given class or interface.
  121. *
  122. * @param string $class The name of the class
  123. *
  124. * @throws \RuntimeException
  125. */
  126. public function loadClass($class)
  127. {
  128. $e = error_reporting(error_reporting() | E_PARSE | E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR);
  129. try {
  130. if ($this->isFinder && !isset($this->loaded[$class])) {
  131. $this->loaded[$class] = true;
  132. if (!$file = $this->classLoader[0]->findFile($class) ?: false) {
  133. // no-op
  134. } elseif (\function_exists('opcache_is_script_cached') && @opcache_is_script_cached($file)) {
  135. require $file;
  136. return;
  137. } else {
  138. require $file;
  139. }
  140. } else {
  141. ($this->classLoader)($class);
  142. $file = false;
  143. }
  144. } finally {
  145. error_reporting($e);
  146. }
  147. $this->checkClass($class, $file);
  148. }
  149. private function checkClass($class, $file = null)
  150. {
  151. $exists = null === $file || \class_exists($class, false) || \interface_exists($class, false) || \trait_exists($class, false);
  152. if (null !== $file && $class && '\\' === $class[0]) {
  153. $class = substr($class, 1);
  154. }
  155. if ($exists) {
  156. if (isset(self::$checkedClasses[$class])) {
  157. return;
  158. }
  159. self::$checkedClasses[$class] = true;
  160. $refl = new \ReflectionClass($class);
  161. if (null === $file && $refl->isInternal()) {
  162. return;
  163. }
  164. $name = $refl->getName();
  165. if ($name !== $class && 0 === \strcasecmp($name, $class)) {
  166. throw new \RuntimeException(sprintf('Case mismatch between loaded and declared class names: "%s" vs "%s".', $class, $name));
  167. }
  168. $deprecations = $this->checkAnnotations($refl, $name);
  169. foreach ($deprecations as $message) {
  170. @trigger_error($message, E_USER_DEPRECATED);
  171. }
  172. }
  173. if (!$file) {
  174. return;
  175. }
  176. if (!$exists) {
  177. if (false !== strpos($class, '/')) {
  178. 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));
  179. }
  180. 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));
  181. }
  182. if (self::$caseCheck && $message = $this->checkCase($refl, $file, $class)) {
  183. throw new \RuntimeException(sprintf('Case mismatch between class and real file names: "%s" vs "%s" in "%s".', $message[0], $message[1], $message[2]));
  184. }
  185. }
  186. public function checkAnnotations(\ReflectionClass $refl, $class)
  187. {
  188. $deprecations = [];
  189. // Don't trigger deprecations for classes in the same vendor
  190. if (2 > $len = 1 + (\strpos($class, '\\') ?: \strpos($class, '_'))) {
  191. $len = 0;
  192. $ns = '';
  193. } else {
  194. $ns = \str_replace('_', '\\', \substr($class, 0, $len));
  195. }
  196. // Detect annotations on the class
  197. if (false !== $doc = $refl->getDocComment()) {
  198. foreach (['final', 'deprecated', 'internal'] as $annotation) {
  199. if (false !== \strpos($doc, $annotation) && preg_match('#\n\s+\* @'.$annotation.'(?:( .+?)\.?)?\r?\n\s+\*(?: @|/$)#s', $doc, $notice)) {
  200. self::${$annotation}[$class] = isset($notice[1]) ? preg_replace('#\.?\r?\n( \*)? *(?= |\r?\n|$)#', '', $notice[1]) : '';
  201. }
  202. }
  203. }
  204. $parent = \get_parent_class($class);
  205. $parentAndOwnInterfaces = $this->getOwnInterfaces($class, $parent);
  206. if ($parent) {
  207. $parentAndOwnInterfaces[$parent] = $parent;
  208. if (!isset(self::$checkedClasses[$parent])) {
  209. $this->checkClass($parent);
  210. }
  211. if (isset(self::$final[$parent])) {
  212. $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], $class);
  213. }
  214. }
  215. // Detect if the parent is annotated
  216. foreach ($parentAndOwnInterfaces + \class_uses($class, false) as $use) {
  217. if (!isset(self::$checkedClasses[$use])) {
  218. $this->checkClass($use);
  219. }
  220. if (isset(self::$deprecated[$use]) && \strncmp($ns, \str_replace('_', '\\', $use), $len)) {
  221. $type = class_exists($class, false) ? 'class' : (interface_exists($class, false) ? 'interface' : 'trait');
  222. $verb = class_exists($use, false) || interface_exists($class, false) ? 'extends' : (interface_exists($use, false) ? 'implements' : 'uses');
  223. $deprecations[] = sprintf('The "%s" %s %s "%s" that is deprecated%s.', $class, $type, $verb, $use, self::$deprecated[$use]);
  224. }
  225. if (isset(self::$internal[$use]) && \strncmp($ns, \str_replace('_', '\\', $use), $len)) {
  226. $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], $class);
  227. }
  228. }
  229. if (\trait_exists($class)) {
  230. return $deprecations;
  231. }
  232. // Inherit @final, @internal and @param annotations for methods
  233. self::$finalMethods[$class] = [];
  234. self::$internalMethods[$class] = [];
  235. self::$annotatedParameters[$class] = [];
  236. foreach ($parentAndOwnInterfaces as $use) {
  237. foreach (['finalMethods', 'internalMethods', 'annotatedParameters'] as $property) {
  238. if (isset(self::${$property}[$use])) {
  239. self::${$property}[$class] = self::${$property}[$class] ? self::${$property}[$use] + self::${$property}[$class] : self::${$property}[$use];
  240. }
  241. }
  242. }
  243. foreach ($refl->getMethods(\ReflectionMethod::IS_PUBLIC | \ReflectionMethod::IS_PROTECTED) as $method) {
  244. if ($method->class !== $class) {
  245. continue;
  246. }
  247. if ($parent && isset(self::$finalMethods[$parent][$method->name])) {
  248. list($declaringClass, $message) = self::$finalMethods[$parent][$method->name];
  249. $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, $class);
  250. }
  251. if (isset(self::$internalMethods[$class][$method->name])) {
  252. list($declaringClass, $message) = self::$internalMethods[$class][$method->name];
  253. if (\strncmp($ns, $declaringClass, $len)) {
  254. $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, $class);
  255. }
  256. }
  257. // To read method annotations
  258. $doc = $method->getDocComment();
  259. if (isset(self::$annotatedParameters[$class][$method->name])) {
  260. $definedParameters = [];
  261. foreach ($method->getParameters() as $parameter) {
  262. $definedParameters[$parameter->name] = true;
  263. }
  264. foreach (self::$annotatedParameters[$class][$method->name] as $parameterName => $deprecation) {
  265. if (!isset($definedParameters[$parameterName]) && !($doc && preg_match("/\\n\\s+\\* @param (.*?)(?<= )\\\${$parameterName}\\b/", $doc))) {
  266. $deprecations[] = sprintf($deprecation, $class);
  267. }
  268. }
  269. }
  270. if (!$doc) {
  271. continue;
  272. }
  273. $finalOrInternal = false;
  274. foreach (['final', 'internal'] as $annotation) {
  275. if (false !== \strpos($doc, $annotation) && preg_match('#\n\s+\* @'.$annotation.'(?:( .+?)\.?)?\r?\n\s+\*(?: @|/$)#s', $doc, $notice)) {
  276. $message = isset($notice[1]) ? preg_replace('#\.?\r?\n( \*)? *(?= |\r?\n|$)#', '', $notice[1]) : '';
  277. self::${$annotation.'Methods'}[$class][$method->name] = [$class, $message];
  278. $finalOrInternal = true;
  279. }
  280. }
  281. if ($finalOrInternal || $method->isConstructor() || false === \strpos($doc, '@param') || StatelessInvocation::class === $class) {
  282. continue;
  283. }
  284. if (!preg_match_all('#\n\s+\* @param (.*?)(?<= )\$([a-zA-Z0-9_\x7f-\xff]++)#', $doc, $matches, PREG_SET_ORDER)) {
  285. continue;
  286. }
  287. if (!isset(self::$annotatedParameters[$class][$method->name])) {
  288. $definedParameters = [];
  289. foreach ($method->getParameters() as $parameter) {
  290. $definedParameters[$parameter->name] = true;
  291. }
  292. }
  293. foreach ($matches as list(, $parameterType, $parameterName)) {
  294. if (!isset($definedParameters[$parameterName])) {
  295. $parameterType = trim($parameterType);
  296. 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 parent class "%s", not defining it is deprecated.', $method->name, $parameterType ? $parameterType.' ' : '', $parameterName, $method->class);
  297. }
  298. }
  299. }
  300. return $deprecations;
  301. }
  302. public function checkCase(\ReflectionClass $refl, $file, $class)
  303. {
  304. $real = explode('\\', $class.strrchr($file, '.'));
  305. $tail = explode(\DIRECTORY_SEPARATOR, str_replace('/', \DIRECTORY_SEPARATOR, $file));
  306. $i = \count($tail) - 1;
  307. $j = \count($real) - 1;
  308. while (isset($tail[$i], $real[$j]) && $tail[$i] === $real[$j]) {
  309. --$i;
  310. --$j;
  311. }
  312. array_splice($tail, 0, $i + 1);
  313. if (!$tail) {
  314. return;
  315. }
  316. $tail = \DIRECTORY_SEPARATOR.implode(\DIRECTORY_SEPARATOR, $tail);
  317. $tailLen = \strlen($tail);
  318. $real = $refl->getFileName();
  319. if (2 === self::$caseCheck) {
  320. $real = $this->darwinRealpath($real);
  321. }
  322. if (0 === substr_compare($real, $tail, -$tailLen, $tailLen, true)
  323. && 0 !== substr_compare($real, $tail, -$tailLen, $tailLen, false)
  324. ) {
  325. return [substr($tail, -$tailLen + 1), substr($real, -$tailLen + 1), substr($real, 0, -$tailLen + 1)];
  326. }
  327. }
  328. /**
  329. * `realpath` on MacOSX doesn't normalize the case of characters.
  330. */
  331. private function darwinRealpath($real)
  332. {
  333. $i = 1 + strrpos($real, '/');
  334. $file = substr($real, $i);
  335. $real = substr($real, 0, $i);
  336. if (isset(self::$darwinCache[$real])) {
  337. $kDir = $real;
  338. } else {
  339. $kDir = strtolower($real);
  340. if (isset(self::$darwinCache[$kDir])) {
  341. $real = self::$darwinCache[$kDir][0];
  342. } else {
  343. $dir = getcwd();
  344. chdir($real);
  345. $real = getcwd().'/';
  346. chdir($dir);
  347. $dir = $real;
  348. $k = $kDir;
  349. $i = \strlen($dir) - 1;
  350. while (!isset(self::$darwinCache[$k])) {
  351. self::$darwinCache[$k] = [$dir, []];
  352. self::$darwinCache[$dir] = &self::$darwinCache[$k];
  353. while ('/' !== $dir[--$i]) {
  354. }
  355. $k = substr($k, 0, ++$i);
  356. $dir = substr($dir, 0, $i--);
  357. }
  358. }
  359. }
  360. $dirFiles = self::$darwinCache[$kDir][1];
  361. if (isset($dirFiles[$file])) {
  362. return $real .= $dirFiles[$file];
  363. }
  364. $kFile = strtolower($file);
  365. if (!isset($dirFiles[$kFile])) {
  366. foreach (scandir($real, 2) as $f) {
  367. if ('.' !== $f[0]) {
  368. $dirFiles[$f] = $f;
  369. if ($f === $file) {
  370. $kFile = $k = $file;
  371. } elseif ($f !== $k = strtolower($f)) {
  372. $dirFiles[$k] = $f;
  373. }
  374. }
  375. }
  376. self::$darwinCache[$kDir][1] = $dirFiles;
  377. }
  378. return $real .= $dirFiles[$kFile];
  379. }
  380. /**
  381. * `class_implements` includes interfaces from the parents so we have to manually exclude them.
  382. *
  383. * @param string $class
  384. * @param string|false $parent
  385. *
  386. * @return string[]
  387. */
  388. private function getOwnInterfaces($class, $parent)
  389. {
  390. $ownInterfaces = class_implements($class, false);
  391. if ($parent) {
  392. foreach (class_implements($parent, false) as $interface) {
  393. unset($ownInterfaces[$interface]);
  394. }
  395. }
  396. foreach ($ownInterfaces as $interface) {
  397. foreach (class_implements($interface) as $interface) {
  398. unset($ownInterfaces[$interface]);
  399. }
  400. }
  401. return $ownInterfaces;
  402. }
  403. }