Merge pull request #6551 from robbieaverill/feature/json-context

API Convert::raw2json can be passed an optional bitmask of JSON constants as options
This commit is contained in:
Daniel Hensby 2017-01-24 12:18:40 +00:00 committed by GitHub
commit d9cffe5f53
2 changed files with 27 additions and 10 deletions

View File

@ -126,24 +126,27 @@ class Convert {
}
/**
* Encode a value as a JSON encoded string.
* Encode a value as a JSON encoded string. You can optionally pass a bitmask of
* JSON constants as options through to the encode function.
*
* @param mixed $val Value to be encoded
* @return string JSON encoded string
* @param mixed $val Value to be encoded
* @param int $options Optional bitmask of JSON constants
* @return string JSON encoded string
*/
public static function raw2json($val) {
return json_encode($val);
public static function raw2json($val, $options = 0) {
return json_encode($val, $options);
}
/**
* Encode an array as a JSON encoded string.
* THis is an alias to {@link raw2json()}
* This is an alias to {@link raw2json()}
*
* @param array $val Array to convert
* @return string JSON encoded string
* @param array $val Array to convert
* @param int $options Optional bitmask of JSON constants
* @return string JSON encoded string
*/
public static function array2json($val) {
return self::raw2json($val);
public static function array2json($val, $options = 0) {
return self::raw2json($val, $options);
}
/**

View File

@ -303,6 +303,20 @@ PHP
);
}
/**
* Test that a context bitmask can be passed through to the json_encode method in {@link Convert::raw2json()}
* and in {@link Convert::array2json()}
*/
public function testRaw2JsonWithContext()
{
$data = array('foo' => 'b"ar');
$expected = '{"foo":"b\u0022ar"}';
$result = Convert::raw2json($data, JSON_HEX_QUOT);
$this->assertSame($expected, $result);
$wrapperResult = Convert::array2json($data, JSON_HEX_QUOT);
$this->assertSame($expected, $wrapperResult);
}
/**
* Tests {@link Convert::xml2array()}
*/