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: */
11:
12: namespace Nette\Application\Responses;
13:
14: use Nette;
15:
16:
17:
18: /**
19: * JSON response used mainly for AJAX requests.
20: *
21: * @author David Grudl
22: *
23: * @property-read array|\stdClass $payload
24: * @property-read string $contentType
25: */
26: class JsonResponse extends Nette\Object implements Nette\Application\IResponse
27: {
28: /** @var array|\stdClass */
29: private $payload;
30:
31: /** @var string */
32: private $contentType;
33:
34:
35:
36: /**
37: * @param array|\stdClass payload
38: * @param string MIME content type
39: */
40: public function __construct($payload, $contentType = NULL)
41: {
42: if (!is_array($payload) && !is_object($payload)) {
43: throw new Nette\InvalidArgumentException("Payload must be array or object class, " . gettype($payload) . " given.");
44: }
45: $this->payload = $payload;
46: $this->contentType = $contentType ? $contentType : 'application/json';
47: }
48:
49:
50:
51: /**
52: * @return array|\stdClass
53: */
54: final public function getPayload()
55: {
56: return $this->payload;
57: }
58:
59:
60:
61: /**
62: * Returns the MIME content type of a downloaded file.
63: * @return string
64: */
65: final public function getContentType()
66: {
67: return $this->contentType;
68: }
69:
70:
71:
72: /**
73: * Sends response to output.
74: * @return void
75: */
76: public function send(Nette\Http\IRequest $httpRequest, Nette\Http\IResponse $httpResponse)
77: {
78: $httpResponse->setContentType($this->contentType);
79: $httpResponse->setExpiration(FALSE);
80: echo Nette\Utils\Json::encode($this->payload);
81: }
82:
83: }
84: