3 * Zend Framework (http://framework.zend.com/)
5 * @see http://github.com/zendframework/zend-diactoros for the canonical source repository
6 * @copyright Copyright (c) 2015-2016 Zend Technologies USA Inc. (http://www.zend.com)
7 * @license https://github.com/zendframework/zend-diactoros/blob/master/LICENSE.md New BSD License
10 namespace Zend\Diactoros\Response;
12 use InvalidArgumentException;
13 use Zend\Diactoros\Response;
14 use Zend\Diactoros\Stream;
19 * Allows creating a response by passing data to the constructor; by default,
20 * serializes the data to JSON, sets a status code of 200 and sets the
21 * Content-Type header to application/json.
23 class JsonResponse extends Response
25 use InjectContentTypeTrait;
28 * Default flags for json_encode; value of:
31 * JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT | JSON_UNESCAPED_SLASHES
36 const DEFAULT_JSON_FLAGS = 79;
39 * Create a JSON response with the given data.
41 * Default JSON encoding is performed with the following options, which
42 * produces RFC4627-compliant JSON, capable of embedding into HTML.
48 * - JSON_UNESCAPED_SLASHES
50 * @param mixed $data Data to convert to JSON.
51 * @param int $status Integer status code for the response; 200 by default.
52 * @param array $headers Array of headers to use at initialization.
53 * @param int $encodingOptions JSON encoding options to use.
54 * @throws InvalidArgumentException if unable to encode the $data to JSON.
56 public function __construct(
60 $encodingOptions = self::DEFAULT_JSON_FLAGS
62 $body = new Stream('php://temp', 'wb+');
63 $body->write($this->jsonEncode($data, $encodingOptions));
66 $headers = $this->injectContentType('application/json', $headers);
68 parent::__construct($body, $status, $headers);
72 * Encode the provided data to JSON.
75 * @param int $encodingOptions
77 * @throws InvalidArgumentException if unable to encode the $data to JSON.
79 private function jsonEncode($data, $encodingOptions)
81 if (is_resource($data)) {
82 throw new InvalidArgumentException('Cannot JSON encode resources');
85 // Clear json_last_error()
88 $json = json_encode($data, $encodingOptions);
90 if (JSON_ERROR_NONE !== json_last_error()) {
91 throw new InvalidArgumentException(sprintf(
92 'Unable to encode data to JSON in %s: %s',