From 0f657d21cc0ff4f9fc835af0aece23b36eac93c5 Mon Sep 17 00:00:00 2001 From: Ryan McCue Date: Thu, 8 Oct 2015 01:29:50 +0000 Subject: [PATCH] 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. git-svn-id: https://develop.svn.wordpress.org/trunk@34926 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/functions.php | 53 +++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/src/wp-includes/functions.php b/src/wp-includes/functions.php index 7abf43ac48..2fd2eb18cb 100644 --- a/src/wp-includes/functions.php +++ b/src/wp-includes/functions.php @@ -2690,6 +2690,9 @@ function wp_json_encode( $data, $options = 0, $depth = 512 ) { $args = array( $data ); } + // Prepare the data for JSON serialization. + $data = _wp_json_prepare_data( $data ); + $json = @call_user_func_array( 'json_encode', $args ); // 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. *