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: * JSON response used mainly for AJAX requests.
19: *
20: * @author David Grudl
21: *
22: * @property-read array|\stdClass $payload
23: * @property-read string $contentType
24: */
25: class JsonResponse extends Nette\Object implements Nette\Application\IResponse
26: {
27: /** @var array|\stdClass */
28: private $payload;
29:
30: /** @var string */
31: private $contentType;
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 Nette\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: * @return array|\stdClass
50: */
51: final public function getPayload()
52: {
53: return $this->payload;
54: }
55:
56:
57: /**
58: * Returns the MIME content type of a downloaded file.
59: * @return string
60: */
61: final public function getContentType()
62: {
63: return $this->contentType;
64: }
65:
66:
67: /**
68: * Sends response to output.
69: * @return void
70: */
71: public function send(Nette\Http\IRequest $httpRequest, Nette\Http\IResponse $httpResponse)
72: {
73: $httpResponse->setContentType($this->contentType);
74: $httpResponse->setExpiration(FALSE);
75: echo Nette\Utils\Json::encode($this->payload);
76: }
77:
78: }
79: