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: * @param array|\stdClass payload
35: * @param string MIME content type
36: */
37: public function __construct($payload, $contentType = NULL)
38: {
39: if (!is_array($payload) && !is_object($payload)) {
40: throw new InvalidArgumentException("Payload must be array or object class, " . gettype($payload) . " given.");
41: }
42: $this->payload = $payload;
43: $this->contentType = $contentType ? $contentType : 'application/json';
44: }
45:
46:
47: /**
48: * @return array|\stdClass
49: */
50: final public function getPayload()
51: {
52: return $this->payload;
53: }
54:
55:
56: /**
57: * Returns the MIME content type of a downloaded file.
58: * @return string
59: */
60: final public function getContentType()
61: {
62: return $this->contentType;
63: }
64:
65:
66: /**
67: * Sends response to output.
68: * @return void
69: */
70: public function send(IHttpRequest $httpRequest, IHttpResponse $httpResponse)
71: {
72: $httpResponse->setContentType($this->contentType);
73: $httpResponse->setExpiration(FALSE);
74: echo Json::encode($this->payload);
75: }
76:
77: }
78: