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

[9.x] Cast Stringable to string when used with json_encode() #35680

Merged
merged 3 commits into from
Dec 20, 2020
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
13 changes: 12 additions & 1 deletion src/Illuminate/Support/Stringable.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@

use Closure;
use Illuminate\Support\Traits\Macroable;
use JsonSerializable;
use Symfony\Component\VarDumper\VarDumper;

class Stringable
class Stringable implements JsonSerializable
{
use Macroable;

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

/**
* Convert the object into something JSON serializable.
*
* @return string
*/
public function jsonSerialize()
{
return $this->__toString();
}

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

public function testJsonSerializable()
{
$this->assertSame('"laravel-php-framework"', json_encode($this->stringable('LaravelPhpFramework')->kebab()));
$this->assertSame('["laravel-php-framework"]', json_encode([$this->stringable('LaravelPhpFramework')->kebab()]));
$this->assertSame('{"title":"laravel-php-framework"}', json_encode(['title' => $this->stringable('LaravelPhpFramework')->kebab()]));
}
}