DebugClassLoader.php 16 KB

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