Browse Source

Add native type hints for Error

Corey Taylor 4 years ago
parent
commit
b20cfea7e4

+ 2 - 2
src/Error/BaseErrorHandler.php

@@ -281,7 +281,7 @@ abstract class BaseErrorHandler
      * @param array $data Array of error data.
      * @return bool
      */
-    protected function _logError($level, array $data): bool
+    protected function _logError(string|int $level, array $data): bool
     {
         $message = sprintf(
             '%s (%s): %s in [%s, line %s]',
@@ -324,7 +324,7 @@ abstract class BaseErrorHandler
      *
      * @return \Cake\Error\ErrorLoggerInterface
      */
-    public function getLogger()
+    public function getLogger(): ErrorLoggerInterface
     {
         if ($this->logger === null) {
             /** @var \Cake\Error\ErrorLoggerInterface $logger */

+ 2 - 2
src/Error/Debug/ArrayItemNode.php

@@ -48,7 +48,7 @@ class ArrayItemNode implements NodeInterface
      *
      * @return \Cake\Error\Debug\NodeInterface
      */
-    public function getValue()
+    public function getValue(): NodeInterface
     {
         return $this->value;
     }
@@ -58,7 +58,7 @@ class ArrayItemNode implements NodeInterface
      *
      * @return \Cake\Error\Debug\NodeInterface
      */
-    public function getKey()
+    public function getKey(): NodeInterface
     {
         return $this->key;
     }

+ 1 - 1
src/Error/Debug/ConsoleFormatter.php

@@ -183,7 +183,7 @@ class ConsoleFormatter implements FormatterInterface
      * @return string
      * @see \Cake\Error\Debugger::exportVar()
      */
-    protected function exportObject($var, int $indent): string
+    protected function exportObject(ClassNode|ReferenceNode $var, int $indent): string
     {
         $props = [];
 

+ 1 - 1
src/Error/Debug/DebugContext.php

@@ -59,7 +59,7 @@ class DebugContext
      *
      * @return static
      */
-    public function withAddedDepth()
+    public function withAddedDepth(): static
     {
         $new = clone $this;
         $new->depth += 1;

+ 1 - 1
src/Error/Debug/HtmlFormatter.php

@@ -193,7 +193,7 @@ class HtmlFormatter implements FormatterInterface
      * @return string
      * @see \Cake\Error\Debugger::exportVar()
      */
-    protected function exportObject($var, int $indent): string
+    protected function exportObject(ClassNode|ReferenceNode $var, int $indent): string
     {
         $objectId = "cake-db-object-{$this->id}-{$var->getId()}";
         $out = sprintf(

+ 1 - 1
src/Error/Debug/NodeInterface.php

@@ -35,5 +35,5 @@ interface NodeInterface
      *
      * @return mixed
      */
-    public function getValue();
+    public function getValue(): mixed;
 }

+ 4 - 4
src/Error/Debug/ScalarNode.php

@@ -27,7 +27,7 @@ class ScalarNode implements NodeInterface
     private $type;
 
     /**
-     * @var string|float|int|bool|null
+     * @var resource|string|float|int|bool|null
      */
     private $value;
 
@@ -35,7 +35,7 @@ class ScalarNode implements NodeInterface
      * Constructor
      *
      * @param string $type The type of scalar value.
-     * @param string|float|int|bool|null $value The wrapped value.
+     * @param resource|string|float|int|bool|null $value The wrapped value.
      */
     public function __construct(string $type, $value)
     {
@@ -56,9 +56,9 @@ class ScalarNode implements NodeInterface
     /**
      * Get the value
      *
-     * @return string|float|int|bool|null
+     * @return resource|string|float|int|bool|null
      */
-    public function getValue()
+    public function getValue(): mixed
     {
         return $this->value;
     }

+ 1 - 1
src/Error/Debug/TextFormatter.php

@@ -127,7 +127,7 @@ TEXT;
      * @return string
      * @see \Cake\Error\Debugger::exportVar()
      */
-    protected function exportObject($var, int $indent): string
+    protected function exportObject(ClassNode|ReferenceNode $var, int $indent): string
     {
         $out = '';
         $props = [];

+ 13 - 17
src/Error/Debugger.php

@@ -196,7 +196,7 @@ class Debugger
      * @param string|null $class Class name.
      * @return static
      */
-    public static function getInstance(?string $class = null)
+    public static function getInstance(?string $class = null): static
     {
         static $instance = [];
         if (!empty($class)) {
@@ -220,7 +220,7 @@ class Debugger
      * @return mixed Config value being read, or the object itself on write operations.
      * @throws \Cake\Core\Exception\CakeException When trying to set a key that is invalid.
      */
-    public static function configInstance($key = null, $value = null, bool $merge = true)
+    public static function configInstance(array|string|null $key = null, mixed $value = null, bool $merge = true): mixed
     {
         if ($key === null) {
             return static::getInstance()->getConfig($key);
@@ -270,13 +270,9 @@ class Debugger
      * @param \Closure|string $template The string template or closure
      * @return void
      */
-    public static function addEditor(string $name, $template): void
+    public static function addEditor(string $name, Closure|string $template): void
     {
         $instance = static::getInstance();
-        if (!is_string($template) && !($template instanceof Closure)) {
-            $type = get_debug_type($template);
-            throw new RuntimeException("Invalid editor type of `{$type}`. Expected string or Closure.");
-        }
         $instance->editors[$name] = $template;
     }
 
@@ -328,7 +324,7 @@ class Debugger
      * @see \Cake\Error\Debugger::exportVar()
      * @link https://book.cakephp.org/4/en/development/debugging.html#outputting-values
      */
-    public static function dump($var, int $maxDepth = 3): void
+    public static function dump(mixed $var, int $maxDepth = 3): void
     {
         pr(static::exportVar($var, $maxDepth));
     }
@@ -342,7 +338,7 @@ class Debugger
      * @param int $maxDepth The depth to output to. Defaults to 3.
      * @return void
      */
-    public static function log($var, $level = 'debug', int $maxDepth = 3): void
+    public static function log(mixed $var, string|int $level = 'debug', int $maxDepth = 3): void
     {
         /** @var string $source */
         $source = static::trace(['start' => 1]);
@@ -370,7 +366,7 @@ class Debugger
      * @return array|string Formatted stack trace.
      * @link https://book.cakephp.org/4/en/development/debugging.html#generating-stack-traces
      */
-    public static function trace(array $options = [])
+    public static function trace(array $options = []): array|string
     {
         return Debugger::formatTrace(debug_backtrace(), $options);
     }
@@ -392,7 +388,7 @@ class Debugger
      * @return array|string Formatted stack trace.
      * @link https://book.cakephp.org/4/en/development/debugging.html#generating-stack-traces
      */
-    public static function formatTrace($backtrace, array $options = [])
+    public static function formatTrace(Throwable|array $backtrace, array $options = []): array|string
     {
         if ($backtrace instanceof Throwable) {
             $backtrace = $backtrace->getTrace();
@@ -621,7 +617,7 @@ class Debugger
      * @param int $maxDepth The depth to output to. Defaults to 3.
      * @return string Variable as a formatted string
      */
-    public static function exportVar($var, int $maxDepth = 3): string
+    public static function exportVar(mixed $var, int $maxDepth = 3): string
     {
         $context = new DebugContext($maxDepth);
         $node = static::export($var, $context);
@@ -636,7 +632,7 @@ class Debugger
      * @param int $maxDepth The depth to output to. Defaults to 3.
      * @return string Variable as a string
      */
-    public static function exportVarAsPlainText($var, int $maxDepth = 3): string
+    public static function exportVarAsPlainText(mixed $var, int $maxDepth = 3): string
     {
         return (new TextFormatter())->dump(
             static::export($var, new DebugContext($maxDepth))
@@ -653,7 +649,7 @@ class Debugger
      * @param int $maxDepth The depth to generate nodes to. Defaults to 3.
      * @return \Cake\Error\Debug\NodeInterface The root node of the tree.
      */
-    public static function exportVarAsNodes($var, int $maxDepth = 3): NodeInterface
+    public static function exportVarAsNodes(mixed $var, int $maxDepth = 3): NodeInterface
     {
         return static::export($var, new DebugContext($maxDepth));
     }
@@ -665,7 +661,7 @@ class Debugger
      * @param \Cake\Error\Debug\DebugContext $context Dump context
      * @return \Cake\Error\Debug\NodeInterface The dumped variable.
      */
-    protected static function export($var, DebugContext $context): NodeInterface
+    protected static function export(mixed $var, DebugContext $context): NodeInterface
     {
         $type = static::getType($var);
 
@@ -997,7 +993,7 @@ class Debugger
      * @param mixed $var The variable to get the type of.
      * @return string The type of variable.
      */
-    public static function getType($var): string
+    public static function getType(mixed $var): string
     {
         $type = get_debug_type($var);
 
@@ -1024,7 +1020,7 @@ class Debugger
      *    environment conditions.
      * @return void
      */
-    public static function printVar($var, array $location = [], ?bool $showHtml = null): void
+    public static function printVar(mixed $var, array $location = [], ?bool $showHtml = null): void
     {
         $location += ['file' => null, 'line' => null];
         if ($location['file']) {

+ 2 - 1
src/Error/ErrorHandler.php

@@ -19,6 +19,7 @@ declare(strict_types=1);
 namespace Cake\Error;
 
 use Cake\Core\App;
+use Cake\Http\Response;
 use Cake\Http\ResponseEmitter;
 use Cake\Routing\Router;
 use Psr\Http\Message\ServerRequestInterface;
@@ -202,7 +203,7 @@ class ErrorHandler extends BaseErrorHandler
      * @param \Cake\Http\Response|string $response Either the message or response object.
      * @return void
      */
-    protected function _sendResponse($response): void
+    protected function _sendResponse(Response|string $response): void
     {
         if (is_string($response)) {
             echo $response;

+ 1 - 1
src/Error/ErrorLoggerInterface.php

@@ -47,5 +47,5 @@ interface ErrorLoggerInterface
      * @param array $context Context.
      * @return bool
      */
-    public function logMessage($level, string $message, array $context = []): bool;
+    public function logMessage(string|int $level, string $message, array $context = []): bool;
 }

+ 1 - 9
src/Error/Middleware/ErrorHandlerMiddleware.php

@@ -23,7 +23,6 @@ use Cake\Error\ErrorHandler;
 use Cake\Error\ExceptionRenderer;
 use Cake\Http\Exception\RedirectException;
 use Cake\Http\Response;
-use InvalidArgumentException;
 use Laminas\Diactoros\Response\RedirectResponse;
 use Psr\Http\Message\ResponseInterface;
 use Psr\Http\Message\ServerRequestInterface;
@@ -82,7 +81,7 @@ class ErrorHandlerMiddleware implements MiddlewareInterface
      *  or config array.
      * @throws \InvalidArgumentException
      */
-    public function __construct($errorHandler = [])
+    public function __construct(ErrorHandler|array $errorHandler = [])
     {
         if (Configure::read('debug')) {
             ini_set('zend.exception_ignore_args', '0');
@@ -94,13 +93,6 @@ class ErrorHandlerMiddleware implements MiddlewareInterface
             return;
         }
 
-        if (!$errorHandler instanceof ErrorHandler) {
-            throw new InvalidArgumentException(sprintf(
-                '$errorHandler argument must be a config array or ErrorHandler instance. Got `%s` instead.',
-                get_debug_type($errorHandler)
-            ));
-        }
-
         $this->errorHandler = $errorHandler;
     }
 

+ 0 - 9
tests/TestCase/Error/DebuggerTest.php

@@ -881,15 +881,6 @@ EXPECTED;
     }
 
     /**
-     * test adding invalid editor
-     */
-    public function testAddEditorInvalid(): void
-    {
-        $this->expectException(RuntimeException::class);
-        Debugger::addEditor('nope', ['invalid']);
-    }
-
-    /**
      * test choosing an unknown editor
      */
     public function testSetEditorInvalid(): void

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

@@ -27,7 +27,6 @@ use Cake\Http\ServerRequestFactory;
 use Cake\Log\Log;
 use Cake\TestSuite\TestCase;
 use Error;
-use InvalidArgumentException;
 use LogicException;
 use Psr\Http\Message\ResponseInterface;
 use TestApp\Http\TestRequestHandler;
@@ -68,16 +67,6 @@ class ErrorHandlerMiddlewareTest extends TestCase
     }
 
     /**
-     * Test constructor error
-     */
-    public function testConstructorInvalid(): void
-    {
-        $this->expectException(InvalidArgumentException::class);
-        $this->expectExceptionMessage('$errorHandler argument must be a config array or ErrorHandler');
-        new ErrorHandlerMiddleware('nope');
-    }
-
-    /**
      * Test returning a response works ok.
      */
     public function testNoErrorResponse(): void