16
16
use PhpRestfulApiResponse \Contracts \PhpRestfulApiResponse ;
17
17
use Zend \Diactoros \MessageTrait ;
18
18
use InvalidArgumentException ;
19
+ use Zend \Diactoros \Response \InjectContentTypeTrait ;
20
+ use Zend \Diactoros \Response \JsonResponse ;
19
21
20
22
class Response implements PhpRestfulApiResponse
21
23
{
22
- use MessageTrait;
24
+ use MessageTrait, InjectContentTypeTrait ;
23
25
24
26
const MIN_STATUS_CODE_VALUE = 100 ;
25
27
const MAX_STATUS_CODE_VALUE = 599 ;
@@ -130,6 +132,7 @@ public function __construct($body = 'php://memory', int $status = 200, $errorCod
130
132
$ this ->setStatusCode ($ status );
131
133
$ this ->setErrorCode ($ errorCode );
132
134
$ this ->stream = $ this ->getStream ($ body , 'wb+ ' );
135
+ $ headers = $ this ->injectContentType ('application/json ' , $ headers );
133
136
$ this ->setHeaders ($ headers );
134
137
}
135
138
@@ -176,8 +179,7 @@ public function withArray($data, $code = 200, array $headers = [])
176
179
{
177
180
$ new = clone $ this ;
178
181
$ new ->setStatusCode ($ code );
179
- $ new ->getBody ()->write (json_encode ($ data ));
180
- $ new = $ new ->withHeader ('Content-Type ' , 'application/json ' );
182
+ $ new ->getBody ()->write ($ this ->jsonEncode ($ data ));
181
183
$ new ->headers = array_merge ($ new ->headers , $ headers );
182
184
return $ new ;
183
185
}
@@ -250,7 +252,7 @@ public function withError($message, int $statusCode, $errorCode = null, array $h
250
252
$ new ->setStatusCode ($ statusCode );
251
253
$ new ->setErrorCode ($ errorCode );
252
254
$ new ->getBody ()->write (
253
- json_encode (
255
+ $ this -> jsonEncode (
254
256
[
255
257
'error ' => array_filter ([
256
258
'http_code ' => $ new ->statusCode ,
@@ -261,7 +263,6 @@ public function withError($message, int $statusCode, $errorCode = null, array $h
261
263
]
262
264
)
263
265
);
264
- $ new = $ new ->withHeader ('Content-Type ' , 'application/json ' );
265
266
$ new ->headers = array_merge ($ new ->headers , $ headers );
266
267
return $ new ;
267
268
}
@@ -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