Skip to content

Commit

Permalink
Merge branch 'gracefully-handle-partial-json-errors' of https://githu…
Browse files Browse the repository at this point in the history
…b.com/Jalle19/framework into Jalle19-gracefully-handle-partial-json-errors
  • Loading branch information
taylorotwell committed Mar 9, 2018
2 parents dd83c6c + 01090f7 commit a53f563
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 12 deletions.
21 changes: 18 additions & 3 deletions src/Illuminate/Http/JsonResponse.php
Original file line number Diff line number Diff line change
Expand Up @@ -86,9 +86,24 @@ public function setData($data = [])
*/
protected function hasValidJson($jsonError)
{
return $jsonError === JSON_ERROR_NONE ||
($jsonError === JSON_ERROR_UNSUPPORTED_TYPE &&
$this->hasEncodingOption(JSON_PARTIAL_OUTPUT_ON_ERROR));
// No error is obviously fine
if ($jsonError === JSON_ERROR_NONE) {
return true;
}

// If the JSON_PARTIAL_OUTPUT_ON_ERROR option is set, some additional errors are fine
// (see https://secure.php.net/manual/en/json.constants.php)
if ($this->hasEncodingOption(JSON_PARTIAL_OUTPUT_ON_ERROR)) {
$acceptableErrors = [
JSON_ERROR_RECURSION,
JSON_ERROR_INF_OR_NAN,
JSON_ERROR_UNSUPPORTED_TYPE,
];

return \in_array($jsonError, $acceptableErrors);
}

return false;
}

/**
Expand Down
45 changes: 36 additions & 9 deletions tests/Http/HttpJsonResponseTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -75,22 +75,49 @@ public function testSetAndRetrieveStatusCode()
}

/**
* @param mixed $data
*
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage Type is not supported
*
* @dataProvider jsonErrorDataProvider
*/
public function testJsonErrorResource()
public function testInvalidArgumentExceptionOnJsonError($data)
{
$resource = tmpfile();
$response = new \Illuminate\Http\JsonResponse(['resource' => $resource]);
new \Illuminate\Http\JsonResponse(['data' => $data]);
}

public function testJsonErrorResourceWithPartialOutputOnError()
/**
* @param mixed $data
*
* @dataProvider jsonErrorDataProvider
*/
public function testGracefullyHandledSomeJsonErrorsWithPartialOutputOnError($data)
{
new \Illuminate\Http\JsonResponse(['data' => $data], 200, [], JSON_PARTIAL_OUTPUT_ON_ERROR);
}

/**
* @return array
*/
public function jsonErrorDataProvider()
{
// Resources can't be encoded
$resource = tmpfile();
$response = new \Illuminate\Http\JsonResponse(['resource' => $resource], 200, [], JSON_PARTIAL_OUTPUT_ON_ERROR);
$data = $response->getData();
$this->assertInstanceOf('stdClass', $data);
$this->assertNull($data->resource);

// Recursion can't be encoded
$recursiveObject = new \stdClass();
$objectB = new \stdClass();
$recursiveObject->b = $objectB;
$objectB->a = $recursiveObject;

// NAN or INF can't be encoded
$nan = NAN;

return [
[$resource],
[$recursiveObject],
[$nan],
];
}
}

Expand Down

0 comments on commit a53f563

Please sign in to comment.