JsonResponse.php 1.72 KB
Newer Older
1 2 3 4
<?php
/**
*
* @package dcbase
Crise's avatar
Crise committed
5
* @copyright (c) 2019 Direct Connect Network Foundation / www.dcbase.org
Crise's avatar
Crise committed
6
* @license https://www.dcbase.org/DCBase/LICENSE GNU General Public License v2
7 8 9 10 11 12 13 14 15 16 17
*
*/

namespace DCBase\Response;

/**
* @ignore
*/
if (!defined('IN_DCBASE')) exit;

use Exception;
Crise's avatar
Crise committed
18
use SplFileInfo;
19 20 21

use DCBase\WebRequest;
use DCBase\WebResponse;
22
use DCBase\Common\Util;
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37

/**
 * Web response implementation for JSON(P) requests
 */
class JsonResponse extends WebResponse
{
	// The JSON data to be encoded and sent
	protected $json = array();
	protected $mime_type = 'application/json';

	public function body($json_data)
	{
		if ($json_data instanceof WebResponse)
			$json_data = $json_data->output();

Crise's avatar
Crise committed
38
		if ($json_data instanceof SplFileInfo)
Crise's avatar
Crise committed
39 40 41 42
		{
			if (!$json_data->isReadable() || $json_data->isDir())
				throw new Exception('File: "' . $json_data->getPathname() . '" not readable.');

Crise's avatar
Crise committed
43
			$json_data = file_get_contents($json_data->getRealPath());
Crise's avatar
Crise committed
44
		}
Crise's avatar
Crise committed
45

46 47 48 49 50 51 52 53 54 55 56
		$this->json = $json_data;
		return $this;
	}

	public function output()
	{
		// encode json and wrap in a callback if requested
		$body = $this->json;
		if (!is_string($body))
		{
			$options = 0;
57
			if (Util::isDebug())
58 59 60 61 62 63 64 65 66 67
				$options |= JSON_PRETTY_PRINT;

			$body = json_encode($body, $options);
		}

		if (isset($this->request['callback']))
		{
			$callback = preg_replace('#[^a-zA-Z0-9_\\.]++#u', '', $this->request['callback']);
			if (!empty($callback))
			{
68
				$this->mime_type = 'application/javascript';
69 70 71 72 73 74 75 76 77
				$body = "// JSONP Response \n $callback($body);";
			}
		}

		return $body;
	}

	public function send()
	{
78 79
		// set content type to json, application/* mime types should have their own encoding specifications
		$this->header('Content-Type', "{$this->mime_type}");
80 81 82 83

		parent::send();
	}
}