Skip to content

Commit e080bde

Browse files
committed
add json encode method
1 parent 7a5ef5f commit e080bde

File tree

1 file changed

+32
-2
lines changed

1 file changed

+32
-2
lines changed

src/Response.php

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
use PhpRestfulApiResponse\Contracts\PhpRestfulApiResponse;
1717
use Zend\Diactoros\MessageTrait;
1818
use InvalidArgumentException;
19+
use Zend\Diactoros\Response\JsonResponse;
1920

2021
class Response implements PhpRestfulApiResponse
2122
{
@@ -176,7 +177,7 @@ public function withArray($data, $code = 200, array $headers = [])
176177
{
177178
$new = clone $this;
178179
$new->setStatusCode($code);
179-
$new->getBody()->write(json_encode($data));
180+
$new->getBody()->write($this->jsonEncode($data));
180181
$new = $new->withHeader('Content-Type', 'application/json');
181182
$new->headers = array_merge($new->headers, $headers);
182183
return $new;
@@ -250,7 +251,7 @@ public function withError($message, int $statusCode, $errorCode = null, array $h
250251
$new->setStatusCode($statusCode);
251252
$new->setErrorCode($errorCode);
252253
$new->getBody()->write(
253-
json_encode(
254+
$this->jsonEncode(
254255
[
255256
'error' => array_filter([
256257
'http_code' => $new->statusCode,
@@ -420,4 +421,33 @@ private function setStatusCode(int $statusCode)
420421
}
421422
$this->statusCode = $statusCode;
422423
}
424+
425+
/**
426+
* Encode the provided data to JSON.
427+
*
428+
* @param mixed $data
429+
* @return string
430+
* @throws InvalidArgumentException if unable to encode the $data to JSON.
431+
*/
432+
private function jsonEncode($data)
433+
{
434+
if (is_resource($data)) {
435+
throw new InvalidArgumentException('Cannot JSON encode resources');
436+
}
437+
438+
// Clear json_last_error()
439+
json_encode(null);
440+
441+
$json = json_encode($data, JsonResponse::DEFAULT_JSON_FLAGS);
442+
443+
if (JSON_ERROR_NONE !== json_last_error()) {
444+
throw new InvalidArgumentException(sprintf(
445+
'Unable to encode data to JSON in %s: %s',
446+
__CLASS__,
447+
json_last_error_msg()
448+
));
449+
}
450+
451+
return $json;
452+
}
423453
}

0 commit comments

Comments
 (0)