16
16
use PhpRestfulApiResponse \Contracts \PhpRestfulApiResponse ;
17
17
use Zend \Diactoros \MessageTrait ;
18
18
use InvalidArgumentException ;
19
+ use Zend \Diactoros \Response \JsonResponse ;
19
20
20
21
class Response implements PhpRestfulApiResponse
21
22
{
@@ -176,7 +177,7 @@ public function withArray($data, $code = 200, array $headers = [])
176
177
{
177
178
$ new = clone $ this ;
178
179
$ new ->setStatusCode ($ code );
179
- $ new ->getBody ()->write (json_encode ($ data ));
180
+ $ new ->getBody ()->write ($ this -> jsonEncode ($ data ));
180
181
$ new = $ new ->withHeader ('Content-Type ' , 'application/json ' );
181
182
$ new ->headers = array_merge ($ new ->headers , $ headers );
182
183
return $ new ;
@@ -250,7 +251,7 @@ public function withError($message, int $statusCode, $errorCode = null, array $h
250
251
$ new ->setStatusCode ($ statusCode );
251
252
$ new ->setErrorCode ($ errorCode );
252
253
$ new ->getBody ()->write (
253
- json_encode (
254
+ $ this -> jsonEncode (
254
255
[
255
256
'error ' => array_filter ([
256
257
'http_code ' => $ new ->statusCode ,
@@ -420,4 +421,33 @@ private function setStatusCode(int $statusCode)
420
421
}
421
422
$ this ->statusCode = $ statusCode ;
422
423
}
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
+ }
423
453
}
0 commit comments