Skip to content

Commit

Permalink
[8.x] Fix json_last_error issue with setData (#42125)
Browse files Browse the repository at this point in the history
* 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]>
  • Loading branch information
3 people authored Apr 25, 2022
1 parent d363435 commit 08167e8
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/Illuminate/Http/JsonResponse.php
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,9 @@ public function setData($data = [])
{
$this->original = $data;

// Ensure json_last_error() is cleared...
json_decode('[]');

if ($data instanceof Jsonable) {
$this->data = $data->toJson($this->encodingOptions);
} elseif ($data instanceof JsonSerializable) {
Expand Down
19 changes: 19 additions & 0 deletions tests/Integration/Http/JsonResponseTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Illuminate\Tests\Integration\Http;

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

$this->get('/response');
}

public function testResponseSetDataPassesWithPriorJsonErrors()
{
$response = new JsonResponse();

// Trigger json_last_error() to have a non-zero value...
json_encode(['a' => acos(2)]);

$response->setData(new class implements Jsonable
{
public function toJson($options = 0): string
{
return '{}';
}
});

$this->assertJson($response->getContent());
}
}

0 comments on commit 08167e8

Please sign in to comment.