1: <?php
2:
3: /**
4: * This file is part of the Nette Framework (http://nette.org)
5: * Copyright (c) 2004 David Grudl (http://davidgrudl.com)
6: */
7:
8: namespace Nette\Application\Responses;
9:
10: use Nette;
11:
12:
13: /**
14: * JSON response used mainly for AJAX requests.
15: *
16: * @property-read array|\stdClass $payload
17: * @property-read string $contentType
18: */
19: class JsonResponse extends Nette\Object implements Nette\Application\IResponse
20: {
21: /** @var array|\stdClass */
22: private $payload;
23:
24: /** @var string */
25: private $contentType;
26:
27:
28: /**
29: * @param array|\stdClass payload
30: * @param string MIME content type
31: */
32: public function __construct($payload, $contentType = NULL)
33: {
34: if (!is_array($payload) && !is_object($payload)) {
35: throw new Nette\InvalidArgumentException(sprintf('Payload must be array or object class, %s given.', gettype($payload)));
36: }
37: $this->payload = $payload;
38: $this->contentType = $contentType ? $contentType : 'application/json';
39: }
40:
41:
42: /**
43: * @return array|\stdClass
44: */
45: public function getPayload()
46: {
47: return $this->payload;
48: }
49:
50:
51: /**
52: * Returns the MIME content type of a downloaded file.
53: * @return string
54: */
55: public function getContentType()
56: {
57: return $this->contentType;
58: }
59:
60:
61: /**
62: * Sends response to output.
63: * @return void
64: */
65: public function send(Nette\Http\IRequest $httpRequest, Nette\Http\IResponse $httpResponse)
66: {
67: $httpResponse->setContentType($this->contentType);
68: $httpResponse->setExpiration(FALSE);
69: echo Nette\Utils\Json::encode($this->payload);
70: }
71:
72: }
73: