Completed
Push — fix/inline-docs-410 ( f96891...63b75c )
by
unknown
43:24 queued 33:40
created

Jetpack_Sync_JSON_Deflate_Codec::json_wrap()   B

Complexity

Conditions 7
Paths 3

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
eloc 7
c 1
b 0
f 0
nc 3
nop 2
dl 0
loc 11
rs 8.2222
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_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
		return $this->json_unwrap( json_decode( $str ) );
31
	}
32
33
	private function json_wrap( $any, $skipAssoc = false ) {
34
		if ( !$skipAssoc && is_array( $any ) && is_string( key( $any ) ) ) {
35
			return (object) array( "_PHP_ASSOC" => $this->json_wrap( $any, true ) );
36
		}
37
		if ( is_array( $any ) || is_object( $any ) ) {
38
			foreach ( $any as &$v ) {
39
				$v = $this->json_wrap( $v );
40
			}
41
		}
42
		return $any;
43
	}
44
45
	private function json_unwrap( $any, $skipAssoc = false ) {
46
		if ( !$skipAssoc && is_object( $any ) && isset( $any->_PHP_ASSOC ) && count( (array) $any ) == 1 ) {
47
			return (array) $this->json_unwrap( $any->_PHP_ASSOC );
48
		}
49
		if ( is_array( $any ) || is_object( $any ) ) {
50
			foreach ( $any as &$v ) {
51
				$v = $this->json_unwrap( $v );
52
			}
53
		}
54
		return $any;
55
	}
56
}