Make WordPress Core

Changeset 34926


Ignore:
Timestamp:
10/08/2015 01:29:50 AM (9 years ago)
Author:
rmccue
Message:

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.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/functions.php

    r34914 r34926  
    26912691    }
    26922692
     2693    // Prepare the data for JSON serialization.
     2694    $data = _wp_json_prepare_data( $data );
     2695
    26932696    $json = @call_user_func_array( 'json_encode', $args );
    26942697
     
    28012804    } else {
    28022805        return wp_check_invalid_utf8( $string, true );
     2806    }
     2807}
     2808
     2809/**
     2810 * Prepares response data to be serialized to JSON.
     2811 *
     2812 * This supports the JsonSerializable interface for PHP 5.2-5.3 as well.
     2813 *
     2814 * @ignore
     2815 * @since 4.4.0
     2816 * @access private
     2817 *
     2818 * @param mixed $data Native representation.
     2819 * @return bool|int|float|null|string|array Data ready for `json_encode()`.
     2820 */
     2821function _wp_json_prepare_data( $data ) {
     2822    if ( ! defined( 'WP_JSON_SERIALIZE_COMPATIBLE' ) || WP_JSON_SERIALIZE_COMPATIBLE === false ) {
     2823        return $data;
     2824    }
     2825
     2826    switch ( gettype( $data ) ) {
     2827        case 'boolean':
     2828        case 'integer':
     2829        case 'double':
     2830        case 'string':
     2831        case 'NULL':
     2832            // These values can be passed through.
     2833            return $data;
     2834
     2835        case 'array':
     2836            // Arrays must be mapped in case they also return objects.
     2837            return array_map( '_wp_json_prepare_data', $data );
     2838
     2839        case 'object':
     2840            // If this is an incomplete object (__PHP_Incomplete_Class), bail.
     2841            if ( ! is_object( $data ) ) {
     2842                return null;
     2843            }
     2844
     2845            if ( $data instanceof JsonSerializable ) {
     2846                $data = $data->jsonSerialize();
     2847            } else {
     2848                $data = get_object_vars( $data );
     2849            }
     2850
     2851            // Now, pass the array (or whatever was returned from jsonSerialize through).
     2852            return _wp_json_prepare_data( $data );
     2853
     2854        default:
     2855            return null;
    28032856    }
    28042857}
Note: See TracChangeset for help on using the changeset viewer.