Completed
Push — update/admin-page-readme-more-... ( 8f2301...4565b6 )
by
unknown
11:51
created

json_unwrap()   B

Complexity

Conditions 5
Paths 3

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 5
eloc 10
c 1
b 0
f 1
nc 3
nop 1
dl 0
loc 17
rs 8.8571
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
	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, true ) );
31
	}
32
33
	private function json_wrap( &$any, $seen_nodes = array() ) {
34
		if ( is_object( $any ) ) {
35
			$input = get_object_vars( $any );
36
			$input['__o'] = 1;
37
		} else {
38
			$input = &$any;
39
		}
40
41
		if ( is_array( $input ) ) {
42
			$seen_nodes[] = &$any;
43
44
			$return = array();
45
46
			foreach ( $input as $k => &$v ) {
47
				if ( ( is_array( $v ) || is_object( $v ) ) ) {
48
					if ( in_array( $v, $seen_nodes, true ) ) {
49
						continue;
50
					} 
51
					$return[ $k ] = $this->json_wrap( $v, $seen_nodes );
52
				} else {
53
					$return[ $k ] = $v;	
54
				}
55
			}
56
57
			return $return;
58
		}
59
60
		return $any;
61
	}
62
63
	private function json_unwrap( $any ) {
64
		if ( is_array( $any ) ) {
65
			foreach ( $any as $k => $v ) {
66
				if ( '__o' === $k ) {
67
					continue;
68
				}
69
				$any[ $k ] = $this->json_unwrap( $v );
70
			}
71
72
			if ( isset( $any['__o'] ) ) {
73
				unset( $any['__o'] );
74
				$any = (object) $any;
75
			}
76
		}
77
78
		return $any;
79
	}
80
}