ClassNotFoundErrorEnhancer.php 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  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\ErrorHandler\ErrorEnhancer;
  11. use Composer\Autoload\ClassLoader as ComposerClassLoader;
  12. use Symfony\Component\ClassLoader\ClassLoader as SymfonyClassLoader;
  13. use Symfony\Component\ErrorHandler\DebugClassLoader;
  14. use Symfony\Component\ErrorHandler\Error\ClassNotFoundError;
  15. use Symfony\Component\ErrorHandler\Error\FatalError;
  16. /**
  17. * @author Fabien Potencier <fabien@symfony.com>
  18. */
  19. class ClassNotFoundErrorEnhancer implements ErrorEnhancerInterface
  20. {
  21. /**
  22. * {@inheritdoc}
  23. */
  24. public function enhance(\Throwable $error): ?\Throwable
  25. {
  26. // Some specific versions of PHP produce a fatal error when extending a not found class.
  27. $message = !$error instanceof FatalError ? $error->getMessage() : $error->getError()['message'];
  28. $messageLen = \strlen($message);
  29. $notFoundSuffix = '\' not found';
  30. $notFoundSuffixLen = \strlen($notFoundSuffix);
  31. if ($notFoundSuffixLen > $messageLen) {
  32. return null;
  33. }
  34. if (0 !== substr_compare($message, $notFoundSuffix, -$notFoundSuffixLen)) {
  35. return null;
  36. }
  37. foreach (['class', 'interface', 'trait'] as $typeName) {
  38. $prefix = ucfirst($typeName).' \'';
  39. $prefixLen = \strlen($prefix);
  40. if (0 !== strpos($message, $prefix)) {
  41. continue;
  42. }
  43. $fullyQualifiedClassName = substr($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 ClassNotFoundError($message, $error);
  64. }
  65. return null;
  66. }
  67. /**
  68. * Tries to guess the full namespace for a given class name.
  69. *
  70. * By default, it looks for PSR-0 and PSR-4 classes registered via a Symfony or a Composer
  71. * autoloader (that should cover all common cases).
  72. *
  73. * @param string $class A class name (without its namespace)
  74. *
  75. * Returns an array of possible fully qualified class names
  76. */
  77. private function getClassCandidates(string $class): array
  78. {
  79. if (!\is_array($functions = spl_autoload_functions())) {
  80. return [];
  81. }
  82. // find Symfony and Composer autoloaders
  83. $classes = [];
  84. foreach ($functions as $function) {
  85. if (!\is_array($function)) {
  86. continue;
  87. }
  88. // get class loaders wrapped by DebugClassLoader
  89. if ($function[0] instanceof DebugClassLoader) {
  90. $function = $function[0]->getClassLoader();
  91. if (!\is_array($function)) {
  92. continue;
  93. }
  94. }
  95. if ($function[0] instanceof ComposerClassLoader || $function[0] instanceof SymfonyClassLoader) {
  96. foreach ($function[0]->getPrefixes() as $prefix => $paths) {
  97. foreach ($paths as $path) {
  98. $classes = array_merge($classes, $this->findClassInPath($path, $class, $prefix));
  99. }
  100. }
  101. }
  102. if ($function[0] instanceof ComposerClassLoader) {
  103. foreach ($function[0]->getPrefixesPsr4() as $prefix => $paths) {
  104. foreach ($paths as $path) {
  105. $classes = array_merge($classes, $this->findClassInPath($path, $class, $prefix));
  106. }
  107. }
  108. }
  109. }
  110. return array_unique($classes);
  111. }
  112. private function findClassInPath(string $path, string $class, string $prefix): array
  113. {
  114. if (!$path = realpath($path.'/'.strtr($prefix, '\\_', '//')) ?: realpath($path.'/'.\dirname(strtr($prefix, '\\_', '//'))) ?: realpath($path)) {
  115. return [];
  116. }
  117. $classes = [];
  118. $filename = $class.'.php';
  119. foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path, \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::LEAVES_ONLY) as $file) {
  120. if ($filename == $file->getFileName() && $class = $this->convertFileToClass($path, $file->getPathName(), $prefix)) {
  121. $classes[] = $class;
  122. }
  123. }
  124. return $classes;
  125. }
  126. private function convertFileToClass(string $path, string $file, string $prefix): ?string
  127. {
  128. $candidates = [
  129. // namespaced class
  130. $namespacedClass = str_replace([$path.\DIRECTORY_SEPARATOR, '.php', '/'], ['', '', '\\'], $file),
  131. // namespaced class (with target dir)
  132. $prefix.$namespacedClass,
  133. // namespaced class (with target dir and separator)
  134. $prefix.'\\'.$namespacedClass,
  135. // PEAR class
  136. str_replace('\\', '_', $namespacedClass),
  137. // PEAR class (with target dir)
  138. str_replace('\\', '_', $prefix.$namespacedClass),
  139. // PEAR class (with target dir and separator)
  140. str_replace('\\', '_', $prefix.'\\'.$namespacedClass),
  141. ];
  142. if ($prefix) {
  143. $candidates = array_filter($candidates, function ($candidate) use ($prefix) { return 0 === strpos($candidate, $prefix); });
  144. }
  145. // We cannot use the autoloader here as most of them use require; but if the class
  146. // is not found, the new autoloader call will require the file again leading to a
  147. // "cannot redeclare class" error.
  148. foreach ($candidates as $candidate) {
  149. if ($this->classExists($candidate)) {
  150. return $candidate;
  151. }
  152. }
  153. try {
  154. require_once $file;
  155. } catch (\Throwable $e) {
  156. return null;
  157. }
  158. foreach ($candidates as $candidate) {
  159. if ($this->classExists($candidate)) {
  160. return $candidate;
  161. }
  162. }
  163. return null;
  164. }
  165. private function classExists(string $class): bool
  166. {
  167. return class_exists($class, false) || interface_exists($class, false) || trait_exists($class, false);
  168. }
  169. }