ClassNotFoundErrorEnhancer.php 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  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. if (!preg_match('/^(Class|Interface|Trait) [\'"]([^\'"]+)[\'"] not found$/', $message, $matches)) {
  28. return null;
  29. }
  30. $typeName = strtolower($matches[1]);
  31. $fullyQualifiedClassName = $matches[2];
  32. if (false !== $namespaceSeparatorIndex = strrpos($fullyQualifiedClassName, '\\')) {
  33. $className = substr($fullyQualifiedClassName, $namespaceSeparatorIndex + 1);
  34. $namespacePrefix = substr($fullyQualifiedClassName, 0, $namespaceSeparatorIndex);
  35. $message = sprintf('Attempted to load %s "%s" from namespace "%s".', $typeName, $className, $namespacePrefix);
  36. $tail = ' for another namespace?';
  37. } else {
  38. $className = $fullyQualifiedClassName;
  39. $message = sprintf('Attempted to load %s "%s" from the global namespace.', $typeName, $className);
  40. $tail = '?';
  41. }
  42. if ($candidates = $this->getClassCandidates($className)) {
  43. $tail = array_pop($candidates).'"?';
  44. if ($candidates) {
  45. $tail = ' for e.g. "'.implode('", "', $candidates).'" or "'.$tail;
  46. } else {
  47. $tail = ' for "'.$tail;
  48. }
  49. }
  50. $message .= "\nDid you forget a \"use\" statement".$tail;
  51. return new ClassNotFoundError($message, $error);
  52. }
  53. /**
  54. * Tries to guess the full namespace for a given class name.
  55. *
  56. * By default, it looks for PSR-0 and PSR-4 classes registered via a Symfony or a Composer
  57. * autoloader (that should cover all common cases).
  58. *
  59. * @param string $class A class name (without its namespace)
  60. *
  61. * Returns an array of possible fully qualified class names
  62. */
  63. private function getClassCandidates(string $class): array
  64. {
  65. if (!\is_array($functions = spl_autoload_functions())) {
  66. return [];
  67. }
  68. // find Symfony and Composer autoloaders
  69. $classes = [];
  70. foreach ($functions as $function) {
  71. if (!\is_array($function)) {
  72. continue;
  73. }
  74. // get class loaders wrapped by DebugClassLoader
  75. if ($function[0] instanceof DebugClassLoader) {
  76. $function = $function[0]->getClassLoader();
  77. if (!\is_array($function)) {
  78. continue;
  79. }
  80. }
  81. if ($function[0] instanceof ClassLoader) {
  82. foreach ($function[0]->getPrefixes() as $prefix => $paths) {
  83. foreach ($paths as $path) {
  84. $classes[] = $this->findClassInPath($path, $class, $prefix);
  85. }
  86. }
  87. foreach ($function[0]->getPrefixesPsr4() as $prefix => $paths) {
  88. foreach ($paths as $path) {
  89. $classes[] = $this->findClassInPath($path, $class, $prefix);
  90. }
  91. }
  92. }
  93. }
  94. return array_unique(array_merge([], ...$classes));
  95. }
  96. private function findClassInPath(string $path, string $class, string $prefix): array
  97. {
  98. if (!$path = realpath($path.'/'.strtr($prefix, '\\_', '//')) ?: realpath($path.'/'.\dirname(strtr($prefix, '\\_', '//'))) ?: realpath($path)) {
  99. return [];
  100. }
  101. $classes = [];
  102. $filename = $class.'.php';
  103. foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path, \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::LEAVES_ONLY) as $file) {
  104. if ($filename == $file->getFileName() && $class = $this->convertFileToClass($path, $file->getPathName(), $prefix)) {
  105. $classes[] = $class;
  106. }
  107. }
  108. return $classes;
  109. }
  110. private function convertFileToClass(string $path, string $file, string $prefix): ?string
  111. {
  112. $candidates = [
  113. // namespaced class
  114. $namespacedClass = str_replace([$path.\DIRECTORY_SEPARATOR, '.php', '/'], ['', '', '\\'], $file),
  115. // namespaced class (with target dir)
  116. $prefix.$namespacedClass,
  117. // namespaced class (with target dir and separator)
  118. $prefix.'\\'.$namespacedClass,
  119. // PEAR class
  120. str_replace('\\', '_', $namespacedClass),
  121. // PEAR class (with target dir)
  122. str_replace('\\', '_', $prefix.$namespacedClass),
  123. // PEAR class (with target dir and separator)
  124. str_replace('\\', '_', $prefix.'\\'.$namespacedClass),
  125. ];
  126. if ($prefix) {
  127. $candidates = array_filter($candidates, function ($candidate) use ($prefix) { return 0 === strpos($candidate, $prefix); });
  128. }
  129. // We cannot use the autoloader here as most of them use require; but if the class
  130. // is not found, the new autoloader call will require the file again leading to a
  131. // "cannot redeclare class" error.
  132. foreach ($candidates as $candidate) {
  133. if ($this->classExists($candidate)) {
  134. return $candidate;
  135. }
  136. }
  137. try {
  138. require_once $file;
  139. } catch (\Throwable $e) {
  140. return null;
  141. }
  142. foreach ($candidates as $candidate) {
  143. if ($this->classExists($candidate)) {
  144. return $candidate;
  145. }
  146. }
  147. return null;
  148. }
  149. private function classExists(string $class): bool
  150. {
  151. return class_exists($class, false) || interface_exists($class, false) || trait_exists($class, false);
  152. }
  153. }