Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[Debug] Developer friendly Class Not Found and Undefined Function errors #8553

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Jul 29, 2013
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions src/Symfony/Component/ClassLoader/DebugClassLoader.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,16 @@ public function __construct($classFinder)
$this->classFinder = $classFinder;
}

/**
* Gets the wrapped class loader.
*
* @return object a class loader instance
*/
public function getClassLoader()
{
return $this->classFinder;
}

/**
* Replaces all autoloaders implementing a findFile method by a DebugClassLoader wrapper.
*/
Expand Down
5 changes: 5 additions & 0 deletions src/Symfony/Component/Debug/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
CHANGELOG
=========

2.4.0
-----

* improved error messages for not found classes and functions

2.3.0
-----

Expand Down
60 changes: 53 additions & 7 deletions src/Symfony/Component/Debug/ErrorHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,12 @@

namespace Symfony\Component\Debug;

use Symfony\Component\Debug\Exception\FatalErrorException;
use Symfony\Component\Debug\Exception\ContextErrorException;
use Psr\Log\LoggerInterface;
use Symfony\Component\Debug\Exception\ContextErrorException;
use Symfony\Component\Debug\Exception\FatalErrorException;
use Symfony\Component\Debug\FatalErrorHandler\UndefinedFunctionFatalErrorHandler;
use Symfony\Component\Debug\FatalErrorHandler\ClassNotFoundFatalErrorHandler;
use Symfony\Component\Debug\FatalErrorHandler\FatalErrorHandlerInterface;

/**
* ErrorHandler.
Expand Down Expand Up @@ -55,7 +58,7 @@ class ErrorHandler
/**
* Registers the error handler.
*
* @param integer $level The level at which the conversion to Exception is done (null to use the error_reporting() value and 0 to disable)
* @param integer $level The level at which the conversion to Exception is done (null to use the error_reporting() value and 0 to disable)
* @param Boolean $displayErrors Display errors (for dev environment) or just log they (production usage)
*
* @return The registered error handler
Expand All @@ -74,16 +77,32 @@ public static function register($level = null, $displayErrors = true)
return $handler;
}

/**
* Sets the level at which the conversion to Exception is done.
*
* @param integer|null $level The level (null to use the error_reporting() value and 0 to disable)
*/
public function setLevel($level)
{
$this->level = null === $level ? error_reporting() : $level;
}

/**
* Sets the display_errors flag value.
*
* @param integer $displayErrors The display_errors flag value
*/
public function setDisplayErrors($displayErrors)
{
$this->displayErrors = $displayErrors;
}

/**
* Sets a logger for the given channel.
*
* @param LoggerInterface $logger A logger interface
* @param string $channel The channel associated with the logger (deprecation or emergency)
*/
public static function setLogger(LoggerInterface $logger, $channel = 'deprecation')
{
self::$loggers[$channel] = $logger;
Expand Down Expand Up @@ -157,10 +176,37 @@ public function handleFatal()
restore_exception_handler();

if (is_array($exceptionHandler) && $exceptionHandler[0] instanceof ExceptionHandler) {
$level = isset($this->levels[$type]) ? $this->levels[$type] : $type;
$message = sprintf('%s: %s in %s line %d', $level, $error['message'], $error['file'], $error['line']);
$exception = new FatalErrorException($message, 0, $type, $error['file'], $error['line']);
$exceptionHandler[0]->handle($exception);
$this->handleFatalError($exceptionHandler[0], $error);
}
}

/**
* Gets the fatal error handlers.
*
* Override this method if you want to define more fatal error handlers.
*
* @return FatalErrorHandlerInterface[] An array of FatalErrorHandlerInterface
*/
protected function getFatalErrorHandlers()
{
return array(
new UndefinedFunctionFatalErrorHandler(),
new ClassNotFoundFatalErrorHandler(),
);
}

private function handleFatalError(ExceptionHandler $exceptionHandler, array $error)
{
$level = isset($this->levels[$error['type']]) ? $this->levels[$error['type']] : $error['type'];
$message = sprintf('%s: %s in %s line %d', $level, $error['message'], $error['file'], $error['line']);
$exception = new FatalErrorException($message, 0, $error['type'], $error['file'], $error['line']);

foreach ($this->getFatalErrorHandlers() as $handler) {
if ($ex = $handler->handleError($error, $exception)) {
return $exceptionHandler->handle($ex);
}
}

$exceptionHandler->handle($exception);
}
}
32 changes: 32 additions & 0 deletions src/Symfony/Component/Debug/Exception/ClassNotFoundException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Debug\Exception;

/**
* Class (or Trait or Interface) Not Found Exception.
*
* @author Konstanton Myakshin <[email protected]>
*/
class ClassNotFoundException extends FatalErrorException
{
public function __construct($message, \ErrorException $previous)
{
parent::__construct(
$message,
$previous->getCode(),
$previous->getSeverity(),
$previous->getFile(),
$previous->getLine(),
$previous->getPrevious()
);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Debug\Exception;

/**
* Undefined Function Exception.
*
* @author Konstanton Myakshin <[email protected]>
*/
class UndefinedFunctionException extends FatalErrorException
{
public function __construct($message, \ErrorException $previous)
{
parent::__construct(
$message,
$previous->getCode(),
$previous->getSeverity(),
$previous->getFile(),
$previous->getLine(),
$previous->getPrevious()
);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Debug\FatalErrorHandler;

use Symfony\Component\Debug\Exception\ClassNotFoundException;
use Symfony\Component\Debug\Exception\FatalErrorException;
use Composer\Autoload\ClassLoader as ComposerClassLoader;
use Symfony\Component\ClassLoader as SymfonyClassLoader;
use Symfony\Component\ClassLoader\DebugClassLoader;

/**
* ErrorHandler for classes that do not exist.
*
* @author Fabien Potencier <[email protected]>
*/
class ClassNotFoundFatalErrorHandler implements FatalErrorHandlerInterface
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would rename the class to ClassNotFoundHandler to be shorter and avoid repeating the namespace. What do you think ?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The way it is named now is how we do it elsewhere, so this is consistent.

{
/**
* {@inheritdoc}
*/
public function handleError(array $error, FatalErrorException $exception)
{
$messageLen = strlen($error['message']);
$notFoundSuffix = '" not found';
$notFoundSuffixLen = strlen($notFoundSuffix);
if ($notFoundSuffixLen > $messageLen) {
return;
}

if (0 !== substr_compare($error['message'], $notFoundSuffix, -$notFoundSuffixLen)) {
return;
}

foreach (array('class', 'interface', 'trait') as $typeName) {
$prefix = ucfirst($typeName).' "';
$prefixLen = strlen($prefix);
if (0 !== strpos($error['message'], $prefix)) {
continue;
}

$fullyQualifiedClassName = substr($error['message'], $prefixLen, -$notFoundSuffixLen);
if (false !== $namespaceSeparatorIndex = strrpos($fullyQualifiedClassName, '\\')) {
$className = substr($fullyQualifiedClassName, $namespaceSeparatorIndex + 1);
$namespacePrefix = substr($fullyQualifiedClassName, 0, $namespaceSeparatorIndex);
$message = sprintf(
'Attempted to load %s "%s" from namespace "%s" in %s line %d. Do you need to "use" it from another namespace?',
$typeName,
$className,
$namespacePrefix,
$error['file'],
$error['line']
);
} else {
$className = $fullyQualifiedClassName;
$message = sprintf(
'Attempted to load %s "%s" from the global namespace in %s line %d. Did you forget a use statement for this %s?',
$typeName,
$className,
$error['file'],
$error['line'],
$typeName
);
}

if ($classes = $this->getClassCandidates($className)) {
$message .= sprintf(' Perhaps you need to add a use statement for one of the following: %s.', implode(', ', $classes));
}

return new ClassNotFoundException($message, $exception);
}
}

/**
* Tries to guess the full namespace for a given class name.
*
* By default, it looks for PSR-0 classes registered via a Symfony or a Composer
* autoloader (that should cover all common cases).
*
* @param string $class A class name (without its namespace)
*
* @return array An array of possible fully qualified class names
*/
private function getClassCandidates($class)
{
if (!is_array($functions = spl_autoload_functions())) {
return array();
}

// find Symfony and Composer autoloaders
$classes = array();
foreach ($functions as $function) {
if (!is_array($function)) {
continue;
}

// get class loaders wrapped by DebugClassLoader
if ($function[0] instanceof DebugClassLoader && method_exists($function[0], 'getClassLoader')) {
$function[0] = $function[0]->getClassLoader();
}

if ($function[0] instanceof ComposerClassLoader || $function[0] instanceof SymfonyClassLoader) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what if the autoloader is a cached one (ApcClassLoader & co) ?

foreach ($function[0]->getPrefixes() as $paths) {
foreach ($paths as $path) {
$classes = array_merge($classes, $this->findClassInPath($function[0], $path, $class));
}
}
}
}

return $classes;
}

private function findClassInPath($loader, $path, $class)
{
if (!$path = realpath($path)) {
continue;
}

$classes = array();
$filename = $class.'.php';
foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path), \RecursiveIteratorIterator::LEAVES_ONLY) as $file) {
if ($filename == $file->getFileName() && $class = $this->convertFileToClass($loader, $path, $file->getPathName())) {
$classes[] = $class;
}
}

return $classes;
}

private function convertFileToClass($loader, $path, $file)
{
// We cannot use the autoloader here as most of them use require; but if the class
// is not found, the new autoloader call will require the file again leading to a
// "cannot redeclare class" error.
require_once $file;

$file = str_replace(array($path.'/', '.php'), array('', ''), $file);

// is it a namespaced class?
$class = str_replace('/', '\\', $file);
if (class_exists($class, false) || interface_exists($class, false) || (function_exists('trait_exists') && trait_exists($class, false))) {
return $class;
}

// is it a PEAR-like class name instead?
$class = str_replace('/', '_', $file);
if (class_exists($class, false) || interface_exists($class, false) || (function_exists('trait_exists') && trait_exists($class, false))) {
return $class;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Debug\FatalErrorHandler;

use Symfony\Component\Debug\Exception\FatalErrorException;

/**
* Attempts to convert fatal errors to exceptions.
*
* @author Fabien Potencier <[email protected]>
*/
interface FatalErrorHandlerInterface
{
/**
* Attempts to convert an error into an exception.
*
* @param array $error An array as returned by error_get_last()
* @param FatalErrorException $exception A FatalErrorException instance
*
* @return FatalErrorException|null A FatalErrorException instance if the class is able to convert the error, null otherwise
*/
public function handleError(array $error, FatalErrorException $exception);
}
Loading