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: * @package Nette\Application\Responses
11: */
12:
13:
14:
15: /**
16: * JSON response used mainly for AJAX requests.
17: *
18: * @author David Grudl
19: * @package Nette\Application\Responses
20: */
21: class JsonResponse extends Object implements IPresenterResponse
22: {
23: /** @var array|stdClass */
24: private $payload;
25:
26: /** @var string */
27: private $contentType;
28:
29:
30:
31: /**
32: * @param array|stdClass payload
33: * @param string MIME content type
34: */
35: public function __construct($payload, $contentType = NULL)
36: {
37: if (!is_array($payload) && !is_object($payload)) {
38: throw new InvalidArgumentException("Payload must be array or object class, " . gettype($payload) . " given.");
39: }
40: $this->payload = $payload;
41: $this->contentType = $contentType ? $contentType : 'application/json';
42: }
43:
44:
45:
46: /**
47: * @return array|stdClass
48: */
49: final public function getPayload()
50: {
51: return $this->payload;
52: }
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: /**
68: * Sends response to output.
69: * @return void
70: */
71: public function send(IHttpRequest $httpRequest, IHttpResponse $httpResponse)
72: {
73: $httpResponse->setContentType($this->contentType);
74: $httpResponse->setExpiration(FALSE);
75: echo Json::encode($this->payload);
76: }
77:
78: }
79: