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