Make WordPress Core

Ticket #33982: 33982-jsonserialize.3.diff

File 33982-jsonserialize.3.diff, 1.8 KB (added by rmccue, 11 years ago)

Ensure we don't touch incomplete objects

  • src/wp-includes/functions.php

     
    26852685                $args = array( $data );
    26862686        }
    26872687
     2688        // Prepare the data for JSON serialization.
     2689        $data = _wp_json_prepare_data( $data );
     2690
    26882691        $json = @call_user_func_array( 'json_encode', $args );
    26892692
    26902693        // If json_encode() was successful, no need to do more sanity checking.
     
    27992802}
    28002803
    28012804/**
     2805 * Prepares response data to be serialized to JSON.
     2806 *
     2807 * This supports the JsonSerializable interface for PHP 5.2-5.3 as well.
     2808 *
     2809 * @ignore
     2810 * @since 4.4.0
     2811 * @access private
     2812 *
     2813 * @param mixed $data Native representation.
     2814 * @return bool|int|float|null|string|array Data ready for `json_encode()`.
     2815 */
     2816function _wp_json_prepare_data( $data ) {
     2817        if ( ! defined( 'WP_JSON_SERIALIZE_COMPATIBLE' ) || WP_JSON_SERIALIZE_COMPATIBLE === false ) {
     2818                return $data;
     2819        }
     2820
     2821        switch ( gettype( $data ) ) {
     2822                case 'boolean':
     2823                case 'integer':
     2824                case 'double':
     2825                case 'string':
     2826                case 'NULL':
     2827                        // These values can be passed through.
     2828                        return $data;
     2829
     2830                case 'array':
     2831                        // Arrays must be mapped in case they also return objects.
     2832                        return array_map( '_wp_json_prepare_data', $data );
     2833
     2834                case 'object':
     2835                        // If this is an incomplete object (__PHP_Incomplete_Class), bail.
     2836                        if ( ! is_object( $data ) ) {
     2837                                return null;
     2838                        }
     2839
     2840                        if ( $data instanceof JsonSerializable ) {
     2841                                $data = $data->jsonSerialize();
     2842                        } else {
     2843                                $data = get_object_vars( $data );
     2844                        }
     2845
     2846                        // Now, pass the array (or whatever was returned from jsonSerialize through).
     2847                        return _wp_json_prepare_data( $data );
     2848
     2849                default:
     2850                        return null;
     2851        }
     2852}
     2853
     2854/**
    28022855 * Send a JSON response back to an Ajax request.
    28032856 *
    28042857 * @since 3.5.0