Completed
Push — add/memory-check-for-sync ( 37fd2c )
by
unknown
23:45 queued 10:57
created

Jetpack_Sync_JSON_Deflate_Codec   A

Complexity

Total Complexity 20

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

Changes 3
Bugs 0 Features 1
Metric Value
c 3
b 0
f 1
dl 0
loc 50
rs 10
wmc 20
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 3 1
B json_wrap() 0 12 7
B json_unwrap() 0 12 8
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( unserialize( 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, $skip_assoc = false ) {
34
		if ( ! $skip_assoc && 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
43
		return $any;
44
	}
45
46
	private function json_unwrap( $any, $skip_assoc = false ) {
47
		if ( ! $skip_assoc && is_object( $any ) && isset( $any->_PHP_ASSOC ) && count( (array) $any ) == 1 ) {
48
			return (array) $this->json_unwrap( $any->_PHP_ASSOC );
49
		}
50
		if ( is_array( $any ) || is_object( $any ) ) {
51
			foreach ( $any as &$v ) {
52
				$v = $this->json_unwrap( $v );
53
			}
54
		}
55
56
		return $any;
57
	}
58
}