Skip to content

Commit

Permalink
[9.x] Cast Stringable to string when used with json_encode() (#35680)
Browse files Browse the repository at this point in the history
* [9.x] Cast Stringable to string when used with json_encode().

Signed-off-by: Mior Muhammad Zaki <crynobone@gmail.com>

* Update src/Illuminate/Support/Stringable.php

Co-authored-by: Anton Komarev <1849174+antonkomarev@users.noreply.github.com>

* Update Stringable.php

Co-authored-by: Taylor Otwell <taylor@laravel.com>
Co-authored-by: Anton Komarev <1849174+antonkomarev@users.noreply.github.com>
  • Loading branch information
3 people authored Dec 20, 2020
1 parent d6059bb commit 840166a
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
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()]));
}
}

0 comments on commit 840166a

Please sign in to comment.