Backport jsonOptions

This commit is contained in:
Mark Scherer 2015-04-30 15:51:13 +02:00
parent c31fcd6f39
commit adf2eb03f2
2 changed files with 43 additions and 5 deletions

View file

@ -194,6 +194,31 @@ class JsonViewTest extends CakeTestCase {
$this->assertSame($expected, $output);
}
/**
* Test render with _jsonOptions setting.
*
* @return void
*/
public function testRenderWithoutViewJsonOptions() {
$this->skipIf(!version_compare(PHP_VERSION, '5.3.0', '>='), 'Needs PHP5.3+ for these constants to be tested');
$Request = new CakeRequest();
$Response = new CakeResponse();
$Controller = new Controller($Request, $Response);
// Test render with encode <, >, ', &, and " for RFC4627-compliant to be serialized.
$data = array('rfc4627_escape' => '<tag> \'quote\' "double-quote" &');
$serialize = 'rfc4627_escape';
$expected = json_encode('<tag> \'quote\' "double-quote" &', JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT);
$Controller->set($data);
$Controller->set('_serialize', $serialize);
$Controller->set('_jsonOptions', JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT);
$View = new JsonView($Controller);
$output = $View->render(false);
$this->assertSame($expected, $output);
}
/**
* Test that rendering with _serialize does not load helpers.
*

View file

@ -125,6 +125,10 @@ class JsonView extends View {
/**
* Serialize view vars
*
* ### Special parameters
* `_jsonOptions` You can set custom options for json_encode() this way,
* e.g. `JSON_HEX_TAG | JSON_HEX_APOS`.
*
* @param array $serialize The viewVars that need to be serialized
* @throws CakeException
* @return string The serialized data
@ -145,15 +149,24 @@ class JsonView extends View {
$data = isset($this->viewVars[$serialize]) ? $this->viewVars[$serialize] : null;
}
if (version_compare(PHP_VERSION, '5.4.0', '>=') && Configure::read('debug')) {
$json = json_encode($data, JSON_PRETTY_PRINT);
$jsonOptions = 0;
if (isset($this->viewVars['_jsonOptions'])) {
if ($this->viewVars['_jsonOptions'] === false) {
$jsonOptions = 0;
} else {
$json = json_encode($data);
$jsonOptions = $this->viewVars['_jsonOptions'];
}
}
if (version_compare(PHP_VERSION, '5.4.0', '>=') && Configure::read('debug')) {
$jsonOptions = $jsonOptions | JSON_PRETTY_PRINT;
}
$json = json_encode($data, $jsonOptions);
if (function_exists('json_last_error') && json_last_error() !== JSON_ERROR_NONE) {
throw new CakeException(json_last_error_msg());
} elseif ($json === false) {
}
if ($json === false) {
throw new CakeException('Failed to parse JSON');
}
return $json;