ClassNotFoundErrorEnhancer.php 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  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;
  12. use Symfony\Component\ErrorHandler\DebugClassLoader;
  13. use Symfony\Component\ErrorHandler\Error\ClassNotFoundError;
  14. use Symfony\Component\ErrorHandler\Error\FatalError;
  15. /**
  16. * @author Fabien Potencier <fabien@symfony.com>
  17. */
  18. class ClassNotFoundErrorEnhancer implements ErrorEnhancerInterface
  19. {
  20. /**
  21. * {@inheritdoc}
  22. */
  23. public function enhance(\Throwable $error): ?\Throwable
  24. {
  25. // Some specific versions of PHP produce a fatal error when extending a not found class.
  26. $message = !$error instanceof FatalError ? $error->getMessage() : $error->getError()['message'];
  27. $messageLen = \strlen($message);
  28. $notFoundSuffix = '\' not found';
  29. $notFoundSuffixLen = \strlen($notFoundSuffix);
  30. if ($notFoundSuffixLen > $messageLen) {
  31. return null;
  32. }
  33. if (0 !== substr_compare($message, $notFoundSuffix, -$notFoundSuffixLen)) {
  34. return null;
  35. }
  36. foreach (['class', 'interface', 'trait'] as $typeName) {
  37. $prefix = ucfirst($typeName).' \'';
  38. $prefixLen = \strlen($prefix);
  39. if (0 !== strpos($message, $prefix)) {
  40. continue;
  41. }
  42. $fullyQualifiedClassName = substr($message, $prefixLen, -$notFoundSuffixLen);
  43. if (false !== $namespaceSeparatorIndex = strrpos($fullyQualifiedClassName, '\\')) {
  44. $className = substr($fullyQualifiedClassName, $namespaceSeparatorIndex + 1);
  45. $namespacePrefix = substr($fullyQualifiedClassName, 0, $namespaceSeparatorIndex);
  46. $message = sprintf('Attempted to load %s "%s" from namespace "%s".', $typeName, $className, $namespacePrefix);
  47. $tail = ' for another namespace?';
  48. } else {
  49. $className = $fullyQualifiedClassName;
  50. $message = sprintf('Attempted to load %s "%s" from the global namespace.', $typeName, $className);
  51. $tail = '?';
  52. }
  53. if ($candidates = $this->getClassCandidates($className)) {
  54. $tail = array_pop($candidates).'"?';
  55. if ($candidates) {
  56. $tail = ' for e.g. "'.implode('", "', $candidates).'" or "'.$tail;
  57. } else {
  58. $tail = ' for "'.$tail;
  59. }
  60. }
  61. $message .= "\nDid you forget a \"use\" statement".$tail;
  62. return new ClassNotFoundError($message, $error);
  63. }
  64. return null;
  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. * Returns 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 ClassLoader) {
  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. foreach ($function[0]->getPrefixesPsr4() as $prefix => $paths) {
  101. foreach ($paths as $path) {
  102. $classes = array_merge($classes, $this->findClassInPath($path, $class, $prefix));
  103. }
  104. }
  105. }
  106. }
  107. return array_unique($classes);
  108. }
  109. private function findClassInPath(string $path, string $class, string $prefix): array
  110. {
  111. if (!$path = realpath($path.'/'.strtr($prefix, '\\_', '//')) ?: realpath($path.'/'.\dirname(strtr($prefix, '\\_', '//'))) ?: realpath($path)) {
  112. return [];
  113. }
  114. $classes = [];
  115. $filename = $class.'.php';
  116. foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path, \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::LEAVES_ONLY) as $file) {
  117. if ($filename == $file->getFileName() && $class = $this->convertFileToClass($path, $file->getPathName(), $prefix)) {
  118. $classes[] = $class;
  119. }
  120. }
  121. return $classes;
  122. }
  123. private function convertFileToClass(string $path, string $file, string $prefix): ?string
  124. {
  125. $candidates = [
  126. // namespaced class
  127. $namespacedClass = str_replace([$path.\DIRECTORY_SEPARATOR, '.php', '/'], ['', '', '\\'], $file),
  128. // namespaced class (with target dir)
  129. $prefix.$namespacedClass,
  130. // namespaced class (with target dir and separator)
  131. $prefix.'\\'.$namespacedClass,
  132. // PEAR class
  133. str_replace('\\', '_', $namespacedClass),
  134. // PEAR class (with target dir)
  135. str_replace('\\', '_', $prefix.$namespacedClass),
  136. // PEAR class (with target dir and separator)
  137. str_replace('\\', '_', $prefix.'\\'.$namespacedClass),
  138. ];
  139. if ($prefix) {
  140. $candidates = array_filter($candidates, function ($candidate) use ($prefix) { return 0 === strpos($candidate, $prefix); });
  141. }
  142. // We cannot use the autoloader here as most of them use require; but if the class
  143. // is not found, the new autoloader call will require the file again leading to a
  144. // "cannot redeclare class" error.
  145. foreach ($candidates as $candidate) {
  146. if ($this->classExists($candidate)) {
  147. return $candidate;
  148. }
  149. }
  150. try {
  151. require_once $file;
  152. } catch (\Throwable $e) {
  153. return null;
  154. }
  155. foreach ($candidates as $candidate) {
  156. if ($this->classExists($candidate)) {
  157. return $candidate;
  158. }
  159. }
  160. return null;
  161. }
  162. private function classExists(string $class): bool
  163. {
  164. return class_exists($class, false) || interface_exists($class, false) || trait_exists($class, false);
  165. }
  166. }