Skip to content

Commit 08167e8

Browse files
driesvintsStyleCIBottaylorotwell
authored
[8.x] Fix json_last_error issue with setData (#42125)
* Fix json_last_error issue with setData * Apply fixes from StyleCI * Update JsonResponse.php Co-authored-by: StyleCI Bot <[email protected]> Co-authored-by: Taylor Otwell <[email protected]>
1 parent d363435 commit 08167e8

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

src/Illuminate/Http/JsonResponse.php

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,9 @@ public function setData($data = [])
7474
{
7575
$this->original = $data;
7676

77+
// Ensure json_last_error() is cleared...
78+
json_decode('[]');
79+
7780
if ($data instanceof Jsonable) {
7881
$this->data = $data->toJson($this->encodingOptions);
7982
} elseif ($data instanceof JsonSerializable) {

tests/Integration/Http/JsonResponseTest.php

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
namespace Illuminate\Tests\Integration\Http;
44

5+
use Illuminate\Contracts\Support\Jsonable;
56
use Illuminate\Http\JsonResponse;
67
use Illuminate\Support\Facades\Route;
78
use Orchestra\Testbench\TestCase;
@@ -27,4 +28,22 @@ public function jsonSerialize(): string
2728

2829
$this->get('/response');
2930
}
31+
32+
public function testResponseSetDataPassesWithPriorJsonErrors()
33+
{
34+
$response = new JsonResponse();
35+
36+
// Trigger json_last_error() to have a non-zero value...
37+
json_encode(['a' => acos(2)]);
38+
39+
$response->setData(new class implements Jsonable
40+
{
41+
public function toJson($options = 0): string
42+
{
43+
return '{}';
44+
}
45+
});
46+
47+
$this->assertJson($response->getContent());
48+
}
3049
}

0 commit comments

Comments
 (0)