4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Debug;
15 * Autoloader checking if the class is really defined in the file found.
17 * The ClassLoader will wrap all registered autoloaders
18 * and will throw an exception if a file is found but does
19 * not declare the class.
21 * @author Fabien Potencier <fabien@symfony.com>
22 * @author Christophe Coevoet <stof@notk.org>
23 * @author Nicolas Grekas <p@tchwork.com>
25 class DebugClassLoader
29 private $loaded = array();
30 private static $caseCheck;
31 private static $checkedClasses = array();
32 private static $final = array();
33 private static $finalMethods = array();
34 private static $deprecated = array();
35 private static $internal = array();
36 private static $internalMethods = array();
37 private static $php7Reserved = array('int' => 1, 'float' => 1, 'bool' => 1, 'string' => 1, 'true' => 1, 'false' => 1, 'null' => 1);
38 private static $darwinCache = array('/' => array('/', array()));
40 public function __construct(callable $classLoader)
42 $this->classLoader = $classLoader;
43 $this->isFinder = is_array($classLoader) && method_exists($classLoader[0], 'findFile');
45 if (!isset(self::$caseCheck)) {
46 $file = file_exists(__FILE__) ? __FILE__ : rtrim(realpath('.'), DIRECTORY_SEPARATOR);
47 $i = strrpos($file, DIRECTORY_SEPARATOR);
48 $dir = substr($file, 0, 1 + $i);
49 $file = substr($file, 1 + $i);
50 $test = strtoupper($file) === $file ? strtolower($file) : strtoupper($file);
51 $test = realpath($dir.$test);
53 if (false === $test || false === $i) {
54 // filesystem is case sensitive
56 } elseif (substr($test, -strlen($file)) === $file) {
57 // filesystem is case insensitive and realpath() normalizes the case of characters
59 } elseif (false !== stripos(PHP_OS, 'darwin')) {
60 // on MacOSX, HFS+ is case insensitive but realpath() doesn't normalize the case of characters
63 // filesystem case checks failed, fallback to disabling them
70 * Gets the wrapped class loader.
72 * @return callable The wrapped class loader
74 public function getClassLoader()
76 return $this->classLoader;
80 * Wraps all autoloaders.
82 public static function enable()
84 // Ensures we don't hit https://bugs.php.net/42098
85 class_exists('Symfony\Component\Debug\ErrorHandler');
86 class_exists('Psr\Log\LogLevel');
88 if (!is_array($functions = spl_autoload_functions())) {
92 foreach ($functions as $function) {
93 spl_autoload_unregister($function);
96 foreach ($functions as $function) {
97 if (!is_array($function) || !$function[0] instanceof self) {
98 $function = array(new static($function), 'loadClass');
101 spl_autoload_register($function);
106 * Disables the wrapping.
108 public static function disable()
110 if (!is_array($functions = spl_autoload_functions())) {
114 foreach ($functions as $function) {
115 spl_autoload_unregister($function);
118 foreach ($functions as $function) {
119 if (is_array($function) && $function[0] instanceof self) {
120 $function = $function[0]->getClassLoader();
123 spl_autoload_register($function);
128 * Loads the given class or interface.
130 * @param string $class The name of the class
132 * @return bool|null True, if loaded
134 * @throws \RuntimeException
136 public function loadClass($class)
138 $e = error_reporting(error_reporting() | E_PARSE | E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR);
141 if ($this->isFinder && !isset($this->loaded[$class])) {
142 $this->loaded[$class] = true;
143 if ($file = $this->classLoader[0]->findFile($class) ?: false) {
144 $wasCached = \function_exists('opcache_is_script_cached') && @opcache_is_script_cached($file);
153 call_user_func($this->classLoader, $class);
160 $this->checkClass($class, $file);
163 private function checkClass($class, $file = null)
165 $exists = null === $file || \class_exists($class, false) || \interface_exists($class, false) || \trait_exists($class, false);
167 if (null !== $file && $class && '\\' === $class[0]) {
168 $class = substr($class, 1);
172 if (isset(self::$checkedClasses[$class])) {
175 self::$checkedClasses[$class] = true;
177 $refl = new \ReflectionClass($class);
178 if (null === $file && $refl->isInternal()) {
181 $name = $refl->getName();
183 if ($name !== $class && 0 === \strcasecmp($name, $class)) {
184 throw new \RuntimeException(sprintf('Case mismatch between loaded and declared class names: "%s" vs "%s".', $class, $name));
187 // Don't trigger deprecations for classes in the same vendor
188 if (2 > $len = 1 + (\strpos($name, '\\') ?: \strpos($name, '_'))) {
192 $ns = \substr($name, 0, $len);
195 // Detect annotations on the class
196 if (false !== $doc = $refl->getDocComment()) {
197 foreach (array('final', 'deprecated', 'internal') as $annotation) {
198 if (false !== \strpos($doc, $annotation) && preg_match('#\n \* @'.$annotation.'(?:( .+?)\.?)?\r?\n \*(?: @|/$)#s', $doc, $notice)) {
199 self::${$annotation}[$name] = isset($notice[1]) ? preg_replace('#\s*\r?\n \* +#', ' ', $notice[1]) : '';
204 $parentAndTraits = \class_uses($name, false);
205 if ($parent = \get_parent_class($class)) {
206 $parentAndTraits[] = $parent;
208 if (!isset(self::$checkedClasses[$parent])) {
209 $this->checkClass($parent);
212 if (isset(self::$final[$parent])) {
213 @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);
217 // Detect if the parent is annotated
218 foreach ($parentAndTraits + $this->getOwnInterfaces($name, $parent) as $use) {
219 if (!isset(self::$checkedClasses[$use])) {
220 $this->checkClass($use);
222 if (isset(self::$deprecated[$use]) && \strncmp($ns, $use, $len)) {
223 $type = class_exists($name, false) ? 'class' : (interface_exists($name, false) ? 'interface' : 'trait');
224 $verb = class_exists($use, false) || interface_exists($name, false) ? 'extends' : (interface_exists($use, false) ? 'implements' : 'uses');
226 @trigger_error(sprintf('The "%s" %s %s "%s" that is deprecated%s.', $name, $type, $verb, $use, self::$deprecated[$use]), E_USER_DEPRECATED);
228 if (isset(self::$internal[$use]) && \strncmp($ns, $use, $len)) {
229 @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);
233 // Inherit @final and @internal annotations for methods
234 self::$finalMethods[$name] = array();
235 self::$internalMethods[$name] = array();
236 foreach ($parentAndTraits as $use) {
237 foreach (array('finalMethods', 'internalMethods') as $property) {
238 if (isset(self::${$property}[$use])) {
239 self::${$property}[$name] = self::${$property}[$name] ? self::${$property}[$use] + self::${$property}[$name] : self::${$property}[$use];
244 $isClass = \class_exists($name, false);
245 foreach ($refl->getMethods(\ReflectionMethod::IS_PUBLIC | \ReflectionMethod::IS_PROTECTED) as $method) {
246 if ($method->class !== $name) {
250 // Method from a trait
251 if ($method->getFilename() !== $refl->getFileName()) {
255 if ($isClass && $parent && isset(self::$finalMethods[$parent][$method->name])) {
256 list($declaringClass, $message) = self::$finalMethods[$parent][$method->name];
257 @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);
260 foreach ($parentAndTraits as $use) {
261 if (isset(self::$internalMethods[$use][$method->name])) {
262 list($declaringClass, $message) = self::$internalMethods[$use][$method->name];
263 if (\strncmp($ns, $declaringClass, $len)) {
264 @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);
269 // Detect method annotations
270 if (false === $doc = $method->getDocComment()) {
274 foreach (array('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('#\s*\r?\n \* +#', ' ', $notice[1]) : '';
277 self::${$annotation.'Methods'}[$name][$method->name] = array($name, $message);
282 if (isset(self::$php7Reserved[\strtolower($refl->getShortName())])) {
283 @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);
289 if (false !== strpos($class, '/')) {
290 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));
293 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));
295 if (self::$caseCheck) {
296 $real = explode('\\', $class.strrchr($file, '.'));
297 $tail = explode(DIRECTORY_SEPARATOR, str_replace('/', DIRECTORY_SEPARATOR, $file));
299 $i = count($tail) - 1;
300 $j = count($real) - 1;
302 while (isset($tail[$i], $real[$j]) && $tail[$i] === $real[$j]) {
307 array_splice($tail, 0, $i + 1);
309 if (self::$caseCheck && $tail) {
310 $tail = DIRECTORY_SEPARATOR.implode(DIRECTORY_SEPARATOR, $tail);
311 $tailLen = strlen($tail);
312 $real = $refl->getFileName();
314 if (2 === self::$caseCheck) {
315 // realpath() on MacOSX doesn't normalize the case of characters
317 $i = 1 + strrpos($real, '/');
318 $file = substr($real, $i);
319 $real = substr($real, 0, $i);
321 if (isset(self::$darwinCache[$real])) {
324 $kDir = strtolower($real);
326 if (isset(self::$darwinCache[$kDir])) {
327 $real = self::$darwinCache[$kDir][0];
331 $real = getcwd().'/';
336 $i = strlen($dir) - 1;
337 while (!isset(self::$darwinCache[$k])) {
338 self::$darwinCache[$k] = array($dir, array());
339 self::$darwinCache[$dir] = &self::$darwinCache[$k];
341 while ('/' !== $dir[--$i]) {
343 $k = substr($k, 0, ++$i);
344 $dir = substr($dir, 0, $i--);
349 $dirFiles = self::$darwinCache[$kDir][1];
351 if (isset($dirFiles[$file])) {
354 $kFile = strtolower($file);
356 if (!isset($dirFiles[$kFile])) {
357 foreach (scandir($real, 2) as $f) {
362 } elseif ($f !== $k = strtolower($f)) {
367 self::$darwinCache[$kDir][1] = $dirFiles;
371 $real .= $dirFiles[$kFile];
374 if (0 === substr_compare($real, $tail, -$tailLen, $tailLen, true)
375 && 0 !== substr_compare($real, $tail, -$tailLen, $tailLen, false)
377 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)));
384 * `class_implements` includes interfaces from the parents so we have to manually exclude them.
386 * @param string $class
387 * @param string|false $parent
391 private function getOwnInterfaces($class, $parent)
393 $ownInterfaces = class_implements($class, false);
396 foreach (class_implements($parent, false) as $interface) {
397 unset($ownInterfaces[$interface]);
401 foreach ($ownInterfaces as $interface) {
402 foreach (class_implements($interface) as $interface) {
403 unset($ownInterfaces[$interface]);
407 return $ownInterfaces;