<?php
/**
* WordPress Core functions.
*/
function wp_json_encode( $data, $options = 0, $depth = 512 ) {
// Simulate JSON encoding failure to trigger the rest of the code.
$json = false; //json_encode( $data, $options, $depth );
// If json_encode() was successful, no need to do more sanity checking.
if ( false !== $json ) {
return $json;
}
try {
$data = _wp_json_sanity_check( $data, $depth );
} catch ( Exception $e ) {
return false;
}
return json_encode( $data, $options, $depth );
}
function _wp_json_sanity_check( $data, $depth ) {
if ( $depth < 0 ) {
throw new Exception( 'Reached depth limit' );
}
if ( is_array( $data ) ) {
$output = array();
foreach ( $data as $id => $el ) {
// Don't forget to sanitize the ID!
if ( is_string( $id ) ) {
$clean_id = _wp_json_convert_string( $id );
} else {
$clean_id = $id;
}
// Check the element type, so that we're only recursing if we really have to.
if ( is_array( $el ) || is_object( $el ) ) {
$output[ $clean_id ] = _wp_json_sanity_check( $el, $depth - 1 );
} elseif ( is_string( $el ) ) {
$output[ $clean_id ] = _wp_json_convert_string( $el );
} else {
$output[ $clean_id ] = $el;
}
}
} elseif ( is_object( $data ) ) {
$output = new stdClass;
foreach ( $data as $id => $el ) {
if ( is_string( $id ) ) {
$clean_id = _wp_json_convert_string( $id );
} else {
$clean_id = $id;
}
if ( is_array( $el ) || is_object( $el ) ) {
$output->$clean_id = _wp_json_sanity_check( $el, $depth - 1 );
} elseif ( is_string( $el ) ) {
$output->$clean_id = _wp_json_convert_string( $el );
} else {
$output->$clean_id = $el;
}
}
} elseif ( is_string( $data ) ) {
return _wp_json_convert_string( $data );
} else {
return $data;
}
var_dump( $output );
return $output;
}
function _wp_json_convert_string( $string ) {
// Simulate failed by returning false.
if ( isset( $GLOBALS['simulate_fail'] ) ) {
return false;
}
$encoding = mb_detect_encoding( $string, mb_detect_order(), true );
if ( $encoding ) {
return mb_convert_encoding( $string, 'UTF-8', $encoding );
} else {
return mb_convert_encoding( $string, 'UTF-8', 'UTF-8' );
}
}
/**
* Run some tests.
*/
echo "\n***** Test with an array. ****\n";
$data = array(
'blogname' => array(
'value' => 'Test',
),
);
echo "\n***** When succeeds ****\n";
$json = wp_json_encode( $data );
echo "JSON = {$json}\n";
echo "\n***** When fails ****\n";
$GLOBALS['simulate_fail'] = true;
$json = wp_json_encode( $data );
echo "JSON = {$json}\n";
preferences:
55.08 ms | 408 KiB | 5 Q