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