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

Jetpack_Sync_JSON_Deflate_Codec::name()   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 0
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_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
}