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