Completed
Push — add/sync-json-array-codec ( 6ceb84...20c4f7 )
by
unknown
135:37 queued 125:33
created

Jetpack_Sync_JSON_Deflate_Array_Codec   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 0
loc 63
rs 10
wmc 15
lcom 0
cbo 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
A name() 0 3 1
A encode() 0 3 1
A decode() 0 3 1
A json_serialize() 0 3 1
A json_unserialize() 0 4 1
B json_wrap() 0 18 5
B json_unwrap() 0 17 5
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
}