diff --git a/src/Illuminate/Support/Stringable.php b/src/Illuminate/Support/Stringable.php index b0f194fa6e0b..c18ef686fa0a 100644 --- a/src/Illuminate/Support/Stringable.php +++ b/src/Illuminate/Support/Stringable.php @@ -1194,6 +1194,30 @@ public function whenIsAscii($callback, $default = null) return $this->when($this->isAscii(), $callback, $default); } + /** + * Execute the given callback if the string is a valid JSON string. + * + * @param callable $callback + * @param callable|null $default + * @return static + */ + public function whenJson($callback, $default = null) + { + return $this->when($this->isJson(), $callback, $default); + } + + /** + * Execute the given callback if the string is not a valid JSON string. + * + * @param callable $callback + * @param callable|null $default + * @return static + */ + public function whenNotJson($callback, $default = null) + { + return $this->when(! $this->isJson(), $callback, $default); + } + /** * Execute the given callback if the string is a valid UUID. * diff --git a/tests/Support/SupportStringableTest.php b/tests/Support/SupportStringableTest.php index c6fb80f01ddf..c98e39912ed6 100644 --- a/tests/Support/SupportStringableTest.php +++ b/tests/Support/SupportStringableTest.php @@ -350,6 +350,32 @@ public function testWhenIsAscii() })); } + public function testWhenJson() + { + $this->assertSame('JSON: 1', (string) $this->stringable('1')->whenJson(function ($stringable) { + return $stringable->prepend('JSON: '); + }, function ($stringable) { + return $stringable->prepend('Not JSON: '); + })); + + $this->assertSame('Not JSON: 1,', (string) $this->stringable('1,')->whenJson(function ($stringable) { + return $stringable->prepend('JSON: '); + }, function ($stringable) { + return $stringable->prepend('Not JSON: '); + })); + } + + public function testWhenNotJson() + { + $this->assertSame('[1,2,3]', (string) $this->stringable('[1,2,3]')->whenNotJson(function ($stringable) { + return $stringable.' JSON'; + })); + + $this->assertSame('Not JSON', (string) $this->stringable('Not')->whenNotJson(function ($stringable) { + return $stringable.' JSON'; + })); + } + public function testWhenIsUuid() { $this->assertSame('Uuid: 2cdc7039-65a6-4ac7-8e5d-d554a98e7b15', (string) $this->stringable('2cdc7039-65a6-4ac7-8e5d-d554a98e7b15')->whenIsUuid(function ($stringable) {