Compare commits

..

52 Commits

Author SHA1 Message Date
Nicolas Grekas
4a7330f29b minor #28114 [travis] merge "same Symfony version" jobs in one (nicolas-grekas)
This PR was merged into the 2.8 branch.

Discussion
----------

[travis] merge "same Symfony version" jobs in one

| Q             | A
| ------------- | ---
| Branch?       | 2.8
| Bug fix?      | no
| New feature?  |
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | yes
| Fixed tickets | -
| License       | MIT
| Doc PR        | -

Allowing to consume fewer jobs and save the 1 to 2 minutes bootstrap time of workers.

Commits
-------

9857ca07aa [travis] merge "same Symfony version" jobs in one
2018-08-03 13:24:48 +02:00
Nicolas Grekas
fc4afe37fd [Debug] Fix populating error_get_last() for handled silent errors 2018-05-11 10:00:11 -07:00
Haralan Dobrev
e191af723b Add PHPDbg support to HTTP components 2018-04-03 07:05:54 +02:00
Haralan Dobrev
7e7619ce57 Support phpdbg SAPI in Debug::enable() 2018-03-27 09:04:21 +02:00
Nicolas Grekas
5555d0c0c4 [Debug] fix test 2018-03-19 19:37:04 +01:00
Nicolas Grekas
0a614d393b [Debug] Reset previous exception handler ealier to prevent infinite loop 2018-03-19 11:28:44 +01:00
Philipp Keck
6a76089f75 Pass on previous exception in FatalThrowableError 2018-02-28 13:02:44 -08:00
Alexander M. Turek
7d96be3eaf Removed unused parameter from flattenDataProvider(). 2018-02-03 01:09:36 +01:00
Nicolas Grekas
a91a8fdd8c [Debug] Fix bad registration of exception handler, leading to mem leak 2018-01-30 16:14:37 +01:00
Nicolas Grekas
bc9e38887a [HttpKernel] DebugHandlersListener should always replace the existing exception handler 2018-01-18 23:01:50 +01:00
Nicolas Grekas
955cfa5e94 [Debug] Always decorate existing exception handlers to deal with fatal errors 2018-01-18 10:58:19 +01:00
Nicolas Grekas
253f4fd5f6 [Debug] prevent infinite loop with faulty exception handlers 2018-01-11 09:02:09 +01:00
Nicolas Grekas
ff9e8cb401 minor #25653 PHP CS Fixer: clean up repo and adjust config (keradus)
This PR was squashed before being merged into the 2.7 branch (closes #25653).

Discussion
----------

PHP CS Fixer: clean up repo and adjust config

| Q             | A
| ------------- | ---
| Branch?       | 2.7
| Bug fix?      | no
| New feature?  | no
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | n/a
| Fixed tickets | n/a
| License       | MIT
| Doc PR        | n/a

Reason for this PR is that one want to have `php-cs-fixer fix -v` command executed without changes that shall not be applied for this repo. To achieve that, we need to groom config to exclude files that violate CS willingly, fix files that are violating CS unwillingly, and deliver missing case handling at PHP CS Fixer itself (https://github.com/FriendsOfPHP/PHP-CS-Fixer/pull/3359) (already merged!).

Commits
-------

b14cbc1 PHP CS Fixer: clean up repo and adjust config
2018-01-03 18:10:39 +01:00
Dariusz
e46133c70d PHP CS Fixer: clean up repo and adjust config 2018-01-03 18:10:15 +01:00
Fabien Potencier
526150f1a8 fixed years in copyright 2018-01-03 08:23:28 +01:00
Kévin Dunglas
79c3d84f0b Update LICENSE year... forever 2017-12-31 13:13:41 +01:00
Fabien Potencier
12370d9f98 fixed some deprecation messages 2017-12-31 05:55:05 +01:00
Romain Neutron
177a0b9b35 [2.7][DX] Use constant message contextualisation for deprecations 2017-12-20 15:36:51 +01:00
Dalibor Karlović
1086f33dba [2.7] Fix issues found by PHPStan 2017-12-20 10:28:52 +01:00
Nicolas Grekas
c573a9f2a1 [Debug] Fix catching fatal errors in case of nested error handlers 2017-12-09 18:06:03 +01:00
Nicolas Grekas
38fdc933c7 Remove function_exists(__phpunit_run_isolated_test) checks 2017-11-19 20:49:57 +02:00
Nicolas Grekas
271c75c24d [DI] minor docblock fixes 2017-10-24 13:40:19 +02:00
hubert.lenoir
f0546da70c [Debug] Fix same vendor detection in class loader 2017-10-13 19:28:12 +02:00
Nicolas Grekas
d2d11379b5 Fix 7.2 compat layer 2017-10-09 20:05:34 +02:00
Fabien Potencier
e12a6f1168 minor #24342 removed useless PHPDoc (OskarStark)
This PR was squashed before being merged into the 2.7 branch (closes #24342).

Discussion
----------

removed useless PHPDoc

| Q             | A
| ------------- | ---
| Branch?       | 2.7
| Bug fix?      | no
| New feature?  | no <!-- don't forget updating src/**/CHANGELOG.md files -->
| BC breaks?    | no
| Deprecations? | no <!-- don't forget updating UPGRADE-*.md files -->
| Tests pass?   | yes
| Fixed tickets |
| License       | MIT
| Doc PR        | n/a

Commits
-------

5ee9043d8b removed useless PHPDoc
2017-09-30 07:00:25 -07:00
Oskar Stark
34d945c4eb removed useless PHPDoc 2017-09-30 07:00:23 -07:00
Dariusz
9c5b622f5a [CS] Apply phpdoc_annotation_without_dot 2017-09-11 13:37:52 -07:00
Nicolas Grekas
f45a908634 [Debug] Remove false-positive check in DebugClassLoader 2017-08-27 10:27:28 +02:00
Nicolas Grekas
0946243775 bug #23684 [Debug] Missing escape in debug output (c960657)
This PR was merged into the 2.7 branch.

Discussion
----------

[Debug] Missing escape in debug output

| Q             | A
| ------------- | ---
| Branch?       | 2.7
| Bug fix?      | yes
| New feature?  | no
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | yes
| Fixed tickets |
| License       | MIT
| Doc PR        |

When pretty-printing an exception, the debug handler does not properly escape array keys.

The problem only occurs when debug output is enabled, so this is not considered a [security issue](http://symfony.com/doc/current/contributing/code/security.html) (according to @fabpot), because the debug tools [should not be used in production](https://symfony.com/doc/current/components/debug.html#usage).

A test for this is included in my patch for #18722.

Commits
-------

636777d [Debug] HTML-escape array key
2017-07-26 22:00:18 +02:00
Christian Schmidt
e1ce6a4ded [Debug] HTML-escape array key 2017-07-26 17:00:11 +02:00
Fabien Potencier
2662c21dea Using FQ name for PHP_VERSION_ID 2017-06-01 13:44:56 -07:00
Nicolas Grekas
28590cbb8f [Debug] Set exit status to 255 on error 2017-04-13 22:03:51 +02:00
Christian Flothmann
102a9b2776 fail when detecting risky tests 2017-04-12 09:39:27 +02:00
Nicolas Grekas
f302a96911 bug #22307 [Debug] Fix php notice (enumag)
This PR was submitted for the 2.8 branch but it was merged into the 2.7 branch instead (closes #22307).

Discussion
----------

[Debug] Fix php notice

| Q             | A
| ------------- | ---
| Branch?       | 2.8
| Bug fix?      | yes
| New feature?  | no
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | yes
| Fixed tickets |
| License       | MIT
| Doc PR        |

Of course autoloading of an empty string should not actually happen (fixed that in https://github.com/twigphp/Twig/pull/2438) but if it does happen it should not throw a php notice.

```
Notice: Uninitialized string offset 0
```

Commits
-------

e333a1a [Debug] Fix php notice
2017-04-07 14:20:28 +02:00
Jáchym Toušek
25f994cdf8 [Debug] Fix php notice 2017-04-07 14:16:45 +02:00
Fabien Potencier
ae2d80df72 fixed Composer constraints 2017-02-18 10:28:08 -08:00
Peter Rehm
0d4887956a Update to PHPUnit namespaces 2017-02-18 08:02:39 -08:00
Nicolas Grekas
4f9612ed86 [Debug] Workaround "null" $context 2017-01-25 13:11:45 +01:00
Nicolas Grekas
0ccbc5c4ca [Debug] Remove $context arg from handleError(), preparing for PHP 7.2 2017-01-24 16:28:42 +01:00
Fabien Potencier
bdc57ddfb5 Revert "fixed typo"
This reverts commit 6830d9f4c904d74020d2619fae990670edb3c3de.
2017-01-21 08:37:26 -08:00
Fabien Potencier
a4bf3f9ca9 fixed typo 2017-01-21 08:33:48 -08:00
Fabien Potencier
637babfcdc fixed CS 2017-01-20 08:54:19 -08:00
Fabien Potencier
b3bdc191eb updated LICENSE year 2017-01-02 12:30:00 -08:00
Grégoire Pineau
2f9a68243d [Debug] Wrap call to ->log in a try catch block
If something goes wrong in the logger, the application ends up
with a blank page. Let's display the original exception.
2016-12-27 15:50:31 +01:00
Nicolas Grekas
3717db3bfa bug #21010 [Debug] UndefinedMethodFatalErrorHandler - Handle anonymous classes (SpacePossum)
This PR was squashed before being merged into the 2.7 branch (closes #21010).

Discussion
----------

[Debug] UndefinedMethodFatalErrorHandler - Handle anonymous classes

| Q             | A
| ------------- | ---
| Branch?       | 2.7
| Bug fix?      | yes
| New feature?  | no
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | yes
| License       | MIT

When trying to call a method on an anonymous class (with or without methods) the `UndefinedMethodFatalErrorHandler` tries to iterate `null`.

For ref.: https://3v4l.org/l26u1

Commits
-------

ed713ae [Debug] UndefinedMethodFatalErrorHandler - Handle anonymous classes
2016-12-27 14:43:30 +01:00
SpacePossum
62a045d4cc [Debug] UndefinedMethodFatalErrorHandler - Handle anonymous classes 2016-12-27 14:43:27 +01:00
Fabien Potencier
83059abb7c fixed @return when returning this or static 2016-12-27 08:23:47 +01:00
Fabien Potencier
9544c5518f fixed obsolete getMock() usage 2016-12-19 16:22:46 +01:00
Nicolas Grekas
a9844f3cd2 bug #20519 [Debug] Remove GLOBALS from exception context to avoid endless recursion (Seldaek)
This PR was merged into the 2.7 branch.

Discussion
----------

[Debug] Remove GLOBALS from exception context to avoid endless recursion

| Q             | A
| ------------- | ---
| Branch?       | 2.7
| Bug fix?      | yes
| New feature?  | no
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | yes
| License       | MIT

This fixes a endless recursion as seen in https://github.com/felixfbecker/php-language-server/pull/137 - it only happens if you trigger an error in the global context so it's kinda hard to write a test for, but hopefully the fix can be accepted.

Commits
-------

1bb95ac [Debug] Remove GLOBALS from exception context to avoid endless recursion
2016-11-15 07:52:31 -05:00
Jordi Boggiano
0a8d55717a [Debug] Remove GLOBALS from exception context to avoid endless recursion 2016-11-15 13:37:17 +01:00
Dariusz Ruminski
6945a0d019 CS: apply rules 2016-11-03 08:44:53 +01:00
Yonel Ceruto
659f346c4a Code enhancement and cleanup 2016-09-06 09:26:07 +02:00
34 changed files with 928 additions and 455 deletions

View File

@@ -1,37 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Debug;
use Psr\Log\AbstractLogger;
/**
* A buffering logger that stacks logs for later.
*
* @author Nicolas Grekas <p@tchwork.com>
*/
class BufferingLogger extends AbstractLogger
{
private $logs = array();
public function log($level, $message, array $context = array())
{
$this->logs[] = array($level, $message, $context);
}
public function cleanLogs()
{
$logs = $this->logs;
$this->logs = array();
return $logs;
}
}

View File

@@ -1,18 +1,6 @@
CHANGELOG
=========
3.0.0
-----
* removed classes, methods and interfaces deprecated in 2.x
2.8.0
-----
* added BufferingLogger for errors that happen before a proper logger is configured
* allow throwing from `__toString()` with `return trigger_error($e, E_USER_ERROR);`
* deprecate ExceptionHandler::createResponse
2.7.0
-----

View File

@@ -31,7 +31,7 @@ class Debug
* @param int $errorReportingLevel The level of error reporting you want
* @param bool $displayErrors Whether to display errors (for development) or just log them (for production)
*/
public static function enable($errorReportingLevel = E_ALL, $displayErrors = true)
public static function enable($errorReportingLevel = null, $displayErrors = true)
{
if (static::$enabled) {
return;
@@ -42,20 +42,19 @@ class Debug
if (null !== $errorReportingLevel) {
error_reporting($errorReportingLevel);
} else {
error_reporting(E_ALL);
error_reporting(-1);
}
if ('cli' !== PHP_SAPI) {
if (!\in_array(PHP_SAPI, array('cli', 'phpdbg'), true)) {
ini_set('display_errors', 0);
ExceptionHandler::register();
} elseif ($displayErrors && (!ini_get('log_errors') || ini_get('error_log'))) {
// CLI - display errors only if they're not already logged to STDERR
ini_set('display_errors', 1);
}
if ($displayErrors) {
ErrorHandler::register(new ErrorHandler(new BufferingLogger()));
} else {
ErrorHandler::register()->throwAt(0, true);
$handler = ErrorHandler::register();
if (!$displayErrors) {
$handler->throwAt(0, true);
}
DebugClassLoader::enable();

View File

@@ -26,20 +26,28 @@ class DebugClassLoader
{
private $classLoader;
private $isFinder;
private $loaded = array();
private $wasFinder;
private static $caseCheck;
private static $deprecated = array();
private static $php7Reserved = array('int', 'float', 'bool', 'string', 'true', 'false', 'null');
private static $darwinCache = array('/' => array('/', array()));
/**
* Constructor.
*
* @param callable $classLoader A class loader
* @param callable|object $classLoader Passing an object is @deprecated since version 2.5 and support for it will be removed in 3.0
*/
public function __construct(callable $classLoader)
public function __construct($classLoader)
{
$this->classLoader = $classLoader;
$this->isFinder = is_array($classLoader) && method_exists($classLoader[0], 'findFile');
$this->wasFinder = is_object($classLoader) && method_exists($classLoader, 'findFile');
if ($this->wasFinder) {
@trigger_error('The '.__METHOD__.' method will no longer support receiving an object into its $classLoader argument in 3.0.', E_USER_DEPRECATED);
$this->classLoader = array($classLoader, 'loadClass');
$this->isFinder = true;
} else {
$this->classLoader = $classLoader;
$this->isFinder = is_array($classLoader) && method_exists($classLoader[0], 'findFile');
}
if (!isset(self::$caseCheck)) {
$file = file_exists(__FILE__) ? __FILE__ : rtrim(realpath('.'), DIRECTORY_SEPARATOR);
@@ -68,11 +76,11 @@ class DebugClassLoader
/**
* Gets the wrapped class loader.
*
* @return callable The wrapped class loader
* @return callable|object A class loader. Since version 2.5, returning an object is @deprecated and support for it will be removed in 3.0
*/
public function getClassLoader()
{
return $this->classLoader;
return $this->wasFinder ? $this->classLoader[0] : $this->classLoader;
}
/**
@@ -123,6 +131,24 @@ class DebugClassLoader
}
}
/**
* Finds a file by class name.
*
* @param string $class A class name to resolve to file
*
* @return string|null
*
* @deprecated since version 2.5, to be removed in 3.0.
*/
public function findFile($class)
{
@trigger_error('The '.__METHOD__.' method is deprecated since Symfony 2.5 and will be removed in 3.0.', E_USER_DEPRECATED);
if ($this->wasFinder) {
return $this->classLoader[0]->findFile($class);
}
}
/**
* Loads the given class or interface.
*
@@ -137,21 +163,30 @@ class DebugClassLoader
ErrorHandler::stackErrors();
try {
if ($this->isFinder) {
if ($this->isFinder && !isset($this->loaded[$class])) {
$this->loaded[$class] = true;
if ($file = $this->classLoader[0]->findFile($class)) {
require_once $file;
require $file;
}
} else {
call_user_func($this->classLoader, $class);
$file = false;
}
} finally {
} catch (\Exception $e) {
ErrorHandler::unstackErrors();
throw $e;
} catch (\Throwable $e) {
ErrorHandler::unstackErrors();
throw $e;
}
$exists = class_exists($class, false) || interface_exists($class, false) || trait_exists($class, false);
ErrorHandler::unstackErrors();
if ('\\' === $class[0]) {
$exists = class_exists($class, false) || interface_exists($class, false) || (function_exists('trait_exists') && trait_exists($class, false));
if ($class && '\\' === $class[0]) {
$class = substr($class, 1);
}
@@ -168,18 +203,11 @@ class DebugClassLoader
} elseif (preg_match('#\n \* @deprecated (.*?)\r?\n \*(?: @|/$)#s', $refl->getDocComment(), $notice)) {
self::$deprecated[$name] = preg_replace('#\s*\r?\n \* +#', ' ', $notice[1]);
} else {
if (2 > $len = 1 + (strpos($name, '\\', 1 + strpos($name, '\\')) ?: strpos($name, '_'))) {
if (2 > $len = 1 + (strpos($name, '\\') ?: strpos($name, '_'))) {
$len = 0;
$ns = '';
} else {
switch ($ns = substr($name, 0, $len)) {
case 'Symfony\Bridge\\':
case 'Symfony\Bundle\\':
case 'Symfony\Component\\':
$ns = 'Symfony\\';
$len = strlen($ns);
break;
}
$ns = substr($name, 0, $len);
}
$parent = get_parent_class($class);
@@ -188,26 +216,9 @@ class DebugClassLoader
@trigger_error(sprintf('The %s class extends %s that is deprecated %s', $name, $parent, self::$deprecated[$parent]), E_USER_DEPRECATED);
}
$parentInterfaces = array();
$deprecatedInterfaces = array();
if ($parent) {
foreach (class_implements($parent) as $interface) {
$parentInterfaces[$interface] = 1;
}
}
foreach ($refl->getInterfaceNames() as $interface) {
if (isset(self::$deprecated[$interface]) && strncmp($ns, $interface, $len)) {
$deprecatedInterfaces[] = $interface;
}
foreach (class_implements($interface) as $interface) {
$parentInterfaces[$interface] = 1;
}
}
foreach ($deprecatedInterfaces as $interface) {
if (!isset($parentInterfaces[$interface])) {
@trigger_error(sprintf('The %s %s %s that is deprecated %s', $name, $refl->isInterface() ? 'interface extends' : 'class implements', $interface, self::$deprecated[$interface]), E_USER_DEPRECATED);
foreach (class_implements($class) as $interface) {
if (isset(self::$deprecated[$interface]) && strncmp($ns, $interface, $len) && !is_subclass_of($parent, $interface)) {
@trigger_error(sprintf('The %s %s %s that is deprecated %s', $name, interface_exists($class) ? 'interface extends' : 'class implements', $interface, self::$deprecated[$interface]), E_USER_DEPRECATED);
}
}
}

View File

@@ -46,6 +46,11 @@ use Symfony\Component\Debug\FatalErrorHandler\FatalErrorHandlerInterface;
*/
class ErrorHandler
{
/**
* @deprecated since version 2.6, to be removed in 3.0.
*/
const TYPE_DEPRECATION = -100;
private $levels = array(
E_DEPRECATED => 'Deprecated',
E_USER_DEPRECATED => 'User Deprecated',
@@ -92,29 +97,42 @@ class ErrorHandler
private $isRecursive = 0;
private $isRoot = false;
private $exceptionHandler;
private $bootstrappingLogger;
private static $reservedMemory;
private static $stackedErrors = array();
private static $stackedErrorLevels = array();
private static $toStringException = null;
private static $exitCode = 0;
/**
* Same init value as thrownErrors.
*
* @deprecated since version 2.6, to be removed in 3.0.
*/
private $displayErrors = 0x1FFF;
/**
* Registers the error handler.
*
* @param self|null $handler The handler to register
* @param bool $replace Whether to replace or not any existing handler
* @param self|null|int $handler The handler to register, or @deprecated (since version 2.6, to be removed in 3.0) bit field of thrown levels
* @param bool $replace Whether to replace or not any existing handler
*
* @return self The registered error handler
*/
public static function register(self $handler = null, $replace = true)
public static function register($handler = null, $replace = true)
{
if (null === self::$reservedMemory) {
self::$reservedMemory = str_repeat('x', 10240);
register_shutdown_function(__CLASS__.'::handleFatalError');
}
if ($handlerIsNew = null === $handler) {
$levels = -1;
if ($handlerIsNew = !$handler instanceof self) {
// @deprecated polymorphism, to be removed in 3.0
if (null !== $handler) {
$levels = $replace ? $handler : 0;
$replace = true;
}
$handler = new static();
}
@@ -129,25 +147,31 @@ class ErrorHandler
$handler = $prev[0];
$replace = false;
}
if ($replace || !$prev) {
$handler->setExceptionHandler(set_exception_handler(array($handler, 'handleException')));
} else {
if (!$replace && $prev) {
restore_error_handler();
$handlerIsRegistered = is_array($prev) && $handler === $prev[0];
} else {
$handlerIsRegistered = true;
}
if (is_array($prev = set_exception_handler(array($handler, 'handleException'))) && $prev[0] instanceof self) {
restore_exception_handler();
if (!$handlerIsRegistered) {
$handler = $prev[0];
} elseif ($handler !== $prev[0] && $replace) {
set_exception_handler(array($handler, 'handleException'));
$p = $prev[0]->setExceptionHandler(null);
$handler->setExceptionHandler($p);
$prev[0]->setExceptionHandler($p);
}
} else {
$handler->setExceptionHandler($prev);
}
$handler->throwAt(E_ALL & $handler->thrownErrors, true);
$handler->throwAt($levels & $handler->thrownErrors, true);
return $handler;
}
public function __construct(BufferingLogger $bootstrappingLogger = null)
{
if ($bootstrappingLogger) {
$this->bootstrappingLogger = $bootstrappingLogger;
$this->setDefaultLogger($bootstrappingLogger);
}
}
/**
* Sets a logger to non assigned errors levels.
*
@@ -155,22 +179,22 @@ class ErrorHandler
* @param array|int $levels An array map of E_* to LogLevel::* or an integer bit field of E_* constants
* @param bool $replace Whether to replace or not any existing logger
*/
public function setDefaultLogger(LoggerInterface $logger, $levels = E_ALL, $replace = false)
public function setDefaultLogger(LoggerInterface $logger, $levels = null, $replace = false)
{
$loggers = array();
if (is_array($levels)) {
foreach ($levels as $type => $logLevel) {
if (empty($this->loggers[$type][0]) || $replace || $this->loggers[$type][0] === $this->bootstrappingLogger) {
if (empty($this->loggers[$type][0]) || $replace) {
$loggers[$type] = array($logger, $logLevel);
}
}
} else {
if (null === $levels) {
$levels = E_ALL;
$levels = E_ALL | E_STRICT;
}
foreach ($this->loggers as $type => $log) {
if (($type & $levels) && (empty($log[0]) || $replace || $log[0] === $this->bootstrappingLogger)) {
if (($type & $levels) && (empty($log[0]) || $replace)) {
$log[0] = $logger;
$loggers[$type] = $log;
}
@@ -193,7 +217,6 @@ class ErrorHandler
{
$prevLogged = $this->loggedErrors;
$prev = $this->loggers;
$flush = array();
foreach ($loggers as $type => $log) {
if (!isset($prev[$type])) {
@@ -212,24 +235,9 @@ class ErrorHandler
throw new \InvalidArgumentException('Invalid logger provided');
}
$this->loggers[$type] = $log + $prev[$type];
if ($this->bootstrappingLogger && $prev[$type][0] === $this->bootstrappingLogger) {
$flush[$type] = $type;
}
}
$this->reRegister($prevLogged | $this->thrownErrors);
if ($flush) {
foreach ($this->bootstrappingLogger->cleanLogs() as $log) {
$type = $log[2]['type'];
if (!isset($flush[$type])) {
$this->bootstrappingLogger->log($log[0], $log[1], $log[2]);
} elseif ($this->loggers[$type][0]) {
$this->loggers[$type][0]->log($this->loggers[$type][1], $log[1], $log[2]);
}
}
}
return $prev;
}
@@ -239,9 +247,14 @@ class ErrorHandler
* @param callable $handler A handler that will be called on Exception
*
* @return callable|null The previous exception handler
*
* @throws \InvalidArgumentException
*/
public function setExceptionHandler(callable $handler = null)
public function setExceptionHandler($handler)
{
if (null !== $handler && !is_callable($handler)) {
throw new \LogicException('The exception handler must be a valid PHP callable.');
}
$prev = $this->exceptionHandler;
$this->exceptionHandler = $handler;
@@ -265,6 +278,9 @@ class ErrorHandler
}
$this->reRegister($prev | $this->loggedErrors);
// $this->displayErrors is @deprecated since version 2.6
$this->displayErrors = $this->thrownErrors;
return $prev;
}
@@ -349,9 +365,9 @@ class ErrorHandler
* Handles errors by filtering then logging them according to the configured bit fields.
*
* @param int $type One of the E_* constants
* @param string $message
* @param string $file
* @param int $line
* @param array $context
*
* @return bool Returns false when no handling happens so that the PHP engine can handle the error itself
*
@@ -359,15 +375,32 @@ class ErrorHandler
*
* @internal
*/
public function handleError($type, $message, $file, $line, array $context, array $backtrace = null)
public function handleError($type, $message, $file, $line)
{
$level = error_reporting() | E_RECOVERABLE_ERROR | E_USER_ERROR | E_DEPRECATED | E_USER_DEPRECATED;
$level = error_reporting();
$silenced = 0 === ($level & $type);
$level |= E_RECOVERABLE_ERROR | E_USER_ERROR | E_DEPRECATED | E_USER_DEPRECATED;
$log = $this->loggedErrors & $type;
$throw = $this->thrownErrors & $type & $level;
$type &= $level | $this->screamedErrors;
if (!$type || (!$log && !$throw)) {
return $type && $log;
return !$silenced && $type && $log;
}
$scope = $this->scopedErrors & $type;
if (4 < $numArgs = func_num_args()) {
$context = $scope ? (func_get_arg(4) ?: array()) : array();
$backtrace = 5 < $numArgs ? func_get_arg(5) : null; // defined on HHVM
} else {
$context = array();
$backtrace = null;
}
if (isset($context['GLOBALS']) && $scope) {
$e = $context; // Whatever the signature of the method,
unset($e['GLOBALS'], $context); // $context is always a reference in 5.3
$context = $e;
}
if (null !== $backtrace && $type & E_ERROR) {
@@ -380,54 +413,19 @@ class ErrorHandler
}
if ($throw) {
if (null !== self::$toStringException) {
$throw = self::$toStringException;
self::$toStringException = null;
} elseif (($this->scopedErrors & $type) && class_exists(ContextErrorException::class)) {
if ($scope && class_exists('Symfony\Component\Debug\Exception\ContextErrorException')) {
// Checking for class existence is a work around for https://bugs.php.net/42098
$throw = new ContextErrorException($this->levels[$type].': '.$message, 0, $type, $file, $line, $context);
} else {
$throw = new \ErrorException($this->levels[$type].': '.$message, 0, $type, $file, $line);
}
if (E_USER_ERROR & $type) {
$backtrace = $backtrace ?: $throw->getTrace();
if (\PHP_VERSION_ID <= 50407 && (\PHP_VERSION_ID >= 50400 || \PHP_VERSION_ID <= 50317)) {
// Exceptions thrown from error handlers are sometimes not caught by the exception
// handler and shutdown handlers are bypassed before 5.4.8/5.3.18.
// We temporarily re-enable display_errors to prevent any blank page related to this bug.
for ($i = 1; isset($backtrace[$i]); ++$i) {
if (isset($backtrace[$i]['function'], $backtrace[$i]['type'], $backtrace[$i - 1]['function'])
&& '__toString' === $backtrace[$i]['function']
&& '->' === $backtrace[$i]['type']
&& !isset($backtrace[$i - 1]['class'])
&& ('trigger_error' === $backtrace[$i - 1]['function'] || 'user_error' === $backtrace[$i - 1]['function'])
) {
// Here, we know trigger_error() has been called from __toString().
// HHVM is fine with throwing from __toString() but PHP triggers a fatal error instead.
// A small convention allows working around the limitation:
// given a caught $e exception in __toString(), quitting the method with
// `return trigger_error($e, E_USER_ERROR);` allows this error handler
// to make $e get through the __toString() barrier.
foreach ($context as $e) {
if (($e instanceof \Exception || $e instanceof \Throwable) && $e->__toString() === $message) {
if (1 === $i) {
// On HHVM
$throw = $e;
break;
}
self::$toStringException = $e;
return true;
}
}
if (1 < $i) {
// On PHP (not on HHVM), display the original error message instead of the default one.
$this->handleException($throw);
// Stop the process by giving back the error to the native handler.
return false;
}
}
}
$throw->errorHandlerCanary = new ErrorHandlerCanary();
}
throw $throw;
@@ -446,7 +444,7 @@ class ErrorHandler
$e = compact('type', 'file', 'line', 'level');
if ($type & $level) {
if ($this->scopedErrors & $type) {
if ($scope) {
$e['scope_vars'] = $context;
if ($trace) {
$e['stack'] = $backtrace ?: debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT);
@@ -471,12 +469,19 @@ class ErrorHandler
try {
$this->isRecursive = true;
$this->loggers[$type][0]->log(($type & $level) ? $this->loggers[$type][1] : LogLevel::DEBUG, $message, $e);
} finally {
$this->isRecursive = false;
} catch (\Exception $e) {
$this->isRecursive = false;
throw $e;
} catch (\Throwable $e) {
$this->isRecursive = false;
throw $e;
}
}
return $type && $log;
return !$silenced && $type && $log;
}
/**
@@ -489,10 +494,14 @@ class ErrorHandler
*/
public function handleException($exception, array $error = null)
{
if (null === $error) {
self::$exitCode = 255;
}
if (!$exception instanceof \Exception) {
$exception = new FatalThrowableError($exception);
}
$type = $exception instanceof FatalErrorException ? $exception->getSeverity() : E_ERROR;
$handlerException = null;
if (($this->loggedErrors & $type) || $exception instanceof FatalThrowableError) {
$e = array(
@@ -523,7 +532,11 @@ class ErrorHandler
}
}
if ($this->loggedErrors & $type) {
$this->loggers[$type][0]->log($this->loggers[$type][1], $message, $e);
try {
$this->loggers[$type][0]->log($this->loggers[$type][1], $message, $e);
} catch (\Exception $handlerException) {
} catch (\Throwable $handlerException) {
}
}
if ($exception instanceof FatalErrorException && !$exception instanceof OutOfMemoryException && $error) {
foreach ($this->getFatalErrorHandlers() as $handler) {
@@ -533,18 +546,21 @@ class ErrorHandler
}
}
}
if (empty($this->exceptionHandler)) {
throw $exception; // Give back $exception to the native handler
}
$exceptionHandler = $this->exceptionHandler;
$this->exceptionHandler = null;
try {
call_user_func($this->exceptionHandler, $exception);
if (null !== $exceptionHandler) {
return \call_user_func($exceptionHandler, $exception);
}
$handlerException = $handlerException ?: $exception;
} catch (\Exception $handlerException) {
} catch (\Throwable $handlerException) {
}
if (isset($handlerException)) {
$this->exceptionHandler = null;
$this->handleException($handlerException);
if ($exception === $handlerException) {
self::$reservedMemory = null; // Disable the fatal error handler
throw $exception; // Give back $exception to the native handler
}
$this->handleException($handlerException);
}
/**
@@ -560,17 +576,41 @@ class ErrorHandler
return;
}
self::$reservedMemory = null;
$handler = self::$reservedMemory = null;
$handlers = array();
$previousHandler = null;
$sameHandlerLimit = 10;
$handler = set_error_handler('var_dump');
$handler = is_array($handler) ? $handler[0] : null;
restore_error_handler();
while (!is_array($handler) || !$handler[0] instanceof self) {
$handler = set_exception_handler('var_dump');
restore_exception_handler();
if (!$handler instanceof self) {
if (!$handler) {
break;
}
restore_exception_handler();
if ($handler !== $previousHandler) {
array_unshift($handlers, $handler);
$previousHandler = $handler;
} elseif (0 === --$sameHandlerLimit) {
$handler = null;
break;
}
}
foreach ($handlers as $h) {
set_exception_handler($h);
}
if (!$handler) {
return;
}
if ($handler !== $h) {
$handler[0]->setExceptionHandler($h);
}
$handler = $handler[0];
$handlers = array();
if (null === $error) {
if ($exit = null === $error) {
$error = error_get_last();
}
@@ -594,15 +634,21 @@ class ErrorHandler
} else {
$exception = new FatalErrorException($handler->levels[$error['type']].': '.$error['message'], 0, $error['type'], $error['file'], $error['line'], 2, true, $trace);
}
} elseif (!isset($exception)) {
return;
}
try {
$handler->handleException($exception, $error);
if (isset($exception)) {
self::$exitCode = 255;
$handler->handleException($exception, $error);
}
} catch (FatalErrorException $e) {
// Ignore this re-throw
}
if ($exit && self::$exitCode) {
$exitCode = self::$exitCode;
register_shutdown_function('register_shutdown_function', function () use ($exitCode) { exit($exitCode); });
}
}
/**
@@ -661,4 +707,118 @@ class ErrorHandler
new ClassNotFoundFatalErrorHandler(),
);
}
/**
* Sets the level at which the conversion to Exception is done.
*
* @param int|null $level The level (null to use the error_reporting() value and 0 to disable)
*
* @deprecated since version 2.6, to be removed in 3.0. Use throwAt() instead.
*/
public function setLevel($level)
{
@trigger_error('The '.__METHOD__.' method is deprecated since Symfony 2.6 and will be removed in 3.0. Use the throwAt() method instead.', E_USER_DEPRECATED);
$level = null === $level ? error_reporting() : $level;
$this->throwAt($level, true);
}
/**
* Sets the display_errors flag value.
*
* @param int $displayErrors The display_errors flag value
*
* @deprecated since version 2.6, to be removed in 3.0. Use throwAt() instead.
*/
public function setDisplayErrors($displayErrors)
{
@trigger_error('The '.__METHOD__.' method is deprecated since Symfony 2.6 and will be removed in 3.0. Use the throwAt() method instead.', E_USER_DEPRECATED);
if ($displayErrors) {
$this->throwAt($this->displayErrors, true);
} else {
$displayErrors = $this->displayErrors;
$this->throwAt(0, true);
$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, emergency or scream)
*
* @deprecated since version 2.6, to be removed in 3.0. Use setLoggers() or setDefaultLogger() instead.
*/
public static function setLogger(LoggerInterface $logger, $channel = 'deprecation')
{
@trigger_error('The '.__METHOD__.' static method is deprecated since Symfony 2.6 and will be removed in 3.0. Use the setLoggers() or setDefaultLogger() methods instead.', E_USER_DEPRECATED);
$handler = set_error_handler('var_dump');
$handler = is_array($handler) ? $handler[0] : null;
restore_error_handler();
if (!$handler instanceof self) {
return;
}
if ('deprecation' === $channel) {
$handler->setDefaultLogger($logger, E_DEPRECATED | E_USER_DEPRECATED, true);
$handler->screamAt(E_DEPRECATED | E_USER_DEPRECATED);
} elseif ('scream' === $channel) {
$handler->setDefaultLogger($logger, E_ALL | E_STRICT, false);
$handler->screamAt(E_ALL | E_STRICT);
} elseif ('emergency' === $channel) {
$handler->setDefaultLogger($logger, E_PARSE | E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR, true);
$handler->screamAt(E_PARSE | E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR);
}
}
/**
* @deprecated since version 2.6, to be removed in 3.0. Use handleError() instead.
*/
public function handle($level, $message, $file = 'unknown', $line = 0, $context = array())
{
$this->handleError(E_USER_DEPRECATED, 'The '.__METHOD__.' method is deprecated since Symfony 2.6 and will be removed in 3.0. Use the handleError() method instead.', __FILE__, __LINE__, array());
return $this->handleError($level, $message, $file, $line, (array) $context);
}
/**
* Handles PHP fatal errors.
*
* @deprecated since version 2.6, to be removed in 3.0. Use handleFatalError() instead.
*/
public function handleFatal()
{
@trigger_error('The '.__METHOD__.' method is deprecated since Symfony 2.6 and will be removed in 3.0. Use the handleFatalError() method instead.', E_USER_DEPRECATED);
static::handleFatalError();
}
}
/**
* Private class used to work around https://bugs.php.net/54275.
*
* @author Nicolas Grekas <p@tchwork.com>
*
* @internal
*/
class ErrorHandlerCanary
{
private static $displayErrors = null;
public function __construct()
{
if (null === self::$displayErrors) {
self::$displayErrors = ini_set('display_errors', 1);
}
}
public function __destruct()
{
if (null !== self::$displayErrors) {
ini_set('display_errors', self::$displayErrors);
self::$displayErrors = null;
}
}
}

View File

@@ -0,0 +1,23 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Debug\Exception;
@trigger_error('The '.__NAMESPACE__.'\DummyException class is deprecated since Symfony 2.5 and will be removed in 3.0.', E_USER_DEPRECATED);
/**
* @author Fabien Potencier <fabien@symfony.com>
*
* @deprecated since version 2.5, to be removed in 3.0.
*/
class DummyException extends \ErrorException
{
}

View File

@@ -9,14 +9,31 @@
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Exception;
/**
* Fatal Error Exception.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Konstanton Myakshin <koc-dp@yandex.ru>
* @author Nicolas Grekas <p@tchwork.com>
*
* @deprecated Deprecated in 2.3, to be removed in 3.0. Use the same class from the Debug component instead.
*/
class FatalErrorException extends \ErrorException
{
}
namespace Symfony\Component\Debug\Exception;
use Symfony\Component\HttpKernel\Exception\FatalErrorException as LegacyFatalErrorException;
/**
* Fatal Error Exception.
*
* @author Konstanton Myakshin <koc-dp@yandex.ru>
*/
class FatalErrorException extends \ErrorException
class FatalErrorException extends LegacyFatalErrorException
{
public function __construct($message, $code, $severity, $filename, $lineno, $traceOffset = null, $traceArgs = true, array $trace = null)
{

View File

@@ -36,7 +36,8 @@ class FatalThrowableError extends FatalErrorException
$e->getCode(),
$severity,
$e->getFile(),
$e->getLine()
$e->getLine(),
$e->getPrevious()
);
$this->setTrace($e->getTrace());

View File

@@ -9,8 +9,49 @@
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Exception;
use Symfony\Component\Debug\Exception\FlattenException as DebugFlattenException;
/**
* FlattenException wraps a PHP Exception to be able to serialize it.
*
* Basically, this class removes all objects from the trace.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @deprecated Deprecated in 2.3, to be removed in 3.0. Use the same class from the Debug component instead.
*/
class FlattenException
{
private $handler;
public static function __callStatic($method, $args)
{
if (!method_exists('Symfony\Component\Debug\Exception\FlattenException', $method)) {
throw new \BadMethodCallException(sprintf('Call to undefined method %s::%s()', get_called_class(), $method));
}
return call_user_func_array(array('Symfony\Component\Debug\Exception\FlattenException', $method), $args);
}
public function __call($method, $args)
{
if (!isset($this->handler)) {
$this->handler = new DebugFlattenException();
}
if (!method_exists($this->handler, $method)) {
throw new \BadMethodCallException(sprintf('Call to undefined method %s::%s()', get_class($this), $method));
}
return call_user_func_array(array($this->handler, $method), $args);
}
}
namespace Symfony\Component\Debug\Exception;
use Symfony\Component\HttpKernel\Exception\FlattenException as LegacyFlattenException;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
/**
@@ -20,7 +61,7 @@ use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class FlattenException
class FlattenException extends LegacyFlattenException
{
private $message;
private $code;

View File

@@ -11,6 +11,7 @@
namespace Symfony\Component\Debug;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Debug\Exception\FlattenException;
use Symfony\Component\Debug\Exception\OutOfMemoryException;
@@ -37,6 +38,12 @@ class ExceptionHandler
public function __construct($debug = true, $charset = null, $fileLinkFormat = null)
{
if (false !== strpos($charset, '%')) {
// Swap $charset and $fileLinkFormat for BC reasons
$pivot = $fileLinkFormat;
$fileLinkFormat = $charset;
$charset = $pivot;
}
$this->debug = $debug;
$this->charset = $charset ?: ini_get('default_charset') ?: 'UTF-8';
$this->fileLinkFormat = $fileLinkFormat ?: ini_get('xdebug.file_link_format') ?: get_cfg_var('xdebug.file_link_format');
@@ -49,7 +56,7 @@ class ExceptionHandler
* @param string|null $charset The charset used by exception messages
* @param string|null $fileLinkFormat The IDE link template
*
* @return ExceptionHandler The registered exception handler
* @return static
*/
public static function register($debug = true, $charset = null, $fileLinkFormat = null)
{
@@ -71,8 +78,11 @@ class ExceptionHandler
*
* @return callable|null The previous exception handler if any
*/
public function setHandler(callable $handler = null)
public function setHandler($handler)
{
if (null !== $handler && !is_callable($handler)) {
throw new \LogicException('The exception handler must be a valid PHP callable.');
}
$old = $this->handler;
$this->handler = $handler;
@@ -105,36 +115,20 @@ class ExceptionHandler
public function handle(\Exception $exception)
{
if (null === $this->handler || $exception instanceof OutOfMemoryException) {
$this->sendPhpResponse($exception);
$this->failSafeHandle($exception);
return;
}
$caughtLength = $this->caughtLength = 0;
ob_start(function ($buffer) {
$this->caughtBuffer = $buffer;
return '';
});
$this->sendPhpResponse($exception);
ob_start(array($this, 'catchOutput'));
$this->failSafeHandle($exception);
while (null === $this->caughtBuffer && ob_end_flush()) {
// Empty loop, everything is in the condition
}
if (isset($this->caughtBuffer[0])) {
ob_start(function ($buffer) {
if ($this->caughtLength) {
// use substr_replace() instead of substr() for mbstring overloading resistance
$cleanBuffer = substr_replace($buffer, '', 0, $this->caughtLength);
if (isset($cleanBuffer[0])) {
$buffer = $cleanBuffer;
}
}
return $buffer;
});
ob_start(array($this, 'cleanOutput'));
echo $this->caughtBuffer;
$caughtLength = ob_get_length();
}
@@ -151,13 +145,37 @@ class ExceptionHandler
}
}
/**
* Sends a response for the given Exception.
*
* If you have the Symfony HttpFoundation component installed,
* this method will use it to create and send the response. If not,
* it will fallback to plain PHP functions.
*/
private function failSafeHandle(\Exception $exception)
{
if (class_exists('Symfony\Component\HttpFoundation\Response', false)
&& __CLASS__ !== get_class($this)
&& ($reflector = new \ReflectionMethod($this, 'createResponse'))
&& __CLASS__ !== $reflector->class
) {
$response = $this->createResponse($exception);
$response->sendHeaders();
$response->sendContent();
return;
}
$this->sendPhpResponse($exception);
}
/**
* Sends the error associated with the given Exception as a plain PHP response.
*
* This method uses plain PHP functions like header() and echo to output
* the response.
*
* @param \Exception|FlattenException $exception An \Exception or FlattenException instance
* @param \Exception|FlattenException $exception An \Exception instance
*/
public function sendPhpResponse($exception)
{
@@ -177,26 +195,24 @@ class ExceptionHandler
}
/**
* Gets the full HTML content associated with the given exception.
* Creates the error Response associated with the given Exception.
*
* @param \Exception|FlattenException $exception An \Exception or FlattenException instance
* @param \Exception|FlattenException $exception An \Exception instance
*
* @return string The HTML content as a string
* @return Response A Response instance
*/
public function getHtml($exception)
public function createResponse($exception)
{
if (!$exception instanceof FlattenException) {
$exception = FlattenException::create($exception);
}
return $this->decorate($this->getContent($exception), $this->getStylesheet($exception));
return Response::create($this->decorate($this->getContent($exception), $this->getStylesheet($exception)), $exception->getStatusCode(), $exception->getHeaders())->setCharset($this->charset);
}
/**
* Gets the HTML content associated with the given exception.
*
* @param FlattenException $exception A FlattenException instance
*
* @return string The content as a string
*/
public function getContent(FlattenException $exception)
@@ -263,8 +279,6 @@ EOF;
/**
* Gets the stylesheet associated with the given exception.
*
* @param FlattenException $exception A FlattenException instance
*
* @return string The stylesheet as a string
*/
public function getStylesheet(FlattenException $exception)
@@ -399,17 +413,55 @@ EOF;
$formattedValue = str_replace("\n", '', var_export($this->escapeHtml((string) $item[1]), true));
}
$result[] = is_int($key) ? $formattedValue : sprintf("'%s' => %s", $key, $formattedValue);
$result[] = is_int($key) ? $formattedValue : sprintf("'%s' => %s", $this->escapeHtml($key), $formattedValue);
}
return implode(', ', $result);
}
/**
* Returns an UTF-8 and HTML encoded string.
*
* @deprecated since version 2.7, to be removed in 3.0.
*/
protected static function utf8Htmlize($str)
{
@trigger_error('The '.__METHOD__.' method is deprecated since Symfony 2.7 and will be removed in 3.0.', E_USER_DEPRECATED);
return htmlspecialchars($str, ENT_QUOTES | (\PHP_VERSION_ID >= 50400 ? ENT_SUBSTITUTE : 0), 'UTF-8');
}
/**
* HTML-encodes a string.
*/
private function escapeHtml($str)
{
return htmlspecialchars($str, ENT_QUOTES | ENT_SUBSTITUTE, $this->charset);
return htmlspecialchars($str, ENT_QUOTES | (\PHP_VERSION_ID >= 50400 ? ENT_SUBSTITUTE : 0), $this->charset);
}
/**
* @internal
*/
public function catchOutput($buffer)
{
$this->caughtBuffer = $buffer;
return '';
}
/**
* @internal
*/
public function cleanOutput($buffer)
{
if ($this->caughtLength) {
// use substr_replace() instead of substr() for mbstring overloading resistance
$cleanBuffer = substr_replace($buffer, '', 0, $this->caughtLength);
if (isset($cleanBuffer[0])) {
$buffer = $cleanBuffer;
}
}
return $buffer;
}
}

View File

@@ -16,6 +16,7 @@ use Symfony\Component\Debug\Exception\FatalErrorException;
use Symfony\Component\Debug\DebugClassLoader;
use Composer\Autoload\ClassLoader as ComposerClassLoader;
use Symfony\Component\ClassLoader\ClassLoader as SymfonyClassLoader;
use Symfony\Component\ClassLoader\UniversalClassLoader as SymfonyUniversalClassLoader;
/**
* ErrorHandler for classes that do not exist.
@@ -100,12 +101,17 @@ class ClassNotFoundFatalErrorHandler implements FatalErrorHandlerInterface
if ($function[0] instanceof DebugClassLoader) {
$function = $function[0]->getClassLoader();
// @deprecated since version 2.5. Returning an object from DebugClassLoader::getClassLoader() is deprecated.
if (is_object($function)) {
$function = array($function);
}
if (!is_array($function)) {
continue;
}
}
if ($function[0] instanceof ComposerClassLoader || $function[0] instanceof SymfonyClassLoader) {
if ($function[0] instanceof ComposerClassLoader || $function[0] instanceof SymfonyClassLoader || $function[0] instanceof SymfonyUniversalClassLoader) {
foreach ($function[0]->getPrefixes() as $prefix => $paths) {
foreach ($paths as $path) {
$classes = array_merge($classes, $this->findClassInPath($path, $class, $prefix));
@@ -173,7 +179,7 @@ class ClassNotFoundFatalErrorHandler implements FatalErrorHandlerInterface
);
if ($prefix) {
$candidates = array_filter($candidates, function ($candidate) use ($prefix) {return 0 === strpos($candidate, $prefix);});
$candidates = array_filter($candidates, function ($candidate) use ($prefix) { return 0 === strpos($candidate, $prefix); });
}
// We cannot use the autoloader here as most of them use require; but if the class
@@ -201,6 +207,6 @@ class ClassNotFoundFatalErrorHandler implements FatalErrorHandlerInterface
*/
private function classExists($class)
{
return class_exists($class, false) || interface_exists($class, false) || trait_exists($class, false);
return class_exists($class, false) || interface_exists($class, false) || (function_exists('trait_exists') && trait_exists($class, false));
}
}

View File

@@ -36,8 +36,13 @@ class UndefinedMethodFatalErrorHandler implements FatalErrorHandlerInterface
$message = sprintf('Attempted to call an undefined method named "%s" of class "%s".', $methodName, $className);
if (!class_exists($className) || null === $methods = get_class_methods($className)) {
// failed to get the class or its methods on which an unknown method was called (for example on an anonymous class)
return new UndefinedMethodException($message, $exception);
}
$candidates = array();
foreach (get_class_methods($className) as $definedMethodName) {
foreach ($methods as $definedMethodName) {
$lev = levenshtein($methodName, $definedMethodName);
if ($lev <= strlen($methodName) / 3 || false !== strpos($definedMethodName, $methodName)) {
$candidates[] = $definedMethodName;
@@ -52,6 +57,7 @@ class UndefinedMethodFatalErrorHandler implements FatalErrorHandlerInterface
} else {
$candidates = '"'.$last;
}
$message .= "\nDid you mean to call ".$candidates;
}

View File

@@ -1,4 +1,4 @@
Copyright (c) 2004-2016 Fabien Potencier
Copyright (c) 2004-2018 Fabien Potencier
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

View File

@@ -1,14 +1,16 @@
--TEST--
Test symfony_zval_info API
--SKIPIF--
<?php if (!extension_loaded("symfony_debug")) print "skip"; ?>
<?php if (!extension_loaded('symfony_debug')) {
echo 'skip';
} ?>
--FILE--
<?php
$int = 42;
$float = 42.42;
$str = "foobar";
$object = new StdClass;
$str = 'foobar';
$object = new StdClass();
$array = array('foo', 'bar');
$resource = tmpfile();
$null = null;
@@ -17,15 +19,17 @@ $bool = true;
$anotherint = 42;
$refcount2 = &$anotherint;
$var = array('int' => $int,
'float' => $float,
'str' => $str,
'object' => $object,
'array' => $array,
'resource' => $resource,
'null' => $null,
'bool' => $bool,
'refcount' => &$refcount2);
$var = array(
'int' => $int,
'float' => $float,
'str' => $str,
'object' => $object,
'array' => $array,
'resource' => $resource,
'null' => $null,
'bool' => $bool,
'refcount' => &$refcount2,
);
var_dump(symfony_zval_info('int', $var));
var_dump(symfony_zval_info('float', $var));

View File

@@ -1,7 +1,9 @@
--TEST--
Test symfony_debug_backtrace in case of fatal error
--SKIPIF--
<?php if (!extension_loaded("symfony_debug")) print "skip"; ?>
<?php if (!extension_loaded('symfony_debug')) {
echo 'skip';
} ?>
--FILE--
<?php
@@ -18,7 +20,6 @@ function foo()
function bt()
{
print_r(symfony_debug_backtrace());
}
register_shutdown_function('bt');

View File

@@ -1,7 +1,9 @@
--TEST--
Test symfony_debug_backtrace in case of non fatal error
--SKIPIF--
<?php if (!extension_loaded("symfony_debug")) print "skip"; ?>
<?php if (!extension_loaded('symfony_debug')) {
echo 'skip';
} ?>
--FILE--
<?php
@@ -13,7 +15,6 @@ function bar()
function bt()
{
print_r(symfony_debug_backtrace());
}
bar();

View File

@@ -1,7 +1,9 @@
--TEST--
Test ErrorHandler in case of fatal error
--SKIPIF--
<?php if (!extension_loaded("symfony_debug")) print "skip"; ?>
<?php if (!extension_loaded('symfony_debug')) {
echo 'skip';
} ?>
--FILE--
<?php

View File

@@ -11,10 +11,11 @@
namespace Symfony\Component\Debug\Tests;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Debug\DebugClassLoader;
use Symfony\Component\Debug\ErrorHandler;
class DebugClassLoaderTest extends \PHPUnit_Framework_TestCase
class DebugClassLoaderTest extends TestCase
{
/**
* @var int Error reporting level before running tests
@@ -25,7 +26,7 @@ class DebugClassLoaderTest extends \PHPUnit_Framework_TestCase
protected function setUp()
{
$this->errorReporting = error_reporting(E_ALL);
$this->errorReporting = error_reporting(E_ALL | E_STRICT);
$this->loader = new ClassLoader();
spl_autoload_register(array($this->loader, 'loadClass'), true, true);
DebugClassLoader::enable();
@@ -58,9 +59,26 @@ class DebugClassLoaderTest extends \PHPUnit_Framework_TestCase
$this->fail('DebugClassLoader did not register');
}
/**
* @expectedException \Exception
* @expectedExceptionMessage boo
*/
public function testThrowingClass()
{
try {
class_exists(__NAMESPACE__.'\Fixtures\Throwing');
$this->fail('Exception expected');
} catch (\Exception $e) {
$this->assertSame('boo', $e->getMessage());
}
// the second call also should throw
class_exists(__NAMESPACE__.'\Fixtures\Throwing');
}
public function testUnsilencing()
{
if (PHP_VERSION_ID >= 70000) {
if (\PHP_VERSION_ID >= 70000) {
$this->markTestSkipped('PHP7 throws exceptions, unsilencing is not required anymore.');
}
if (defined('HHVM_VERSION')) {
@@ -107,22 +125,27 @@ class DebugClassLoaderTest extends \PHPUnit_Framework_TestCase
$this->fail('ContextErrorException expected');
} catch (\ErrorException $exception) {
// if an exception is thrown, the test passed
restore_error_handler();
restore_exception_handler();
$this->assertStringStartsWith(__FILE__, $exception->getFile());
if (PHP_VERSION_ID < 70000) {
if (\PHP_VERSION_ID < 70000) {
$this->assertRegExp('/^Runtime Notice: Declaration/', $exception->getMessage());
$this->assertEquals(E_STRICT, $exception->getSeverity());
} else {
$this->assertRegExp('/^Warning: Declaration/', $exception->getMessage());
$this->assertEquals(E_WARNING, $exception->getSeverity());
}
} finally {
} catch (\Exception $exception) {
restore_error_handler();
restore_exception_handler();
throw $exception;
}
}
/**
* @expectedException \RuntimeException
* @expectedExceptionMessage Case mismatch between loaded and declared class names
*/
public function testNameCaseMismatch()
{
@@ -144,6 +167,7 @@ class DebugClassLoaderTest extends \PHPUnit_Framework_TestCase
/**
* @expectedException \RuntimeException
* @expectedExceptionMessage Case mismatch between loaded and declared class names
*/
public function testPsr4CaseMismatch()
{
@@ -184,7 +208,7 @@ class DebugClassLoaderTest extends \PHPUnit_Framework_TestCase
$xError = array(
'type' => E_USER_DEPRECATED,
'message' => 'The Test\Symfony\Component\Debug\Tests\\'.$class.' class '.$type.' Symfony\Component\Debug\Tests\Fixtures\\'.$super.' that is deprecated but this is a test deprecation notice.',
'message' => 'The Test\Symfony\Component\Debug\Tests\\'.$class.' class '.$type.' Symfony\Component\Debug\Tests\Fixtures\\'.$super.' that is deprecated but this is a test deprecation notice',
);
$this->assertSame($xError, $lastError);
@@ -198,28 +222,6 @@ class DebugClassLoaderTest extends \PHPUnit_Framework_TestCase
);
}
public function testInterfaceExtendsDeprecatedInterface()
{
set_error_handler(function () { return false; });
$e = error_reporting(0);
trigger_error('', E_USER_NOTICE);
class_exists('Test\\'.__NAMESPACE__.'\\NonDeprecatedInterfaceClass', true);
error_reporting($e);
restore_error_handler();
$lastError = error_get_last();
unset($lastError['file'], $lastError['line']);
$xError = array(
'type' => E_USER_NOTICE,
'message' => '',
);
$this->assertSame($xError, $lastError);
}
public function testDeprecatedSuperInSameNamespace()
{
set_error_handler(function () { return false; });
@@ -244,7 +246,7 @@ class DebugClassLoaderTest extends \PHPUnit_Framework_TestCase
public function testReservedForPhp7()
{
if (PHP_VERSION_ID >= 70000) {
if (\PHP_VERSION_ID >= 70000) {
$this->markTestSkipped('PHP7 already prevents using reserved names.');
}
@@ -306,8 +308,6 @@ class ClassLoader
eval('namespace Test\\'.__NAMESPACE__.'; class DeprecatedParentClass extends \\'.__NAMESPACE__.'\Fixtures\DeprecatedClass {}');
} elseif ('Test\\'.__NAMESPACE__.'\DeprecatedInterfaceClass' === $class) {
eval('namespace Test\\'.__NAMESPACE__.'; class DeprecatedInterfaceClass implements \\'.__NAMESPACE__.'\Fixtures\DeprecatedInterface {}');
} elseif ('Test\\'.__NAMESPACE__.'\NonDeprecatedInterfaceClass' === $class) {
eval('namespace Test\\'.__NAMESPACE__.'; class NonDeprecatedInterfaceClass implements \\'.__NAMESPACE__.'\Fixtures\NonDeprecatedInterface {}');
} elseif ('Test\\'.__NAMESPACE__.'\Float' === $class) {
eval('namespace Test\\'.__NAMESPACE__.'; class Float {}');
}

View File

@@ -11,9 +11,9 @@
namespace Symfony\Component\Debug\Tests;
use PHPUnit\Framework\TestCase;
use Psr\Log\LogLevel;
use Symfony\Component\Debug\ErrorHandler;
use Symfony\Component\Debug\BufferingLogger;
use Symfony\Component\Debug\Exception\ContextErrorException;
/**
@@ -22,7 +22,7 @@ use Symfony\Component\Debug\Exception\ContextErrorException;
* @author Robert Schönthal <seroscho@googlemail.com>
* @author Nicolas Grekas <p@tchwork.com>
*/
class ErrorHandlerTest extends \PHPUnit_Framework_TestCase
class ErrorHandlerTest extends TestCase
{
public function testRegister()
{
@@ -34,7 +34,7 @@ class ErrorHandlerTest extends \PHPUnit_Framework_TestCase
$newHandler = new ErrorHandler();
$this->assertSame($newHandler, ErrorHandler::register($newHandler, false));
$this->assertSame($handler, ErrorHandler::register($newHandler, false));
$h = set_error_handler('var_dump');
restore_error_handler();
$this->assertSame(array($handler, 'handleError'), $h);
@@ -64,6 +64,30 @@ class ErrorHandlerTest extends \PHPUnit_Framework_TestCase
}
}
public function testErrorGetLast()
{
$handler = ErrorHandler::register();
$logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
$handler->setDefaultLogger($logger);
$handler->screamAt(E_ALL);
try {
@trigger_error('Hello', E_USER_WARNING);
$expected = array(
'type' => E_USER_WARNING,
'message' => 'Hello',
'file' => __FILE__,
'line' => __LINE__ - 5,
);
$this->assertSame($expected, error_get_last());
} catch (\Exception $e) {
restore_error_handler();
restore_exception_handler();
throw $e;
}
}
public function testNotice()
{
ErrorHandler::register();
@@ -73,10 +97,15 @@ class ErrorHandlerTest extends \PHPUnit_Framework_TestCase
$this->fail('ContextErrorException expected');
} catch (ContextErrorException $exception) {
// if an exception is thrown, the test passed
restore_error_handler();
restore_exception_handler();
$this->assertEquals(E_NOTICE, $exception->getSeverity());
$this->assertEquals(__FILE__, $exception->getFile());
$this->assertRegExp('/^Notice: Undefined variable: (foo|bar)/', $exception->getMessage());
$this->assertArrayHasKey('foobar', $exception->getContext());
if (\PHP_VERSION_ID < 70200) {
$this->assertArrayHasKey('foobar', $exception->getContext());
}
$trace = $exception->getTrace();
$this->assertEquals(__FILE__, $trace[0]['file']);
@@ -93,9 +122,11 @@ class ErrorHandlerTest extends \PHPUnit_Framework_TestCase
$this->assertEquals(__CLASS__, $trace[2]['class']);
$this->assertEquals(__FUNCTION__, $trace[2]['function']);
$this->assertEquals('->', $trace[2]['type']);
} finally {
} catch (\Exception $e) {
restore_error_handler();
restore_exception_handler();
throw $e;
}
}
@@ -113,9 +144,14 @@ class ErrorHandlerTest extends \PHPUnit_Framework_TestCase
$handler = ErrorHandler::register();
$handler->throwAt(3, true);
$this->assertEquals(3 | E_RECOVERABLE_ERROR | E_USER_ERROR, $handler->throwAt(0));
} finally {
restore_error_handler();
restore_exception_handler();
} catch (\Exception $e) {
restore_error_handler();
restore_exception_handler();
throw $e;
}
}
@@ -124,7 +160,7 @@ class ErrorHandlerTest extends \PHPUnit_Framework_TestCase
try {
$handler = ErrorHandler::register();
$logger = $this->getMock('Psr\Log\LoggerInterface');
$logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
$handler->setDefaultLogger($logger, E_NOTICE);
$handler->setDefaultLogger($logger, array(E_USER_NOTICE => LogLevel::CRITICAL));
@@ -147,9 +183,14 @@ class ErrorHandlerTest extends \PHPUnit_Framework_TestCase
E_CORE_ERROR => array(null, LogLevel::CRITICAL),
);
$this->assertSame($loggers, $handler->setLoggers(array()));
} finally {
restore_error_handler();
restore_exception_handler();
} catch (\Exception $e) {
restore_error_handler();
restore_exception_handler();
throw $e;
}
}
@@ -198,15 +239,16 @@ class ErrorHandlerTest extends \PHPUnit_Framework_TestCase
restore_error_handler();
restore_exception_handler();
$logger = $this->getMock('Psr\Log\LoggerInterface');
$logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
$warnArgCheck = function ($logLevel, $message, $context) {
$this->assertEquals('info', $logLevel);
$this->assertEquals('foo', $message);
$this->assertArrayHasKey('type', $context);
$this->assertEquals($context['type'], E_USER_DEPRECATED);
$this->assertArrayHasKey('stack', $context);
$this->assertInternalType('array', $context['stack']);
$that = $this;
$warnArgCheck = function ($logLevel, $message, $context) use ($that) {
$that->assertEquals('info', $logLevel);
$that->assertEquals('foo', $message);
$that->assertArrayHasKey('type', $context);
$that->assertEquals($context['type'], E_USER_DEPRECATED);
$that->assertArrayHasKey('stack', $context);
$that->assertInternalType('array', $context['stack']);
};
$logger
@@ -222,12 +264,13 @@ class ErrorHandlerTest extends \PHPUnit_Framework_TestCase
restore_error_handler();
restore_exception_handler();
$logger = $this->getMock('Psr\Log\LoggerInterface');
$logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
$logArgCheck = function ($level, $message, $context) {
$this->assertEquals('Undefined variable: undefVar', $message);
$this->assertArrayHasKey('type', $context);
$this->assertEquals($context['type'], E_NOTICE);
$that = $this;
$logArgCheck = function ($level, $message, $context) use ($that) {
$that->assertEquals('Undefined variable: undefVar', $message);
$that->assertArrayHasKey('type', $context);
$that->assertEquals($context['type'], E_NOTICE);
};
$logger
@@ -252,38 +295,17 @@ class ErrorHandlerTest extends \PHPUnit_Framework_TestCase
}
}
public function testHandleUserError()
{
try {
$handler = ErrorHandler::register();
$handler->throwAt(0, true);
$e = null;
$x = new \Exception('Foo');
try {
$f = new Fixtures\ToStringThrower($x);
$f .= ''; // Trigger $f->__toString()
} catch (\Exception $e) {
}
$this->assertSame($x, $e);
} finally {
restore_error_handler();
restore_exception_handler();
}
}
public function testHandleDeprecation()
{
$logArgCheck = function ($level, $message, $context) {
$this->assertEquals(LogLevel::INFO, $level);
$this->assertArrayHasKey('level', $context);
$this->assertEquals(E_RECOVERABLE_ERROR | E_USER_ERROR | E_DEPRECATED | E_USER_DEPRECATED, $context['level']);
$this->assertArrayHasKey('stack', $context);
$that = $this;
$logArgCheck = function ($level, $message, $context) use ($that) {
$that->assertEquals(LogLevel::INFO, $level);
$that->assertArrayHasKey('level', $context);
$that->assertEquals(E_RECOVERABLE_ERROR | E_USER_ERROR | E_DEPRECATED | E_USER_DEPRECATED, $context['level']);
$that->assertArrayHasKey('stack', $context);
};
$logger = $this->getMock('Psr\Log\LoggerInterface');
$logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
$logger
->expects($this->once())
->method('log')
@@ -295,6 +317,9 @@ class ErrorHandlerTest extends \PHPUnit_Framework_TestCase
@$handler->handleError(E_USER_DEPRECATED, 'Foo deprecation', __FILE__, __LINE__, array());
}
/**
* @group no-hhvm
*/
public function testHandleException()
{
try {
@@ -302,12 +327,13 @@ class ErrorHandlerTest extends \PHPUnit_Framework_TestCase
$exception = new \Exception('foo');
$logger = $this->getMock('Psr\Log\LoggerInterface');
$logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
$logArgCheck = function ($level, $message, $context) {
$this->assertEquals('Uncaught Exception: foo', $message);
$this->assertArrayHasKey('type', $context);
$this->assertEquals($context['type'], E_ERROR);
$that = $this;
$logArgCheck = function ($level, $message, $context) use ($that) {
$that->assertEquals('Uncaught Exception: foo', $message);
$that->assertArrayHasKey('type', $context);
$that->assertEquals($context['type'], E_ERROR);
};
$logger
@@ -325,14 +351,20 @@ class ErrorHandlerTest extends \PHPUnit_Framework_TestCase
$this->assertSame($exception, $e);
}
$handler->setExceptionHandler(function ($e) use ($exception) {
$this->assertSame($exception, $e);
$that = $this;
$handler->setExceptionHandler(function ($e) use ($exception, $that) {
$that->assertSame($exception, $e);
});
$handler->handleException($exception);
} finally {
restore_error_handler();
restore_exception_handler();
} catch (\Exception $e) {
restore_error_handler();
restore_exception_handler();
throw $e;
}
}
@@ -342,7 +374,7 @@ class ErrorHandlerTest extends \PHPUnit_Framework_TestCase
$handler = ErrorHandler::register();
$handler->screamAt(E_USER_WARNING);
$logger = $this->getMock('Psr\Log\LoggerInterface');
$logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
$logger
->expects($this->exactly(2))
@@ -359,55 +391,20 @@ class ErrorHandlerTest extends \PHPUnit_Framework_TestCase
@trigger_error('Silenced warning', E_USER_WARNING);
$logger->log(LogLevel::WARNING, 'Dummy log');
ErrorHandler::unstackErrors();
} finally {
restore_error_handler();
restore_exception_handler();
} catch (\Exception $e) {
restore_error_handler();
restore_exception_handler();
throw $e;
}
}
public function testBootstrappingLogger()
{
$bootLogger = new BufferingLogger();
$handler = new ErrorHandler($bootLogger);
$loggers = array(
E_DEPRECATED => array($bootLogger, LogLevel::INFO),
E_USER_DEPRECATED => array($bootLogger, LogLevel::INFO),
E_NOTICE => array($bootLogger, LogLevel::WARNING),
E_USER_NOTICE => array($bootLogger, LogLevel::WARNING),
E_STRICT => array($bootLogger, LogLevel::WARNING),
E_WARNING => array($bootLogger, LogLevel::WARNING),
E_USER_WARNING => array($bootLogger, LogLevel::WARNING),
E_COMPILE_WARNING => array($bootLogger, LogLevel::WARNING),
E_CORE_WARNING => array($bootLogger, LogLevel::WARNING),
E_USER_ERROR => array($bootLogger, LogLevel::CRITICAL),
E_RECOVERABLE_ERROR => array($bootLogger, LogLevel::CRITICAL),
E_COMPILE_ERROR => array($bootLogger, LogLevel::CRITICAL),
E_PARSE => array($bootLogger, LogLevel::CRITICAL),
E_ERROR => array($bootLogger, LogLevel::CRITICAL),
E_CORE_ERROR => array($bootLogger, LogLevel::CRITICAL),
);
$this->assertSame($loggers, $handler->setLoggers(array()));
$handler->handleError(E_DEPRECATED, 'Foo message', __FILE__, 123, array());
$expectedLog = array(LogLevel::INFO, 'Foo message', array('type' => E_DEPRECATED, 'file' => __FILE__, 'line' => 123, 'level' => error_reporting()));
$logs = $bootLogger->cleanLogs();
unset($logs[0][2]['stack']);
$this->assertSame(array($expectedLog), $logs);
$bootLogger->log($expectedLog[0], $expectedLog[1], $expectedLog[2]);
$mockLogger = $this->getMock('Psr\Log\LoggerInterface');
$mockLogger->expects($this->once())
->method('log')
->with(LogLevel::WARNING, 'Foo message', $expectedLog[2]);
$handler->setLoggers(array(E_DEPRECATED => array($mockLogger, LogLevel::WARNING)));
}
/**
* @group no-hhvm
*/
public function testHandleFatalError()
{
try {
@@ -420,12 +417,13 @@ class ErrorHandlerTest extends \PHPUnit_Framework_TestCase
'line' => 123,
);
$logger = $this->getMock('Psr\Log\LoggerInterface');
$logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
$logArgCheck = function ($level, $message, $context) {
$this->assertEquals('Fatal Parse Error: foo', $message);
$this->assertArrayHasKey('type', $context);
$this->assertEquals($context['type'], E_PARSE);
$that = $this;
$logArgCheck = function ($level, $message, $context) use ($that) {
$that->assertEquals('Fatal Parse Error: foo', $message);
$that->assertArrayHasKey('type', $context);
$that->assertEquals($context['type'], E_PARSE);
};
$logger
@@ -466,12 +464,15 @@ class ErrorHandlerTest extends \PHPUnit_Framework_TestCase
$this->assertStringStartsWith("Attempted to load class \"Foo\" from the global namespace.\nDid you forget a \"use\" statement", $args[0]->getMessage());
}
/**
* @group no-hhvm
*/
public function testHandleFatalErrorOnHHVM()
{
try {
$handler = ErrorHandler::register();
$logger = $this->getMock('Psr\Log\LoggerInterface');
$logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
$logger
->expects($this->once())
->method('log')
@@ -501,9 +502,70 @@ class ErrorHandlerTest extends \PHPUnit_Framework_TestCase
call_user_func_array(array($handler, 'handleError'), $error);
$handler->handleFatalError($error);
} finally {
restore_error_handler();
restore_exception_handler();
} catch (\Exception $e) {
restore_error_handler();
restore_exception_handler();
throw $e;
}
}
/**
* @group legacy
*/
public function testLegacyInterface()
{
try {
$handler = ErrorHandler::register(0);
$this->assertFalse($handler->handle(0, 'foo', 'foo.php', 12, array()));
restore_error_handler();
restore_exception_handler();
$logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
$that = $this;
$logArgCheck = function ($level, $message, $context) use ($that) {
$that->assertEquals('Undefined variable: undefVar', $message);
$that->assertArrayHasKey('type', $context);
$that->assertEquals($context['type'], E_NOTICE);
};
$logger
->expects($this->once())
->method('log')
->will($this->returnCallback($logArgCheck))
;
$handler = ErrorHandler::register(E_NOTICE);
@$handler->setLogger($logger, 'scream');
unset($undefVar);
@$undefVar++;
restore_error_handler();
restore_exception_handler();
} catch (\Exception $e) {
restore_error_handler();
restore_exception_handler();
throw $e;
}
}
/**
* @expectedException \Exception
* @group no-hhvm
*/
public function testCustomExceptionHandler()
{
$handler = new ErrorHandler();
$handler->setExceptionHandler(function ($e) use ($handler) {
$handler->handleException($e);
});
$handler->handleException(new \Exception());
}
}

View File

@@ -11,6 +11,7 @@
namespace Symfony\Component\Debug\Tests\Exception;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Debug\Exception\FlattenException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
@@ -27,7 +28,7 @@ use Symfony\Component\HttpKernel\Exception\ServiceUnavailableHttpException;
use Symfony\Component\HttpKernel\Exception\TooManyRequestsHttpException;
use Symfony\Component\HttpKernel\Exception\UnsupportedMediaTypeHttpException;
class FlattenExceptionTest extends \PHPUnit_Framework_TestCase
class FlattenExceptionTest extends TestCase
{
public function testStatusCode()
{
@@ -104,7 +105,7 @@ class FlattenExceptionTest extends \PHPUnit_Framework_TestCase
/**
* @dataProvider flattenDataProvider
*/
public function testFlattenHttpException(\Exception $exception, $statusCode)
public function testFlattenHttpException(\Exception $exception)
{
$flattened = FlattenException::create($exception);
$flattened2 = FlattenException::create($exception);
@@ -119,7 +120,7 @@ class FlattenExceptionTest extends \PHPUnit_Framework_TestCase
/**
* @dataProvider flattenDataProvider
*/
public function testPrevious(\Exception $exception, $statusCode)
public function testPrevious(\Exception $exception)
{
$flattened = FlattenException::create($exception);
$flattened2 = FlattenException::create($exception);
@@ -166,7 +167,7 @@ class FlattenExceptionTest extends \PHPUnit_Framework_TestCase
/**
* @dataProvider flattenDataProvider
*/
public function testToArray(\Exception $exception, $statusCode)
public function testToArray(\Exception $exception)
{
$flattened = FlattenException::create($exception);
$flattened->setTrace(array(), 'foo.php', 123);
@@ -186,12 +187,13 @@ class FlattenExceptionTest extends \PHPUnit_Framework_TestCase
public function flattenDataProvider()
{
return array(
array(new \Exception('test', 123), 500),
array(new \Exception('test', 123)),
);
}
public function testRecursionInArguments()
{
$a = null;
$a = array('foo', array(2, &$a));
$exception = $this->createException($a);

View File

@@ -11,6 +11,7 @@
namespace Symfony\Component\Debug\Tests;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Debug\ExceptionHandler;
use Symfony\Component\Debug\Exception\OutOfMemoryException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
@@ -18,7 +19,7 @@ use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
require_once __DIR__.'/HeaderMock.php';
class ExceptionHandlerTest extends \PHPUnit_Framework_TestCase
class ExceptionHandlerTest extends TestCase
{
protected function setUp()
{
@@ -100,15 +101,16 @@ class ExceptionHandlerTest extends \PHPUnit_Framework_TestCase
{
$exception = new \Exception('foo');
$handler = $this->getMock('Symfony\Component\Debug\ExceptionHandler', array('sendPhpResponse'));
$handler = $this->getMockBuilder('Symfony\Component\Debug\ExceptionHandler')->setMethods(array('sendPhpResponse'))->getMock();
$handler
->expects($this->exactly(2))
->method('sendPhpResponse');
$handler->handle($exception);
$handler->setHandler(function ($e) use ($exception) {
$this->assertSame($exception, $e);
$that = $this;
$handler->setHandler(function ($e) use ($exception, $that) {
$that->assertSame($exception, $e);
});
$handler->handle($exception);
@@ -118,13 +120,14 @@ class ExceptionHandlerTest extends \PHPUnit_Framework_TestCase
{
$exception = new OutOfMemoryException('foo', 0, E_ERROR, __FILE__, __LINE__);
$handler = $this->getMock('Symfony\Component\Debug\ExceptionHandler', array('sendPhpResponse'));
$handler = $this->getMockBuilder('Symfony\Component\Debug\ExceptionHandler')->setMethods(array('sendPhpResponse'))->getMock();
$handler
->expects($this->once())
->method('sendPhpResponse');
$handler->setHandler(function ($e) {
$this->fail('OutOfMemoryException should bypass the handler');
$that = $this;
$handler->setHandler(function ($e) use ($that) {
$that->fail('OutOfMemoryException should bypass the handler');
});
$handler->handle($exception);

View File

@@ -11,13 +11,15 @@
namespace Symfony\Component\Debug\Tests\FatalErrorHandler;
use Symfony\Component\Debug\Exception\FatalErrorException;
use PHPUnit\Framework\TestCase;
use Symfony\Component\ClassLoader\ClassLoader as SymfonyClassLoader;
use Symfony\Component\ClassLoader\UniversalClassLoader as SymfonyUniversalClassLoader;
use Symfony\Component\Debug\Exception\FatalErrorException;
use Symfony\Component\Debug\FatalErrorHandler\ClassNotFoundFatalErrorHandler;
use Symfony\Component\Debug\DebugClassLoader;
use Composer\Autoload\ClassLoader as ComposerClassLoader;
class ClassNotFoundFatalErrorHandlerTest extends \PHPUnit_Framework_TestCase
class ClassNotFoundFatalErrorHandlerTest extends TestCase
{
public static function setUpBeforeClass()
{
@@ -67,6 +69,27 @@ class ClassNotFoundFatalErrorHandlerTest extends \PHPUnit_Framework_TestCase
$this->assertSame($error['line'], $exception->getLine());
}
/**
* @group legacy
*/
public function testLegacyHandleClassNotFound()
{
$prefixes = array('Symfony\Component\Debug\Exception\\' => realpath(__DIR__.'/../../Exception'));
$symfonyUniversalClassLoader = new SymfonyUniversalClassLoader();
$symfonyUniversalClassLoader->registerPrefixes($prefixes);
$this->testHandleClassNotFound(
array(
'type' => 1,
'line' => 12,
'file' => 'foo.php',
'message' => 'Class \'Foo\\Bar\\UndefinedFunctionException\' not found',
),
"Attempted to load class \"UndefinedFunctionException\" from namespace \"Foo\Bar\".\nDid you forget a \"use\" statement for \"Symfony\Component\Debug\Exception\UndefinedFunctionException\"?",
array($symfonyUniversalClassLoader, 'loadClass')
);
}
public function provideClassNotFoundData()
{
$prefixes = array('Symfony\Component\Debug\Exception\\' => realpath(__DIR__.'/../../Exception'));

View File

@@ -11,10 +11,11 @@
namespace Symfony\Component\Debug\Tests\FatalErrorHandler;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Debug\Exception\FatalErrorException;
use Symfony\Component\Debug\FatalErrorHandler\UndefinedFunctionFatalErrorHandler;
class UndefinedFunctionFatalErrorHandlerTest extends \PHPUnit_Framework_TestCase
class UndefinedFunctionFatalErrorHandlerTest extends TestCase
{
/**
* @dataProvider provideUndefinedFunctionData

View File

@@ -11,10 +11,11 @@
namespace Symfony\Component\Debug\Tests\FatalErrorHandler;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Debug\Exception\FatalErrorException;
use Symfony\Component\Debug\FatalErrorHandler\UndefinedMethodFatalErrorHandler;
class UndefinedMethodFatalErrorHandlerTest extends \PHPUnit_Framework_TestCase
class UndefinedMethodFatalErrorHandlerTest extends TestCase
{
/**
* @dataProvider provideUndefinedMethodData
@@ -61,6 +62,15 @@ class UndefinedMethodFatalErrorHandlerTest extends \PHPUnit_Framework_TestCase
),
"Attempted to call an undefined method named \"offsetFet\" of class \"SplObjectStorage\".\nDid you mean to call e.g. \"offsetGet\", \"offsetSet\" or \"offsetUnset\"?",
),
array(
array(
'type' => 1,
'message' => 'Call to undefined method class@anonymous::test()',
'file' => '/home/possum/work/symfony/test.php',
'line' => 11,
),
'Attempted to call an undefined method named "test" of class "class@anonymous".',
),
);
}
}

View File

@@ -4,7 +4,7 @@ namespace Symfony\Component\Debug\Tests\Fixtures;
/**
* @deprecated but this is a test
* deprecation notice.
* deprecation notice
* @foobar
*/
class DeprecatedClass

View File

@@ -4,7 +4,7 @@ namespace Symfony\Component\Debug\Tests\Fixtures;
/**
* @deprecated but this is a test
* deprecation notice.
* deprecation notice
* @foobar
*/
interface DeprecatedInterface

View File

@@ -1,7 +0,0 @@
<?php
namespace Symfony\Component\Debug\Tests\Fixtures;
interface NonDeprecatedInterface extends DeprecatedInterface
{
}

View File

@@ -0,0 +1,3 @@
<?php
throw new \Exception('boo');

View File

@@ -1,24 +0,0 @@
<?php
namespace Symfony\Component\Debug\Tests\Fixtures;
class ToStringThrower
{
private $exception;
public function __construct(\Exception $e)
{
$this->exception = $e;
}
public function __toString()
{
try {
throw $this->exception;
} catch (\Exception $e) {
// Using user_error() here is on purpose so we do not forget
// that this alias also should work alongside with trigger_error().
return user_error($e, E_USER_ERROR);
}
}
}

View File

@@ -0,0 +1,46 @@
--TEST--
Test catching fatal errors when handlers are nested
--FILE--
<?php
namespace Symfony\Component\Debug;
$vendor = __DIR__;
while (!file_exists($vendor.'/vendor')) {
$vendor = dirname($vendor);
}
require $vendor.'/vendor/autoload.php';
set_error_handler('var_dump');
set_exception_handler('var_dump');
ErrorHandler::register(null, false);
if (true) {
class foo extends missing
{
}
}
?>
--EXPECTF--
Fatal error: Class 'Symfony\Component\Debug\missing' not found in %s on line %d
object(Symfony\Component\Debug\Exception\ClassNotFoundException)#%d (8) {
["message":protected]=>
string(131) "Attempted to load class "missing" from namespace "Symfony\Component\Debug".
Did you forget a "use" statement for another namespace?"
["string":"Exception":private]=>
string(0) ""
["code":protected]=>
int(0)
["file":protected]=>
string(%d) "%s"
["line":protected]=>
int(%d)
["trace":"Exception":private]=>
array(%d) {%A}
["previous":"Exception":private]=>
NULL
["severity":protected]=>
int(1)
}

View File

@@ -0,0 +1,35 @@
--TEST--
Test rethrowing in custom exception handler
--FILE--
<?php
namespace Symfony\Component\Debug;
$vendor = __DIR__;
while (!file_exists($vendor.'/vendor')) {
$vendor = dirname($vendor);
}
require $vendor.'/vendor/autoload.php';
if (true) {
class TestLogger extends \Psr\Log\AbstractLogger
{
public function log($level, $message, array $context = array())
{
echo $message, "\n";
}
}
}
set_exception_handler(function ($e) { echo 123; throw $e; });
ErrorHandler::register()->setDefaultLogger(new TestLogger());
ini_set('display_errors', 1);
throw new \Exception('foo');
?>
--EXPECTF--
Uncaught Exception: foo
123
Fatal error: Uncaught %s:25
Stack trace:
%a

View File

@@ -0,0 +1,42 @@
--TEST--
Test catching fatal errors when handlers are nested
--FILE--
<?php
namespace Symfony\Component\Debug;
$vendor = __DIR__;
while (!file_exists($vendor.'/vendor')) {
$vendor = dirname($vendor);
}
require $vendor.'/vendor/autoload.php';
Debug::enable();
ini_set('display_errors', 0);
$eHandler = set_error_handler('var_dump');
$xHandler = set_exception_handler('var_dump');
var_dump(array(
$eHandler[0] === $xHandler[0] ? 'Error and exception handlers do match' : 'Error and exception handlers are different',
));
$eHandler[0]->setExceptionHandler('print_r');
if (true) {
class Broken implements \Serializable
{
}
}
?>
--EXPECTF--
array(1) {
[0]=>
string(37) "Error and exception handlers do match"
}
object(Symfony\Component\Debug\Exception\FatalErrorException)#%d (8) {
["message":protected]=>
string(199) "Error: Class Symfony\Component\Debug\Broken contains 2 abstract methods and must therefore be declared abstract or implement the remaining methods (Serializable::serialize, Serializable::unserialize)"
%a
}

View File

@@ -16,15 +16,15 @@
}
],
"require": {
"php": ">=5.5.9",
"php": ">=5.3.9",
"psr/log": "~1.0"
},
"conflict": {
"symfony/http-kernel": ">=2.3,<2.3.24|~2.4.0|>=2.5,<2.5.9|>=2.6,<2.6.2"
},
"require-dev": {
"symfony/class-loader": "~2.8|~3.0",
"symfony/http-kernel": "~2.8|~3.0"
"symfony/class-loader": "~2.2",
"symfony/http-kernel": "~2.3.24|~2.5.9|^2.6.2"
},
"autoload": {
"psr-4": { "Symfony\\Component\\Debug\\": "" },
@@ -35,7 +35,7 @@
"minimum-stability": "dev",
"extra": {
"branch-alias": {
"dev-master": "3.1-dev"
"dev-master": "2.7-dev"
}
}
}

View File

@@ -5,6 +5,8 @@
backupGlobals="false"
colors="true"
bootstrap="vendor/autoload.php"
failOnRisky="true"
failOnWarning="true"
>
<php>
<ini name="error_reporting" value="-1" />