ClassNotFoundFatalErrorHandler.php 7.4 KB

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