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
|
|
|
const MAX_DEPTH = 10; |
12
|
|
|
|
13
|
|
|
public function name() { |
14
|
|
|
return self::CODEC_NAME; |
15
|
|
|
} |
16
|
|
|
|
17
|
|
|
public function encode( $object ) { |
18
|
|
|
return base64_encode( gzdeflate( $this->json_serialize( $object ) ) ); |
19
|
|
|
} |
20
|
|
|
|
21
|
|
|
public function decode( $input ) { |
22
|
|
|
return $this->json_unserialize( gzinflate( base64_decode( $input ) ) ); |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
// @see https://gist.github.com/muhqu/820694 |
26
|
|
|
private function json_serialize( $any ) { |
27
|
|
|
return json_encode( $this->json_wrap( $any ) ); |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
private function json_unserialize( $str ) { |
31
|
|
|
$json = json_decode( $str, true ); |
32
|
|
|
return $this->json_unwrap( $json ); |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
private function json_wrap( $any, $depth = 1 ) { |
36
|
|
|
if ( $depth > self::MAX_DEPTH ) { |
37
|
|
|
return null; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
if ( is_object( $any ) ) { |
41
|
|
|
$any = get_object_vars( $any ); |
42
|
|
|
$any['__o'] = 1; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
if ( is_array( $any ) ) { |
46
|
|
|
foreach ( $any as $k => $v ) { |
47
|
|
|
$any[ $k ] = $this->json_wrap( $v, $depth + 1 ); |
48
|
|
|
} |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
return $any; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
private function json_unwrap( $any ) { |
55
|
|
|
if ( is_array( $any ) ) { |
56
|
|
|
foreach ( $any as $k => $v ) { |
57
|
|
|
if ( '__o' === $k ) { |
58
|
|
|
continue; |
59
|
|
|
} |
60
|
|
|
$any[ $k ] = $this->json_unwrap( $v ); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
if ( isset( $any['__o'] ) ) { |
64
|
|
|
unset( $any['__o'] ); |
65
|
|
|
$any = (object) $any; |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
return $any; |
70
|
|
|
} |
71
|
|
|
} |