Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[8.x] Support JSON encoding Stringable #36012

Merged
merged 4 commits into from
Jan 25, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/Illuminate/Routing/Router.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
use Illuminate\Routing\Events\RouteMatched;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
use Illuminate\Support\Traits\Macroable;
use JsonSerializable;
use Psr\Http\Message\ResponseInterface as PsrResponseInterface;
Expand Down Expand Up @@ -769,6 +770,8 @@ public static function toResponse($request, $response)
$response = (new HttpFoundationFactory)->createResponse($response);
} elseif ($response instanceof Model && $response->wasRecentlyCreated) {
$response = new JsonResponse($response, 201);
} elseif ($response instanceof Stringable) {
$response = new Response($response->__toString(), 200, ['Content-Type' => 'text/html']);
GrahamCampbell marked this conversation as resolved.
Show resolved Hide resolved
} elseif (! $response instanceof SymfonyResponse &&
($response instanceof Arrayable ||
$response instanceof Jsonable ||
Expand Down
13 changes: 12 additions & 1 deletion src/Illuminate/Support/Stringable.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@
use Closure;
use Illuminate\Support\Traits\Macroable;
use Illuminate\Support\Traits\Tappable;
use JsonSerializable;
use Symfony\Component\VarDumper\VarDumper;

class Stringable
class Stringable implements JsonSerializable
{
use Macroable, Tappable;

Expand Down Expand Up @@ -734,6 +735,16 @@ public function dd()
exit(1);
}

/**
* Convert the object to a string when JSON encoded.
*
* @return string
*/
public function jsonSerialize()
{
return $this->__toString();
}

/**
* Proxy dynamic properties onto methods.
*
Expand Down
5 changes: 5 additions & 0 deletions tests/Support/SupportStringableTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -546,6 +546,11 @@ public function testChunk()
$this->assertSame(['foo', 'bar', 'baz'], $chunks->all());
}

public function testJsonSerialize()
{
$this->assertSame('"foo"', json_encode($this->stringable('foo')));
}

public function testTap()
{
$stringable = $this->stringable('foobarbaz');
Expand Down