Completed
Push — add/sync-json-array-codec ( 4bf13e )
by
unknown
61:08 queued 48:56
created

json_serialize()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
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";
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
		$json = json_decode( $str, true );
31
		return $this->json_unwrap( $json );
32
	}
33
34
	private function json_wrap( &$any ) {
35
		if ( is_object( $any ) ) {
36
			$any = get_object_vars( $any );
37
			$any['__o'] = 1;
38
		}
39
40
		if ( is_array( $any ) ) {
41
			foreach ( $any as $k => $v ) {
42
				$any[ $k ] = $this->json_wrap( $v );
43
			}
44
		}
45
46
		return $any;
47
	}
48
49
	private function json_unwrap( &$any ) {
50
		if ( is_array( $any ) ) {
51
			foreach ( $any as $k => $v ) {
52
				if ( '__o' === $k ) {
53
					continue;
54
				}
55
				$any[ $k ] = $this->json_unwrap( $v );
56
			}
57
58
			if ( isset( $any['__o'] ) ) {
59
				unset( $any['__o'] );
60
				$any = (object) $any;
61
			}
62
		}
63
64
		return $any;
65
	}
66
}