Skip to content

Commit f364d7f

Browse files
authored
[8.x] Support JSON encoding Stringable (#36012)
* Support JSON encoding Stringable * Call __toString() from jsonSerialize() in Stringable class * Update router to properly handle Stringable instances
1 parent 52e67dd commit f364d7f

File tree

3 files changed

+20
-1
lines changed

3 files changed

+20
-1
lines changed

src/Illuminate/Routing/Router.php

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
use Illuminate\Routing\Events\RouteMatched;
1919
use Illuminate\Support\Collection;
2020
use Illuminate\Support\Str;
21+
use Illuminate\Support\Stringable;
2122
use Illuminate\Support\Traits\Macroable;
2223
use JsonSerializable;
2324
use Psr\Http\Message\ResponseInterface as PsrResponseInterface;
@@ -769,6 +770,8 @@ public static function toResponse($request, $response)
769770
$response = (new HttpFoundationFactory)->createResponse($response);
770771
} elseif ($response instanceof Model && $response->wasRecentlyCreated) {
771772
$response = new JsonResponse($response, 201);
773+
} elseif ($response instanceof Stringable) {
774+
$response = new Response($response->__toString(), 200, ['Content-Type' => 'text/html']);
772775
} elseif (! $response instanceof SymfonyResponse &&
773776
($response instanceof Arrayable ||
774777
$response instanceof Jsonable ||

src/Illuminate/Support/Stringable.php

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,10 @@
55
use Closure;
66
use Illuminate\Support\Traits\Macroable;
77
use Illuminate\Support\Traits\Tappable;
8+
use JsonSerializable;
89
use Symfony\Component\VarDumper\VarDumper;
910

10-
class Stringable
11+
class Stringable implements JsonSerializable
1112
{
1213
use Macroable, Tappable;
1314

@@ -734,6 +735,16 @@ public function dd()
734735
exit(1);
735736
}
736737

738+
/**
739+
* Convert the object to a string when JSON encoded.
740+
*
741+
* @return string
742+
*/
743+
public function jsonSerialize()
744+
{
745+
return $this->__toString();
746+
}
747+
737748
/**
738749
* Proxy dynamic properties onto methods.
739750
*

tests/Support/SupportStringableTest.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -546,6 +546,11 @@ public function testChunk()
546546
$this->assertSame(['foo', 'bar', 'baz'], $chunks->all());
547547
}
548548

549+
public function testJsonSerialize()
550+
{
551+
$this->assertSame('"foo"', json_encode($this->stringable('foo')));
552+
}
553+
549554
public function testTap()
550555
{
551556
$stringable = $this->stringable('foobarbaz');

0 commit comments

Comments
 (0)