DebugClassLoader.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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 static $caseCheck;
  27. private static $final = array();
  28. private static $finalMethods = array();
  29. private static $deprecated = array();
  30. private static $php7Reserved = array('int', 'float', 'bool', 'string', 'true', 'false', 'null');
  31. private static $darwinCache = array('/' => array('/', array()));
  32. /**
  33. * Constructor.
  34. *
  35. * @param callable $classLoader A class loader
  36. */
  37. public function __construct(callable $classLoader)
  38. {
  39. $this->classLoader = $classLoader;
  40. $this->isFinder = is_array($classLoader) && method_exists($classLoader[0], 'findFile');
  41. if (!isset(self::$caseCheck)) {
  42. $file = file_exists(__FILE__) ? __FILE__ : rtrim(realpath('.'), DIRECTORY_SEPARATOR);
  43. $i = strrpos($file, DIRECTORY_SEPARATOR);
  44. $dir = substr($file, 0, 1 + $i);
  45. $file = substr($file, 1 + $i);
  46. $test = strtoupper($file) === $file ? strtolower($file) : strtoupper($file);
  47. $test = realpath($dir.$test);
  48. if (false === $test || false === $i) {
  49. // filesystem is case sensitive
  50. self::$caseCheck = 0;
  51. } elseif (substr($test, -strlen($file)) === $file) {
  52. // filesystem is case insensitive and realpath() normalizes the case of characters
  53. self::$caseCheck = 1;
  54. } elseif (false !== stripos(PHP_OS, 'darwin')) {
  55. // on MacOSX, HFS+ is case insensitive but realpath() doesn't normalize the case of characters
  56. self::$caseCheck = 2;
  57. } else {
  58. // filesystem case checks failed, fallback to disabling them
  59. self::$caseCheck = 0;
  60. }
  61. }
  62. }
  63. /**
  64. * Gets the wrapped class loader.
  65. *
  66. * @return callable The wrapped class loader
  67. */
  68. public function getClassLoader()
  69. {
  70. return $this->classLoader;
  71. }
  72. /**
  73. * Wraps all autoloaders.
  74. */
  75. public static function enable()
  76. {
  77. // Ensures we don't hit https://bugs.php.net/42098
  78. class_exists('Symfony\Component\Debug\ErrorHandler');
  79. class_exists('Psr\Log\LogLevel');
  80. if (!is_array($functions = spl_autoload_functions())) {
  81. return;
  82. }
  83. foreach ($functions as $function) {
  84. spl_autoload_unregister($function);
  85. }
  86. foreach ($functions as $function) {
  87. if (!is_array($function) || !$function[0] instanceof self) {
  88. $function = array(new static($function), 'loadClass');
  89. }
  90. spl_autoload_register($function);
  91. }
  92. }
  93. /**
  94. * Disables the wrapping.
  95. */
  96. public static function disable()
  97. {
  98. if (!is_array($functions = spl_autoload_functions())) {
  99. return;
  100. }
  101. foreach ($functions as $function) {
  102. spl_autoload_unregister($function);
  103. }
  104. foreach ($functions as $function) {
  105. if (is_array($function) && $function[0] instanceof self) {
  106. $function = $function[0]->getClassLoader();
  107. }
  108. spl_autoload_register($function);
  109. }
  110. }
  111. /**
  112. * Loads the given class or interface.
  113. *
  114. * @param string $class The name of the class
  115. *
  116. * @return bool|null True, if loaded
  117. *
  118. * @throws \RuntimeException
  119. */
  120. public function loadClass($class)
  121. {
  122. ErrorHandler::stackErrors();
  123. try {
  124. if ($this->isFinder) {
  125. if ($file = $this->classLoader[0]->findFile($class)) {
  126. require_once $file;
  127. }
  128. } else {
  129. call_user_func($this->classLoader, $class);
  130. $file = false;
  131. }
  132. } finally {
  133. ErrorHandler::unstackErrors();
  134. }
  135. $exists = class_exists($class, false) || interface_exists($class, false) || trait_exists($class, false);
  136. if ($class && '\\' === $class[0]) {
  137. $class = substr($class, 1);
  138. }
  139. if ($exists) {
  140. $refl = new \ReflectionClass($class);
  141. $name = $refl->getName();
  142. if ($name !== $class && 0 === strcasecmp($name, $class)) {
  143. throw new \RuntimeException(sprintf('Case mismatch between loaded and declared class names: "%s" vs "%s".', $class, $name));
  144. }
  145. $parent = get_parent_class($class);
  146. // Not an interface nor a trait
  147. if (class_exists($name, false)) {
  148. if (preg_match('#\n \* @final(?:( .+?)\.?)?\r?\n \*(?: @|/$)#s', $refl->getDocComment(), $notice)) {
  149. self::$final[$name] = isset($notice[1]) ? preg_replace('#\s*\r?\n \* +#', ' ', $notice[1]) : '';
  150. }
  151. if ($parent && isset(self::$final[$parent])) {
  152. @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);
  153. }
  154. // Inherit @final annotations
  155. self::$finalMethods[$name] = $parent && isset(self::$finalMethods[$parent]) ? self::$finalMethods[$parent] : array();
  156. foreach ($refl->getMethods(\ReflectionMethod::IS_PUBLIC | \ReflectionMethod::IS_PROTECTED) as $method) {
  157. if ($method->class !== $name) {
  158. continue;
  159. }
  160. if ($parent && isset(self::$finalMethods[$parent][$method->name])) {
  161. @trigger_error(sprintf('%s It may change without further notice as of its next major version. You should not extend it from "%s".', self::$finalMethods[$parent][$method->name], $name), E_USER_DEPRECATED);
  162. }
  163. $doc = $method->getDocComment();
  164. if (false === $doc || false === strpos($doc, '@final')) {
  165. continue;
  166. }
  167. if (preg_match('#\n\s+\* @final(?:( .+?)\.?)?\r?\n\s+\*(?: @|/$)#s', $doc, $notice)) {
  168. $message = isset($notice[1]) ? preg_replace('#\s*\r?\n \* +#', ' ', $notice[1]) : '';
  169. self::$finalMethods[$name][$method->name] = sprintf('The "%s::%s()" method is considered final%s.', $name, $method->name, $message);
  170. }
  171. }
  172. }
  173. if (in_array(strtolower($refl->getShortName()), self::$php7Reserved)) {
  174. @trigger_error(sprintf('The "%s" class uses the reserved name "%s", it will break on PHP 7 and higher', $name, $refl->getShortName()), E_USER_DEPRECATED);
  175. } elseif (preg_match('#\n \* @deprecated (.*?)\r?\n \*(?: @|/$)#s', $refl->getDocComment(), $notice)) {
  176. self::$deprecated[$name] = preg_replace('#\s*\r?\n \* +#', ' ', $notice[1]);
  177. } else {
  178. // Don't trigger deprecations for classes in the same vendor
  179. if (2 > $len = 1 + (strpos($name, '\\', 1 + strpos($name, '\\')) ?: strpos($name, '_'))) {
  180. $len = 0;
  181. $ns = '';
  182. } else {
  183. switch ($ns = substr($name, 0, $len)) {
  184. case 'Symfony\Bridge\\':
  185. case 'Symfony\Bundle\\':
  186. case 'Symfony\Component\\':
  187. $ns = 'Symfony\\';
  188. $len = strlen($ns);
  189. break;
  190. }
  191. }
  192. if (!$parent || strncmp($ns, $parent, $len)) {
  193. if ($parent && isset(self::$deprecated[$parent]) && strncmp($ns, $parent, $len)) {
  194. @trigger_error(sprintf('The "%s" class extends "%s" that is deprecated %s', $name, $parent, self::$deprecated[$parent]), E_USER_DEPRECATED);
  195. }
  196. $parentInterfaces = array();
  197. $deprecatedInterfaces = array();
  198. if ($parent) {
  199. foreach (class_implements($parent) as $interface) {
  200. $parentInterfaces[$interface] = 1;
  201. }
  202. }
  203. foreach ($refl->getInterfaceNames() as $interface) {
  204. if (isset(self::$deprecated[$interface]) && strncmp($ns, $interface, $len)) {
  205. $deprecatedInterfaces[] = $interface;
  206. }
  207. foreach (class_implements($interface) as $interface) {
  208. $parentInterfaces[$interface] = 1;
  209. }
  210. }
  211. foreach ($deprecatedInterfaces as $interface) {
  212. if (!isset($parentInterfaces[$interface])) {
  213. @trigger_error(sprintf('The "%s" %s "%s" that is deprecated %s', $name, $refl->isInterface() ? 'interface extends' : 'class implements', $interface, self::$deprecated[$interface]), E_USER_DEPRECATED);
  214. }
  215. }
  216. }
  217. }
  218. }
  219. if ($file) {
  220. if (!$exists) {
  221. if (false !== strpos($class, '/')) {
  222. 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));
  223. }
  224. 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));
  225. }
  226. if (self::$caseCheck) {
  227. $real = explode('\\', $class.strrchr($file, '.'));
  228. $tail = explode(DIRECTORY_SEPARATOR, str_replace('/', DIRECTORY_SEPARATOR, $file));
  229. $i = count($tail) - 1;
  230. $j = count($real) - 1;
  231. while (isset($tail[$i], $real[$j]) && $tail[$i] === $real[$j]) {
  232. --$i;
  233. --$j;
  234. }
  235. array_splice($tail, 0, $i + 1);
  236. }
  237. if (self::$caseCheck && $tail) {
  238. $tail = DIRECTORY_SEPARATOR.implode(DIRECTORY_SEPARATOR, $tail);
  239. $tailLen = strlen($tail);
  240. $real = $refl->getFileName();
  241. if (2 === self::$caseCheck) {
  242. // realpath() on MacOSX doesn't normalize the case of characters
  243. $i = 1 + strrpos($real, '/');
  244. $file = substr($real, $i);
  245. $real = substr($real, 0, $i);
  246. if (isset(self::$darwinCache[$real])) {
  247. $kDir = $real;
  248. } else {
  249. $kDir = strtolower($real);
  250. if (isset(self::$darwinCache[$kDir])) {
  251. $real = self::$darwinCache[$kDir][0];
  252. } else {
  253. $dir = getcwd();
  254. chdir($real);
  255. $real = getcwd().'/';
  256. chdir($dir);
  257. $dir = $real;
  258. $k = $kDir;
  259. $i = strlen($dir) - 1;
  260. while (!isset(self::$darwinCache[$k])) {
  261. self::$darwinCache[$k] = array($dir, array());
  262. self::$darwinCache[$dir] = &self::$darwinCache[$k];
  263. while ('/' !== $dir[--$i]) {
  264. }
  265. $k = substr($k, 0, ++$i);
  266. $dir = substr($dir, 0, $i--);
  267. }
  268. }
  269. }
  270. $dirFiles = self::$darwinCache[$kDir][1];
  271. if (isset($dirFiles[$file])) {
  272. $kFile = $file;
  273. } else {
  274. $kFile = strtolower($file);
  275. if (!isset($dirFiles[$kFile])) {
  276. foreach (scandir($real, 2) as $f) {
  277. if ('.' !== $f[0]) {
  278. $dirFiles[$f] = $f;
  279. if ($f === $file) {
  280. $kFile = $k = $file;
  281. } elseif ($f !== $k = strtolower($f)) {
  282. $dirFiles[$k] = $f;
  283. }
  284. }
  285. }
  286. self::$darwinCache[$kDir][1] = $dirFiles;
  287. }
  288. }
  289. $real .= $dirFiles[$kFile];
  290. }
  291. if (0 === substr_compare($real, $tail, -$tailLen, $tailLen, true)
  292. && 0 !== substr_compare($real, $tail, -$tailLen, $tailLen, false)
  293. ) {
  294. 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)));
  295. }
  296. }
  297. return true;
  298. }
  299. }
  300. }