From 45da94d85d48032477fdc09f5eba35abed31d949 Mon Sep 17 00:00:00 2001 From: "Paul M. Jones" Date: Fri, 21 Oct 2022 21:47:33 -0500 Subject: [PATCH] improve json-encodability of Route::$exception --- composer.json | 6 ++++-- src/Route.php | 9 ++++++++- tests/RouteTest.php | 20 ++++++++++++++++++++ 3 files changed, 32 insertions(+), 3 deletions(-) diff --git a/composer.json b/composer.json index 57013db..470d2b2 100644 --- a/composer.json +++ b/composer.json @@ -7,7 +7,8 @@ "license": "MIT", "require": { "php": "^8.0", - "psr/log": "^3.0" + "psr/log": "^3.0", + "pmjones/throwable-properties": "^1.0" }, "autoload": { "psr-4": { @@ -29,6 +30,7 @@ ], "scripts": { "test": "./vendor/bin/phpunit", - "stan": "./vendor/bin/phpstan analyze -c phpstan.neon src" + "stan": "./vendor/bin/phpstan analyze -c phpstan.neon src", + "testan": "composer test && composer stan" } } diff --git a/src/Route.php b/src/Route.php index 4c48457..392e86e 100644 --- a/src/Route.php +++ b/src/Route.php @@ -11,6 +11,7 @@ namespace AutoRoute; use JsonSerializable; +use pmjones\ThrowableProperties; use Throwable; /** @@ -47,6 +48,12 @@ public function asArray() : array public function jsonSerialize() : mixed { - return get_object_vars($this); + $array = $this->asArray(); + + if ($array['exception'] !== null) { + $array['exception'] = new ThrowableProperties($array['exception']); + } + + return $array; } } diff --git a/tests/RouteTest.php b/tests/RouteTest.php index 6071788..8ec6b15 100644 --- a/tests/RouteTest.php +++ b/tests/RouteTest.php @@ -3,6 +3,8 @@ namespace AutoRoute; +use LogicException; + class RouteTest extends \PHPUnit\Framework\TestCase { public function testAsArray() @@ -32,4 +34,22 @@ public function testAsArray() $actual = json_encode($route); $this->assertSame($expect, $actual); } + + public function testJsonEncode() + { + $route = new Route( + 'FooClass', + '__invoke', + ['arg0', 'arg1'], + LogicException::CLASS, + new LogicException('fake message', 88), + ); + + $actual = json_decode(json_encode($route)); + $this->assertSame('FooClass', $actual->class); + $this->assertSame('__invoke', $actual->method); + $this->assertSame(['arg0', 'arg1'], $actual->arguments); + $this->assertSame(LogicException::CLASS, $actual->error); + $this->assertSame(LogicException::CLASS, $actual->exception->class); + } }