暫無描述

ClassNotFoundErrorEnhancer.php 6.6KB

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