Json pretty print (#18726)

* Added pretty print support to Json helper

* Updated documentation for `yii\helpers\Json::$prettyPrint`

* Fixed line ending in \yiiunit\framework\helpers\JsonTest::testPrettyPrint for windows

* Added helper-json.md link in docs/guide/README.md

* Capitalized JSON in descriptions

Co-authored-by: Alexander Makarov <sam@rmcreative.ru>

Co-authored-by: Alexander Makarov <sam@rmcreative.ru>
Co-authored-by: Bizley <pawel@positive.codes>
This commit is contained in:
rhertogh
2021-06-27 14:08:41 +02:00
committed by GitHub
parent b9cd4c14ef
commit db39f7c955
6 changed files with 74 additions and 1 deletions

View File

@ -22,6 +22,13 @@ use yii\base\Model;
*/
class BaseJson
{
/**
* @var bool|null Enables human readable output a.k.a. Pretty Print.
* This can useful for debugging during development but is not recommended in a production environment!
* In case `prettyPrint` is `null` (default) the `options` passed to `encode` functions will not be changed.
* @since 2.0.43
*/
public static $prettyPrint = null;
/**
* List of JSON Error messages assigned to constant names for better handling of version differences.
* @var array
@ -62,6 +69,13 @@ class BaseJson
set_error_handler(function () {
static::handleJsonError(JSON_ERROR_SYNTAX);
}, E_WARNING);
if (static::$prettyPrint === true) {
$options |= JSON_PRETTY_PRINT;
} elseif (static::$prettyPrint === false) {
$options &= ~JSON_PRETTY_PRINT;
}
$json = json_encode($value, $options);
restore_error_handler();
static::handleJsonError(json_last_error());