ClassNotFoundFatalErrorHandler.php 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  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 Symfony\Component\Debug\Exception\ClassNotFoundException;
  12. use Symfony\Component\Debug\Exception\FatalErrorException;
  13. use Symfony\Component\Debug\DebugClassLoader;
  14. use Composer\Autoload\ClassLoader as ComposerClassLoader;
  15. use Symfony\Component\ClassLoader\ClassLoader as SymfonyClassLoader;
  16. /**
  17. * ErrorHandler for classes that do not exist.
  18. *
  19. * @author Fabien Potencier <fabien@symfony.com>
  20. */
  21. class ClassNotFoundFatalErrorHandler implements FatalErrorHandlerInterface
  22. {
  23. /**
  24. * {@inheritdoc}
  25. */
  26. public function handleError(array $error, FatalErrorException $exception)
  27. {
  28. $messageLen = strlen($error['message']);
  29. $notFoundSuffix = '\' not found';
  30. $notFoundSuffixLen = strlen($notFoundSuffix);
  31. if ($notFoundSuffixLen > $messageLen) {
  32. return;
  33. }
  34. if (0 !== substr_compare($error['message'], $notFoundSuffix, -$notFoundSuffixLen)) {
  35. return;
  36. }
  37. foreach (array('class', 'interface', 'trait') as $typeName) {
  38. $prefix = ucfirst($typeName).' \'';
  39. $prefixLen = strlen($prefix);
  40. if (0 !== strpos($error['message'], $prefix)) {
  41. continue;
  42. }
  43. $fullyQualifiedClassName = substr($error['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 ClassNotFoundException($message, $exception);
  64. }
  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. * @return array An array of possible fully qualified class names
  75. */
  76. private function getClassCandidates($class)
  77. {
  78. if (!is_array($functions = spl_autoload_functions())) {
  79. return array();
  80. }
  81. // find Symfony and Composer autoloaders
  82. $classes = array();
  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 ComposerClassLoader || $function[0] instanceof SymfonyClassLoader) {
  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. }
  101. if ($function[0] instanceof ComposerClassLoader) {
  102. foreach ($function[0]->getPrefixesPsr4() as $prefix => $paths) {
  103. foreach ($paths as $path) {
  104. $classes = array_merge($classes, $this->findClassInPath($path, $class, $prefix));
  105. }
  106. }
  107. }
  108. }
  109. return array_unique($classes);
  110. }
  111. /**
  112. * @param string $path
  113. * @param string $class
  114. * @param string $prefix
  115. *
  116. * @return array
  117. */
  118. private function findClassInPath($path, $class, $prefix)
  119. {
  120. if (!$path = realpath($path.'/'.strtr($prefix, '\\_', '//')) ?: realpath($path.'/'.dirname(strtr($prefix, '\\_', '//'))) ?: realpath($path)) {
  121. return array();
  122. }
  123. $classes = array();
  124. $filename = $class.'.php';
  125. foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path, \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::LEAVES_ONLY) as $file) {
  126. if ($filename == $file->getFileName() && $class = $this->convertFileToClass($path, $file->getPathName(), $prefix)) {
  127. $classes[] = $class;
  128. }
  129. }
  130. return $classes;
  131. }
  132. /**
  133. * @param string $path
  134. * @param string $file
  135. * @param string $prefix
  136. *
  137. * @return string|null
  138. */
  139. private function convertFileToClass($path, $file, $prefix)
  140. {
  141. $candidates = array(
  142. // namespaced class
  143. $namespacedClass = str_replace(array($path.DIRECTORY_SEPARATOR, '.php', '/'), array('', '', '\\'), $file),
  144. // namespaced class (with target dir)
  145. $prefix.$namespacedClass,
  146. // namespaced class (with target dir and separator)
  147. $prefix.'\\'.$namespacedClass,
  148. // PEAR class
  149. str_replace('\\', '_', $namespacedClass),
  150. // PEAR class (with target dir)
  151. str_replace('\\', '_', $prefix.$namespacedClass),
  152. // PEAR class (with target dir and separator)
  153. str_replace('\\', '_', $prefix.'\\'.$namespacedClass),
  154. );
  155. if ($prefix) {
  156. $candidates = array_filter($candidates, function ($candidate) use ($prefix) {return 0 === strpos($candidate, $prefix);});
  157. }
  158. // We cannot use the autoloader here as most of them use require; but if the class
  159. // is not found, the new autoloader call will require the file again leading to a
  160. // "cannot redeclare class" error.
  161. foreach ($candidates as $candidate) {
  162. if ($this->classExists($candidate)) {
  163. return $candidate;
  164. }
  165. }
  166. require_once $file;
  167. foreach ($candidates as $candidate) {
  168. if ($this->classExists($candidate)) {
  169. return $candidate;
  170. }
  171. }
  172. }
  173. /**
  174. * @param string $class
  175. *
  176. * @return bool
  177. */
  178. private function classExists($class)
  179. {
  180. return class_exists($class, false) || interface_exists($class, false) || trait_exists($class, false);
  181. }
  182. }