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
11: */
12:
13:
14:
15: /**
16: * JSON response used mainly for AJAX requests.
17: *
18: * @author David Grudl
19: */
20: class JsonResponse extends Object implements IPresenterResponse
21: {
22: /** @var array|stdClass */
23: private $payload;
24:
25: /** @var string */
26: private $contentType;
27:
28:
29:
30: /**
31: * @param array|stdClass payload
32: * @param string MIME content type
33: */
34: public function __construct($payload, $contentType = NULL)
35: {
36: if (!is_array($payload) && !is_object($payload)) {
37: throw new InvalidArgumentException("Payload must be array or object class, " . gettype($payload) . " given.");
38: }
39: $this->payload = $payload;
40: $this->contentType = $contentType ? $contentType : 'application/json';
41: }
42:
43:
44:
45: /**
46: * @return array|stdClass
47: */
48: final public function getPayload()
49: {
50: return $this->payload;
51: }
52:
53:
54:
55: /**
56: * Returns the MIME content type of a downloaded file.
57: * @return string
58: */
59: final public function getContentType()
60: {
61: return $this->contentType;
62: }
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: