Browse Source

Merge pull request #11518 from cakephp/bugfix/php7exceptions

Fix PHP7 error handler compatibility.
Mark Sch 8 years ago
parent
commit
4b10e9c559

+ 10 - 6
src/Error/Middleware/ErrorHandlerMiddleware.php

@@ -19,7 +19,9 @@ use Cake\Core\Configure;
 use Cake\Core\Exception\Exception as CakeException;
 use Cake\Core\InstanceConfigTrait;
 use Cake\Error\ExceptionRenderer;
+use Cake\Error\PHP7ErrorException;
 use Cake\Log\Log;
+use Error;
 use Exception;
 use Throwable;
 
@@ -155,6 +157,11 @@ class ErrorHandlerMiddleware
             $this->exceptionRenderer = $this->getConfig('exceptionRenderer') ?: ExceptionRenderer::class;
         }
 
+        // For PHP5 backwards compatibility
+        if ($exception instanceof Error) {
+            $exception = new PHP7ErrorException($exception);
+        }
+
         if (is_string($this->exceptionRenderer)) {
             $class = App::className($this->exceptionRenderer, 'Error');
             if (!$class) {
@@ -184,12 +191,9 @@ class ErrorHandlerMiddleware
             return;
         }
 
-        $skipLog = $this->getConfig('skipLog');
-        if ($skipLog) {
-            foreach ((array)$skipLog as $class) {
-                if ($exception instanceof $class) {
-                    return;
-                }
+        foreach ((array)$this->getConfig('skipLog') as $class) {
+            if ($exception instanceof $class) {
+                return;
             }
         }
 

+ 19 - 0
tests/TestCase/Error/Middleware/ErrorHandlerMiddlewareTest.php

@@ -19,6 +19,7 @@ use Cake\Http\Response;
 use Cake\Http\ServerRequestFactory;
 use Cake\Log\Log;
 use Cake\TestSuite\TestCase;
+use Error;
 use LogicException;
 use Psr\Log\LoggerInterface;
 
@@ -147,6 +148,24 @@ class ErrorHandlerMiddlewareTest extends TestCase
     }
 
     /**
+     * Test handling PHP 7's Error instance.
+     *
+     * @return void
+     */
+    public function testHandlePHP7Error()
+    {
+        $this->skipIf(version_compare(PHP_VERSION, '7.0.0', '<'), 'Error class only exists since PHP 7.');
+
+        $middleware = new ErrorHandlerMiddleware();
+        $request = ServerRequestFactory::fromGlobals();
+        $response = new Response();
+        $error = new Error();
+
+        $result = $middleware->handleException($error, $request, $response);
+        $this->assertInstanceOf(Response::class, $result);
+    }
+
+    /**
      * Test rendering an error page logs errors
      *
      * @return void