Skip to content

Commit 908a2fe

Browse files
author
Szekeres Bálint
committed
hasJsonError() in JsonResponse
+ handling JSON_PARTIAL_OUTPUT_ON_ERROR flag (e.g. w/ resource)
1 parent f3a6039 commit 908a2fe

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed

src/Illuminate/Http/JsonResponse.php

+25-1
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ public function setData($data = [])
6767
$this->data = json_encode($data, $this->encodingOptions);
6868
}
6969

70-
if (JSON_ERROR_NONE !== json_last_error()) {
70+
if ($this->hasJsonError(json_last_error())) {
7171
throw new InvalidArgumentException(json_last_error_msg());
7272
}
7373

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

8484
return $this->setData($this->getData());
8585
}
86+
87+
/**
88+
* Checks the JSON encoding option is set.
89+
*
90+
* @param int $option
91+
* @return bool
92+
*/
93+
public function isEncodingOptionSet($option)
94+
{
95+
return (bool) ($this->encodingOptions & $option);
96+
}
97+
98+
/**
99+
* Checks if error happened during json_encode.
100+
*
101+
* @param int $jsonError
102+
* @return bool
103+
*/
104+
protected function hasJsonError($jsonError)
105+
{
106+
return $jsonError !== JSON_ERROR_NONE &&
107+
($jsonError !== JSON_ERROR_UNSUPPORTED_TYPE ||
108+
! $this->isEncodingOptionSet(JSON_PARTIAL_OUTPUT_ON_ERROR));
109+
}
86110
}

tests/Http/HttpJsonResponseTest.php

+19
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,25 @@ public function testSetAndRetrieveStatusCode()
7373
$response->setStatusCode(404);
7474
$this->assertSame(404, $response->getStatusCode());
7575
}
76+
77+
/**
78+
* @expectedException \InvalidArgumentException
79+
* @expectedExceptionMessage Type is not supported
80+
*/
81+
public function testJsonErrorResource()
82+
{
83+
$resource = tmpfile();
84+
$response = new \Illuminate\Http\JsonResponse(['resource' => $resource]);
85+
}
86+
87+
public function testJsonErrorResourceWithPartialOutputOnError()
88+
{
89+
$resource = tmpfile();
90+
$response = new \Illuminate\Http\JsonResponse(['resource' => $resource], 200, [], JSON_PARTIAL_OUTPUT_ON_ERROR);
91+
$data = $response->getData();
92+
$this->assertInstanceOf('StdClass', $data);
93+
$this->assertNull($data->resource);
94+
}
7695
}
7796

7897
class JsonResponseTestJsonableObject implements Jsonable

0 commit comments

Comments
 (0)