Split Json::encode() into Json::encode() and Json::sanitize()

refs #2635
This commit is contained in:
Alexander A. Klimov 2018-06-20 18:03:21 +02:00
parent 02b60633ff
commit 906c1668a4
4 changed files with 36 additions and 4 deletions

View File

@ -17,12 +17,42 @@ class Json
* @param mixed $value
* @param int $options
* @param int $depth
*
* @return string
* @throws JsonEncodeException
*/
public static function encode($value, $options = 0, $depth = 512)
{
return static::encodeAndSanitize($value, $options, $depth, false);
}
/**
* {@link json_encode()} wrapper, automatically sanitizes bad UTF-8
*
* @param mixed $value
* @param int $options
* @param int $depth
*
* @return string
* @throws JsonEncodeException
*/
public static function sanitize($value, $options = 0, $depth = 512)
{
return static::encodeAndSanitize($value, $options, $depth, true);
}
/**
* {@link json_encode()} wrapper, sanitizes bad UTF-8
*
* @param mixed $value
* @param int $options
* @param int $depth
* @param bool $autoSanitize Automatically sanitize invalid UTF-8 (if any)
*
* @return string
* @throws JsonEncodeException
*/
public static function encode($value, $options = 0, $depth = 512, $autoSanitize = false)
protected static function encodeAndSanitize($value, $options, $depth, $autoSanitize)
{
if (version_compare(phpversion(), '5.5.0', '<')) {
$encoded = json_encode($value, $options);

View File

@ -222,7 +222,9 @@ class JsonResponse extends Response
$body['data'] = $this->getSuccessData();
break;
}
echo Json::encode($body, $this->getEncodingOptions(), 512, $this->autoSanitize);
echo $this->getAutoSanitize()
? Json::sanitize($body, $this->getEncodingOptions())
: Json::encode($body, $this->getEncodingOptions());
}
/**

View File

@ -79,7 +79,7 @@ class ListCommand extends Command
$query = $query->getQuery();
switch ($format) {
case 'json':
echo Json::encode($query->fetchAll(), 0, 512, true);
echo Json::sanitize($query->fetchAll());
break;
case 'csv':
Csv::fromQuery($query)->dump();

View File

@ -60,7 +60,7 @@ class Controller extends IcingaWebController
'Content-Disposition',
'inline; filename=' . $this->getRequest()->getActionName() . '.json'
)
->appendBody(Json::encode($query->fetchAll()), 0, 512, true)
->appendBody(Json::sanitize($query->fetchAll()))
->sendResponse();
exit;
case 'csv':