ClassNotFoundFatalErrorHandler.php 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  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\FatalErrorHandler;
  11. use Composer\Autoload\ClassLoader as ComposerClassLoader;
  12. use Symfony\Component\ClassLoader\ClassLoader as SymfonyClassLoader;
  13. use Symfony\Component\Debug\DebugClassLoader;
  14. use Symfony\Component\Debug\Exception\ClassNotFoundException;
  15. use Symfony\Component\Debug\Exception\FatalErrorException;
  16. /**
  17. * ErrorHandler for classes that do not exist.
  18. *
  19. * @author Fabien Potencier <fabien@symfony.com>
  20. */
  21. class ClassNotFoundFatalErrorHandler implements FatalErrorHandlerInterface
  22. {
  23. /**
  24. * {@inheritdoc}
  25. */
  26. public function handleError(array $error, FatalErrorException $exception)
  27. {
  28. $messageLen = \strlen($error['message']);
  29. $notFoundSuffix = '\' not found';
  30. $notFoundSuffixLen = \strlen($notFoundSuffix);
  31. if ($notFoundSuffixLen > $messageLen) {
  32. return;
  33. }
  34. if (0 !== substr_compare($error['message'], $notFoundSuffix, -$notFoundSuffixLen)) {
  35. return;
  36. }
  37. foreach (['class', 'interface', 'trait'] as $typeName) {
  38. $prefix = ucfirst($typeName).' \'';
  39. $prefixLen = \strlen($prefix);
  40. if (0 !== strpos($error['message'], $prefix)) {
  41. continue;
  42. }
  43. $fullyQualifiedClassName = substr($error['message'], $prefixLen, -$notFoundSuffixLen);
  44. if (false !== $namespaceSeparatorIndex = strrpos($fullyQualifiedClassName, '\\')) {
  45. $className = substr($fullyQualifiedClassName, $namespaceSeparatorIndex + 1);
  46. $namespacePrefix = substr($fullyQualifiedClassName, 0, $namespaceSeparatorIndex);
  47. $message = sprintf('Attempted to load %s "%s" from namespace "%s".', $typeName, $className, $namespacePrefix);
  48. $tail = ' for another namespace?';
  49. } else {
  50. $className = $fullyQualifiedClassName;
  51. $message = sprintf('Attempted to load %s "%s" from the global namespace.', $typeName, $className);
  52. $tail = '?';
  53. }
  54. if ($candidates = $this->getClassCandidates($className)) {
  55. $tail = array_pop($candidates).'"?';
  56. if ($candidates) {
  57. $tail = ' for e.g. "'.implode('", "', $candidates).'" or "'.$tail;
  58. } else {
  59. $tail = ' for "'.$tail;
  60. }
  61. }
  62. $message .= "\nDid you forget a \"use\" statement".$tail;
  63. return new ClassNotFoundException($message, $exception);
  64. }
  65. }
  66. /**
  67. * Tries to guess the full namespace for a given class name.
  68. *
  69. * By default, it looks for PSR-0 and PSR-4 classes registered via a Symfony or a Composer
  70. * autoloader (that should cover all common cases).
  71. *
  72. * @param string $class A class name (without its namespace)
  73. *
  74. * @return array An array of possible fully qualified class names
  75. */
  76. private function getClassCandidates(string $class): array
  77. {
  78. if (!\is_array($functions = spl_autoload_functions())) {
  79. return [];
  80. }
  81. // find Symfony and Composer autoloaders
  82. $classes = [];
  83. foreach ($functions as $function) {
  84. if (!\is_array($function)) {
  85. continue;
  86. }
  87. // get class loaders wrapped by DebugClassLoader
  88. if ($function[0] instanceof DebugClassLoader) {
  89. $function = $function[0]->getClassLoader();
  90. if (!\is_array($function)) {
  91. continue;
  92. }
  93. }
  94. if ($function[0] instanceof ComposerClassLoader || $function[0] instanceof SymfonyClassLoader) {
  95. foreach ($function[0]->getPrefixes() as $prefix => $paths) {
  96. foreach ($paths as $path) {
  97. $classes = array_merge($classes, $this->findClassInPath($path, $class, $prefix));
  98. }
  99. }
  100. }
  101. if ($function[0] instanceof ComposerClassLoader) {
  102. foreach ($function[0]->getPrefixesPsr4() as $prefix => $paths) {
  103. foreach ($paths as $path) {
  104. $classes = array_merge($classes, $this->findClassInPath($path, $class, $prefix));
  105. }
  106. }
  107. }
  108. }
  109. return array_unique($classes);
  110. }
  111. private function findClassInPath(string $path, string $class, string $prefix): array
  112. {
  113. if (!$path = realpath($path.'/'.strtr($prefix, '\\_', '//')) ?: realpath($path.'/'.\dirname(strtr($prefix, '\\_', '//'))) ?: realpath($path)) {
  114. return [];
  115. }
  116. $classes = [];
  117. $filename = $class.'.php';
  118. foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path, \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::LEAVES_ONLY) as $file) {
  119. if ($filename == $file->getFileName() && $class = $this->convertFileToClass($path, $file->getPathName(), $prefix)) {
  120. $classes[] = $class;
  121. }
  122. }
  123. return $classes;
  124. }
  125. private function convertFileToClass(string $path, string $file, string $prefix): ?string
  126. {
  127. $candidates = [
  128. // namespaced class
  129. $namespacedClass = str_replace([$path.\DIRECTORY_SEPARATOR, '.php', '/'], ['', '', '\\'], $file),
  130. // namespaced class (with target dir)
  131. $prefix.$namespacedClass,
  132. // namespaced class (with target dir and separator)
  133. $prefix.'\\'.$namespacedClass,
  134. // PEAR class
  135. str_replace('\\', '_', $namespacedClass),
  136. // PEAR class (with target dir)
  137. str_replace('\\', '_', $prefix.$namespacedClass),
  138. // PEAR class (with target dir and separator)
  139. str_replace('\\', '_', $prefix.'\\'.$namespacedClass),
  140. ];
  141. if ($prefix) {
  142. $candidates = array_filter($candidates, function ($candidate) use ($prefix) { return 0 === strpos($candidate, $prefix); });
  143. }
  144. // We cannot use the autoloader here as most of them use require; but if the class
  145. // is not found, the new autoloader call will require the file again leading to a
  146. // "cannot redeclare class" error.
  147. foreach ($candidates as $candidate) {
  148. if ($this->classExists($candidate)) {
  149. return $candidate;
  150. }
  151. }
  152. require_once $file;
  153. foreach ($candidates as $candidate) {
  154. if ($this->classExists($candidate)) {
  155. return $candidate;
  156. }
  157. }
  158. return null;
  159. }
  160. private function classExists(string $class): bool
  161. {
  162. return class_exists($class, false) || interface_exists($class, false) || trait_exists($class, false);
  163. }
  164. }