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

Jetpack_Sync_JSON_Deflate_Codec::encode()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
c 0
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_Codec implements iJetpack_Sync_Codec {
10
	const CODEC_NAME = 'deflate-json';
11
	const MAX_DEPTH = 10;
12
13
	public function name() {
14
		return self::CODEC_NAME;
15
	}
16
17
	public function encode( $object ) {
18
		return base64_encode( gzdeflate( $this->json_serialize( unserialize( serialize( $object ) ) ) ) );
19
	}
20
21
	public function decode( $input ) {
22
		return $this->json_unserialize( gzinflate( base64_decode( $input ) ) );
23
	}
24
25
	// @see https://gist.github.com/muhqu/820694
26
	private function json_serialize( $any ) {
27
		return json_encode( $this->json_wrap( $any ) );
28
	}
29
30
	private function json_unserialize( $str ) {
31
		return $this->json_unwrap( json_decode( $str ) );
32
	}
33
34
	private function json_wrap( $any, $skip_assoc = false, $seen_nodes = array() ) {
35
		
36
		if ( ! $skip_assoc && is_array( $any ) && is_string( key( $any ) ) ) {
37
			return (object) array( '_PHP_ASSOC' => $this->json_wrap( $any, true ) );
38
		}
39
40
		if ( is_array( $any ) || is_object( $any ) ) {
41
			foreach ( $any as $k => &$v ) {
42
				if ( ( is_array( $v ) || is_object( $v ) ) ) {
43 View Code Duplication
					if ( in_array( $v, $seen_nodes, true ) ) {
44
						if ( is_object( $any ) ) {
45
							unset( $any->{ $k } );	
46
						} else {
47
							unset( $any[ $k ] );
48
						}
49
						continue;
50
					} else {
51
						$seen_nodes[] = $v;
52
					}
53
				}
54
				$v = $this->json_wrap( $v, false, $seen_nodes );
55
			}
56
		}
57
58
		return $any;
59
	}
60
61
	private function json_unwrap( $any, $skip_assoc = false ) {
62
		if ( ! $skip_assoc && is_object( $any ) && isset( $any->_PHP_ASSOC ) && count( (array) $any ) == 1 ) {
63
			return (array) $this->json_unwrap( $any->_PHP_ASSOC );
64
		}
65
66
		if ( is_array( $any ) || is_object( $any ) ) {
67
			foreach ( $any as &$v ) {
68
				$v = $this->json_unwrap( $v );
69
			}
70
		}
71
72
		return $any;
73
	}
74
}
75