10000 [9.x] Cast Stringable to string when used with json_encode() (#35680) · laravel/framework@840166a · GitHub
[go: up one dir, main page]

Skip to content

Commit 840166a

Browse files
crynobonetaylorotwellantonkomarev
authored
[9.x] Cast Stringable to string when used with json_encode() (#35680)
* [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>
1 parent d6059bb commit 840166a

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

src/Illuminate/Support/Stringable.php

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,10 @@
44

55
use Closure;
66
use Illuminate\Support\Traits\Macroable;
7+
use JsonSerializable;
78
use Symfony\Component\VarDumper\VarDumper;
89

9-
class Stringable
10+
class Stringable implements JsonSerializable
1011
{
1112
use Macroable;
1213

@@ -722,6 +723,16 @@ public function dd()
722723
exit(1);
723724
}
724725

726+
/**
727+
* Convert the object into something JSON serializable.
728+
*
729+
* @return string
730+
*/
731+
public function jsonSerialize()
732+
{
733+
return $this->__toString();
734+
}
735+
725736
/**
726737
* Proxy dynamic properties onto methods.
727738
*

tests/Support/SupportStringableTest.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -545,4 +545,11 @@ public function testChunk()
545545
$this->assertInstanceOf(Collection::class, $chunks);
546546
$this->assertSame(['foo', 'bar', 'baz'], $chunks->all());
547547
}
548+
549+
public function testJsonSerializable()
550+
{
551+
$this->assertSame('"laravel-php-framework"', json_encode($this->stringable('LaravelPhpFramework')->kebab()));
552+
$this->assertSame('["laravel-php-framework"]', json_encode([$this->stringable('LaravelPhpFramework')->kebab()]));
553+
$this->assertSame('{"title":"laravel-php-framework"}', json_encode(['title' => $this->stringable('LaravelPhpFramework')->kebab()]));
554+
}
548555
}

0 commit comments

Comments
 (0)
0