| 1 |
<?php |
| 2 |
|
| 3 |
require_once dirname( __FILE__ ) . '/interface.jetpack-sync-codec.php'; |
| 4 |
|
| 5 |
/** |
| 6 |
* An implementation of iJetpack_Sync_Codec that uses gzip's DEFLATE |
| 7 |
* algorithm to compress objects serialized using json_encode |
| 8 |
*/ |
| 9 |
class Jetpack_Sync_JSON_Deflate_Array_Codec implements iJetpack_Sync_Codec { |
| 10 |
const CODEC_NAME = "deflate-json-array"; |
| 11 |
|
| 12 |
public function name() { |
| 13 |
return self::CODEC_NAME; |
| 14 |
} |
| 15 |
|
| 16 |
public function encode( $object ) { |
| 17 |
return base64_encode( gzdeflate( $this->json_serialize( $object ) ) ); |
| 18 |
} |
| 19 |
|
| 20 |
public function decode( $input ) { |
| 21 |
return $this->json_unserialize( gzinflate( base64_decode( $input ) ) ); |
| 22 |
} |
| 23 |
|
| 24 |
// @see https://gist.github.com/muhqu/820694 |
| 25 |
|
| 26 |
protected function json_serialize( $any ) { |
| 27 |
if ( function_exists( 'jetpack_json_wrap' ) ) { |
| 28 |
return wp_json_encode( jetpack_json_wrap( $any ) ); |
| 29 |
} |
| 30 |
// This prevents fatal error when updating pre 6.0 via the cli command |
| 31 |
return wp_json_encode( $this->json_wrap( $any ) ); |
| 32 |
} |
| 33 |
|
| 34 |
protected function json_unserialize( $str ) { |
| 35 |
return $this->json_unwrap( json_decode( $str, true ) ); |
| 36 |
} |
| 37 |
|
| 38 |
private function json_wrap( &$any, $seen_nodes = array() ) { |
| 39 |
if ( is_object( $any ) ) { |
| 40 |
$input = get_object_vars( $any ); |
| 41 |
$input['__o'] = 1; |
| 42 |
} else { |
| 43 |
$input = &$any; |
| 44 |
} |
| 45 |
|
| 46 |
if ( is_array( $input ) ) { |
| 47 |
$seen_nodes[] = &$any; |
| 48 |
|
| 49 |
$return = array(); |
| 50 |
|
| 51 |
foreach ( $input as $k => &$v ) { |
| 52 |
if ( ( is_array( $v ) || is_object( $v ) ) ) { |
| 53 |
if ( in_array( $v, $seen_nodes, true ) ) { |
| 54 |
continue; |
| 55 |
} |
| 56 |
$return[ $k ] = $this->json_wrap( $v, $seen_nodes ); |
| 57 |
} else { |
| 58 |
$return[ $k ] = $v; |
| 59 |
} |
| 60 |
} |
| 61 |
|
| 62 |
return $return; |
| 63 |
} |
| 64 |
|
| 65 |
return $any; |
| 66 |
} |
| 67 |
|
| 68 |
private function json_unwrap( $any ) { |
| 69 |
if ( is_array( $any ) ) { |
| 70 |
foreach ( $any as $k => $v ) { |
| 71 |
if ( '__o' === $k ) { |
| 72 |
continue; |
| 73 |
} |
| 74 |
$any[ $k ] = $this->json_unwrap( $v ); |
| 75 |
} |
| 76 |
|
| 77 |
if ( isset( $any['__o'] ) ) { |
| 78 |
unset( $any['__o'] ); |
| 79 |
$any = (object) $any; |
| 80 |
} |
| 81 |
} |
| 82 |
|
| 83 |
return $any; |
| 84 |
} |
| 85 |
} |
| 86 |
|