REST API: Add JsonSerializable compatibility to wp_json_encode

Following on from r34845, the JsonSerializable shim needs support
on the encoding side too. _wp_json_prepare_data handles this when
we've loaded the shim.

Props chriscct7.

See #33982. 

Built from https://develop.svn.wordpress.org/trunk@34926


git-svn-id: http://core.svn.wordpress.org/trunk@34891 1a063a9b-81f0-0310-95a4-ce76da25c4cd
This commit is contained in:
Ryan McCue 2015-10-08 01:30:25 +00:00
parent 0e1ecdcbf3
commit 4bac3c3f14
2 changed files with 54 additions and 1 deletions

View File

@ -2690,6 +2690,9 @@ function wp_json_encode( $data, $options = 0, $depth = 512 ) {
$args = array( $data ); $args = array( $data );
} }
// Prepare the data for JSON serialization.
$data = _wp_json_prepare_data( $data );
$json = @call_user_func_array( 'json_encode', $args ); $json = @call_user_func_array( 'json_encode', $args );
// If json_encode() was successful, no need to do more sanity checking. // If json_encode() was successful, no need to do more sanity checking.
@ -2803,6 +2806,56 @@ function _wp_json_convert_string( $string ) {
} }
} }
/**
* Prepares response data to be serialized to JSON.
*
* This supports the JsonSerializable interface for PHP 5.2-5.3 as well.
*
* @ignore
* @since 4.4.0
* @access private
*
* @param mixed $data Native representation.
* @return bool|int|float|null|string|array Data ready for `json_encode()`.
*/
function _wp_json_prepare_data( $data ) {
if ( ! defined( 'WP_JSON_SERIALIZE_COMPATIBLE' ) || WP_JSON_SERIALIZE_COMPATIBLE === false ) {
return $data;
}
switch ( gettype( $data ) ) {
case 'boolean':
case 'integer':
case 'double':
case 'string':
case 'NULL':
// These values can be passed through.
return $data;
case 'array':
// Arrays must be mapped in case they also return objects.
return array_map( '_wp_json_prepare_data', $data );
case 'object':
// If this is an incomplete object (__PHP_Incomplete_Class), bail.
if ( ! is_object( $data ) ) {
return null;
}
if ( $data instanceof JsonSerializable ) {
$data = $data->jsonSerialize();
} else {
$data = get_object_vars( $data );
}
// Now, pass the array (or whatever was returned from jsonSerialize through).
return _wp_json_prepare_data( $data );
default:
return null;
}
}
/** /**
* Send a JSON response back to an Ajax request. * Send a JSON response back to an Ajax request.
* *

View File

@ -4,7 +4,7 @@
* *
* @global string $wp_version * @global string $wp_version
*/ */
$wp_version = '4.4-alpha-34925'; $wp_version = '4.4-alpha-34926';
/** /**
* Holds the WordPress DB revision, increments when changes are made to the WordPress DB schema. * Holds the WordPress DB revision, increments when changes are made to the WordPress DB schema.