1: <?php
2:
3: /**
4: * This file is part of the Nette Framework (http://nette.org)
5: *
6: * Copyright (c) 2004, 2011 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;
13:
14: use Nette;
15:
16:
17:
18: /**
19: * JSON response used mainly for AJAX requests.
20: *
21: * @author David Grudl
22: */
23: class JsonResponse extends Nette\Object implements IPresenterResponse
24: {
25: /** @var array|stdClass */
26: private $payload;
27:
28: /** @var string */
29: private $contentType;
30:
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: /**
49: * @return array|stdClass
50: */
51: final public function getPayload()
52: {
53: return $this->payload;
54: }
55:
56:
57:
58: /**
59: * Returns the MIME content type of a downloaded file.
60: * @return string
61: */
62: final public function getContentType()
63: {
64: return $this->contentType;
65: }
66:
67:
68:
69: /**
70: * Sends response to output.
71: * @return void
72: */
73: public function send(Nette\Web\IHttpRequest $httpRequest, Nette\Web\IHttpResponse $httpResponse)
74: {
75: $httpResponse->setContentType($this->contentType);
76: $httpResponse->setExpiration(FALSE);
77: echo Nette\Json::encode($this->payload);
78: }
79:
80: }
81: