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