DebugClassLoader.php 16KB

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