1: <?php
2:
3: /**
4: * This file is part of the Nette Framework (https://nette.org)
5: * Copyright (c) 2004 David Grudl (http://davidgrudl.com)
6: * @package Nette\Application\Responses
7: */
8:
9:
10:
11: /**
12: * JSON response used mainly for AJAX requests.
13: *
14: * @author David Grudl
15: *
16: * @property-read array|\stdClass $payload
17: * @property-read string $contentType
18: * @package Nette\Application\Responses
19: */
20: class JsonResponse extends Object implements IPresenterResponse
21: {
22: /** @var array|\stdClass */
23: private $payload;
24:
25: /** @var string */
26: private $contentType;
27:
28:
29: /**
30: * @param array|\stdClass payload
31: * @param string MIME content type
32: */
33: public function __construct($payload, $contentType = NULL)
34: {
35: if (!is_array($payload) && !is_object($payload)) {
36: throw new InvalidArgumentException(sprintf('Payload must be array or object class, %s given.', gettype($payload)));
37: }
38: $this->payload = $payload;
39: $this->contentType = $contentType ? $contentType : 'application/json';
40: }
41:
42:
43: /**
44: * @return array|\stdClass
45: */
46: public function getPayload()
47: {
48: return $this->payload;
49: }
50:
51:
52: /**
53: * Returns the MIME content type of a downloaded file.
54: * @return string
55: */
56: public function getContentType()
57: {
58: return $this->contentType;
59: }
60:
61:
62: /**
63: * Sends response to output.
64: * @return void
65: */
66: public function send(IHttpRequest $httpRequest, IHttpResponse $httpResponse)
67: {
68: $httpResponse->setContentType($this->contentType);
69: $httpResponse->setExpiration(FALSE);
70: echo Json::encode($this->payload);
71: }
72:
73: }
74: