Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[5.4] JsonResponse unsupported type error handling if flag set #18917

Merged
merged 1 commit into from
Apr 26, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 25 additions & 1 deletion src/Illuminate/Http/JsonResponse.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ public function setData($data = [])
$this->data = json_encode($data, $this->encodingOptions);
}

if (JSON_ERROR_NONE !== json_last_error()) {
if ($this->hasJsonError(json_last_error())) {
throw new InvalidArgumentException(json_last_error_msg());
}

Expand All @@ -83,4 +83,28 @@ public function setEncodingOptions($options)

return $this->setData($this->getData());
}

/**
* Checks the JSON encoding option is set.
*
* @param int $option
* @return bool
*/
public function isEncodingOptionSet($option)
{
return (bool) ($this->encodingOptions & $option);
}

/**
* Checks if error happened during json_encode.
*
* @param int $jsonError
* @return bool
*/
protected function hasJsonError($jsonError)
{
return $jsonError !== JSON_ERROR_NONE &&
($jsonError !== JSON_ERROR_UNSUPPORTED_TYPE ||
! $this->isEncodingOptionSet(JSON_PARTIAL_OUTPUT_ON_ERROR));
}
}
19 changes: 19 additions & 0 deletions tests/Http/HttpJsonResponseTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,25 @@ public function testSetAndRetrieveStatusCode()
$response->setStatusCode(404);
$this->assertSame(404, $response->getStatusCode());
}

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

public function testJsonErrorResourceWithPartialOutputOnError()
{
$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);
}
}

class JsonResponseTestJsonableObject implements Jsonable
Expand Down