Skip to content

[8.x] Logs deprecations instead of treating them as exceptions #1197

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 2 commits into from
Oct 19, 2021
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
13 changes: 13 additions & 0 deletions config/logging.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,19 @@

'default' => env('LOG_CHANNEL', 'stack'),

/*
|--------------------------------------------------------------------------
| Deprecations Log Channel
|--------------------------------------------------------------------------
|
| This option controls the log channel that should be used to log warnings
| regarding deprecated PHP and library features. This allows you to get
| your application ready for upcoming major versions of dependencies.
|
*/

'deprecations' => env('LOG_DEPRECATIONS_CHANNEL', 'null'),

/*
|--------------------------------------------------------------------------
| Log Channels
Expand Down
1 change: 1 addition & 0 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
beStrictAboutTestsThatDoNotTestAnything="false"
bootstrap="tests/bootstrap.php"
colors="true"
convertErrorsToExceptions="true"
Expand Down
87 changes: 84 additions & 3 deletions src/Concerns/RegistersExceptionHandlers.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
namespace Laravel\Lumen\Concerns;

use ErrorException;
use Exception;
use Illuminate\Contracts\Debug\ExceptionHandler;
use Illuminate\Log\LogManager;
use Laravel\Lumen\Exceptions\Handler;
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\ErrorHandler\Error\FatalError;
Expand Down Expand Up @@ -42,9 +44,7 @@ protected function registerErrorHandling()
error_reporting(-1);

set_error_handler(function ($level, $message, $file = '', $line = 0) {
if (error_reporting() & $level) {
throw new ErrorException($message, 0, $level, $file, $line);
}
$this->handleError($level, $message, $file, $line);
});

set_exception_handler(function ($e) {
Expand All @@ -56,6 +56,76 @@ protected function registerErrorHandling()
});
}

/**
* Report PHP deprecations, or convert PHP errors to ErrorException instances.
*
* @param int $level
* @param string $message
* @param string $file
* @param int $line
* @param array $context
* @return void
*
* @throws \ErrorException
*/
public function handleError($level, $message, $file = '', $line = 0, $context = [])
{
if (error_reporting() & $level) {
if ($this->isDeprecation($level)) {
return $this->handleDeprecation($message, $file, $line);
}

throw new ErrorException($message, 0, $level, $file, $line);
}
}

/**
* Reports a deprecation to the "deprecations" logger.
*
* @param string $message
* @param string $file
* @param int $line
* @return void
*/
public function handleDeprecation($message, $file, $line)
{
try {
$logger = $this->make('log');
} catch (Exception $e) {
return;
}

if (! $logger instanceof LogManager) {
return;
}

$this->ensureDeprecationLoggerIsConfigured();

with($logger->channel('deprecations'), function ($log) use ($message, $file, $line) {
$log->warning(sprintf('%s in %s on line %s',
$message, $file, $line
));
});
}

/**
* Ensure the "deprecations" logger is configured.
*
* @return void
*/
protected function ensureDeprecationLoggerIsConfigured()
{
with($this->make('config'), function ($config) {
if ($config->get('logging.channels.deprecations')) {
return;
}

$driver = $config->get('logging.deprecations') ?? 'null';

$config->set('logging.channels.deprecations', $config->get("logging.channels.{$driver}"));
});
}

/**
* Handle the PHP shutdown event.
*
Expand All @@ -80,6 +150,17 @@ protected function fatalErrorFromPhpError(array $error, $traceOffset = null)
return new FatalError($error['message'], 0, $error, $traceOffset);
}

/**
* Determine if the error level is a deprecation.
*
* @param int $level
* @return bool
*/
protected function isDeprecation($level)
{
return in_array($level, [E_DEPRECATED, E_USER_DEPRECATED]);
}

/**
* Determine if the error type is fatal.
*
Expand Down
164 changes: 164 additions & 0 deletions tests/HandleExceptionsTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
<?php

use Illuminate\Config\Repository as Config;
use Illuminate\Container\Container;
use Illuminate\Log\LogManager;
use Laravel\Lumen\Concerns\RegistersExceptionHandlers;
use Mockery as m;
use PHPUnit\Framework\TestCase;

class HandleExceptionsTest extends TestCase
{
use RegistersExceptionHandlers;

protected function setUp(): void
{
$this->container = new Container;

$this->config = new Config();

$this->container->singleton('config', function () {
return $this->config;
});
}

protected function tearDown(): void
{
$this->container::setInstance(null);

m::close();
}

public function testPhpDeprecations()
{
$logger = m::mock(LogManager::class);
$this->container->instance('log', $logger);
$logger->shouldReceive('channel')->with('deprecations')->andReturnSelf();
$logger->shouldReceive('warning')->with(sprintf('%s in %s on line %s',
'str_contains(): Passing null to parameter #2 ($needle) of type string is deprecated',
'/home/user/laravel/routes/web.php',
17
));

$this->handleError(
E_DEPRECATED,
'str_contains(): Passing null to parameter #2 ($needle) of type string is deprecated',
'/home/user/laravel/routes/web.php',
17
);
}

public function testUserDeprecations()
{
$logger = m::mock(LogManager::class);
$this->container->instance('log', $logger);
$logger->shouldReceive('channel')->with('deprecations')->andReturnSelf();
$logger->shouldReceive('warning')->with(sprintf('%s in %s on line %s',
'str_contains(): Passing null to parameter #2 ($needle) of type string is deprecated',
'/home/user/laravel/routes/web.php',
17
));

$this->handleError(
E_USER_DEPRECATED,
'str_contains(): Passing null to parameter #2 ($needle) of type string is deprecated',
'/home/user/laravel/routes/web.php',
17
);
}

public function testErrors()
{
$logger = m::mock(LogManager::class);
$this->container->instance('log', $logger);
$logger->shouldNotReceive('channel');
$logger->shouldNotReceive('warning');

$this->expectException(ErrorException::class);
$this->expectExceptionMessage('Something went wrong');

$this->handleError(
E_ERROR,
'Something went wrong',
'/home/user/laravel/src/Providers/AppServiceProvider.php',
17
);
}

public function testEnsuresDeprecationsDriver()
{
$logger = m::mock(LogManager::class);
$this->container->instance('log', $logger);
$logger->shouldReceive('channel')->andReturnSelf();
$logger->shouldReceive('warning');

$this->config->set('logging.channels.stack', [
'driver' => 'stack',
'channels' => ['single'],
'ignore_exceptions' => false,
]);
$this->config->set('logging.deprecations', 'stack');

$this->handleError(
E_USER_DEPRECATED,
'str_contains(): Passing null to parameter #2 ($needle) of type string is deprecated',
'/home/user/laravel/routes/web.php',
17
);

$this->assertEquals(
[
'driver' => 'stack',
'channels' => ['single'],
'ignore_exceptions' => false,
],
$this->config->get('logging.channels.deprecations')
);
}

public function testEnsuresNullDeprecationsDriver()
{
$logger = m::mock(LogManager::class);
$this->container->instance('log', $logger);
$logger->shouldReceive('channel')->andReturnSelf();
$logger->shouldReceive('warning');

$this->config->set('logging.channels.null', [
'driver' => 'monolog',
'handler' => NullHandler::class,
]);

$this->handleError(
E_USER_DEPRECATED,
'str_contains(): Passing null to parameter #2 ($needle) of type string is deprecated',
'/home/user/laravel/routes/web.php',
17
);

$this->assertEquals(
NullHandler::class,
$this->config->get('logging.channels.deprecations.handler')
);
}

public function testNoDeprecationsDriverIfNoDeprecationsHereSend()
{
$this->assertEquals(null, $this->config->get('logging.deprecations'));
$this->assertEquals(null, $this->config->get('logging.channels.deprecations'));
}

public function testIgnoreDeprecationIfLoggerUnresolvable()
{
$this->handleError(
E_DEPRECATED,
'str_contains(): Passing null to parameter #2 ($needle) of type string is deprecated',
'/home/user/laravel/routes/web.php',
17
);
}

protected function make($abstract, array $parameters = [])
{
return $this->container->make($abstract, $parameters);
}
}