Completed
Push — add/sync-json-array-codec ( 937ecd...5d850e )
by
unknown
152:36 queued 131:07
created

Jetpack_Sync_JSON_Deflate_Array_Codec::json_wrap()   C

Complexity

Conditions 7
Paths 4

Size

Total Lines 22
Code Lines 14

Duplication

Lines 8
Ratio 36.36 %

Importance

Changes 3
Bugs 0 Features 1
Metric Value
cc 7
eloc 14
c 3
b 0
f 1
nc 4
nop 2
dl 8
loc 22
rs 6.9811
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
			$any = get_object_vars( $any );
36
			$any['__o'] = 1;
37
		}
38
39
		if ( is_array( $any ) ) {
40
			foreach ( $any as $k => $v ) {
41 View Code Duplication
				if ( ( is_array( $v ) || is_object( $v ) ) ) {
42
					if ( in_array( $v, $seen_nodes, true ) ) {
43
						unset( $any[ $k ] );
44
						continue;
45
					} else {
46
						$seen_nodes[] = &$v;		
47
					}
48
				}				
49
				$any[ $k ] = $this->json_wrap( $v, $seen_nodes );
50
			}
51
		}
52
53
		return $any;
54
	}
55
56
	private function json_unwrap( $any ) {
57
		if ( is_array( $any ) ) {
58
			foreach ( $any as $k => $v ) {
59
				if ( '__o' === $k ) {
60
					continue;
61
				}
62
				$any[ $k ] = $this->json_unwrap( $v );
63
			}
64
65
			if ( isset( $any['__o'] ) ) {
66
				unset( $any['__o'] );
67
				$any = (object) $any;
68
			}
69
		}
70
71
		return $any;
72
	}
73
}