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 mixed $value
* @param int $options * @param int $options
* @param int $depth * @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) * @param bool $autoSanitize Automatically sanitize invalid UTF-8 (if any)
* *
* @return string * @return string
* @throws JsonEncodeException * @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', '<')) { if (version_compare(phpversion(), '5.5.0', '<')) {
$encoded = json_encode($value, $options); $encoded = json_encode($value, $options);

View File

@ -222,7 +222,9 @@ class JsonResponse extends Response
$body['data'] = $this->getSuccessData(); $body['data'] = $this->getSuccessData();
break; 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(); $query = $query->getQuery();
switch ($format) { switch ($format) {
case 'json': case 'json':
echo Json::encode($query->fetchAll(), 0, 512, true); echo Json::sanitize($query->fetchAll());
break; break;
case 'csv': case 'csv':
Csv::fromQuery($query)->dump(); Csv::fromQuery($query)->dump();

View File

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