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_Codec implements iJetpack_Sync_Codec { |
10
|
|
|
const CODEC_NAME = "deflate-json"; |
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
|
|
|
private function json_serialize( $any ) { |
26
|
|
|
return json_encode( $this->json_wrap( $any ) ); |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
private function json_unserialize( $str ) { |
30
|
|
|
return $this->json_unwrap( json_decode( $str ) ); |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
private function json_wrap( $any, $skipAssoc = false ) { |
34
|
|
|
if ( !$skipAssoc && is_array( $any ) && is_string( key( $any ) ) ) { |
35
|
|
|
return (object) array( "_PHP_ASSOC" => $this->json_wrap( $any, true ) ); |
36
|
|
|
} |
37
|
|
|
if ( is_array( $any ) || is_object( $any ) ) { |
38
|
|
|
foreach ( $any as &$v ) { |
39
|
|
|
$v = $this->json_wrap( $v ); |
40
|
|
|
} |
41
|
|
|
} |
42
|
|
|
return $any; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
private function json_unwrap( $any, $skipAssoc = false ) { |
46
|
|
|
if ( !$skipAssoc && is_object( $any ) && isset( $any->_PHP_ASSOC ) && count( (array) $any ) == 1 ) { |
47
|
|
|
return (array) $this->json_unwrap( $any->_PHP_ASSOC ); |
48
|
|
|
} |
49
|
|
|
if ( is_array( $any ) || is_object( $any ) ) { |
50
|
|
|
foreach ( $any as &$v ) { |
51
|
|
|
$v = $this->json_unwrap( $v ); |
52
|
|
|
} |
53
|
|
|
} |
54
|
|
|
return $any; |
55
|
|
|
} |
56
|
|
|
} |