Skip to content

Commit

Permalink
improve json-encodability of Route::$exception
Browse files Browse the repository at this point in the history
  • Loading branch information
Paul M. Jones committed Oct 22, 2022
1 parent e8ba799 commit 45da94d
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 3 deletions.
6 changes: 4 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand All @@ -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"
}
}
9 changes: 8 additions & 1 deletion src/Route.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
namespace AutoRoute;

use JsonSerializable;
use pmjones\ThrowableProperties;
use Throwable;

/**
Expand Down Expand Up @@ -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;
}
}
20 changes: 20 additions & 0 deletions tests/RouteTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@

namespace AutoRoute;

use LogicException;

class RouteTest extends \PHPUnit\Framework\TestCase
{
public function testAsArray()
Expand Down Expand Up @@ -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);
}
}

0 comments on commit 45da94d

Please sign in to comment.