class.jetpack-sync-json-deflate-array-codec.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. require_once dirname( __FILE__ ) . '/interface.jetpack-sync-codec.php';
  3. /**
  4. * An implementation of iJetpack_Sync_Codec that uses gzip's DEFLATE
  5. * algorithm to compress objects serialized using json_encode
  6. */
  7. class Jetpack_Sync_JSON_Deflate_Array_Codec implements iJetpack_Sync_Codec {
  8. const CODEC_NAME = "deflate-json-array";
  9. public function name() {
  10. return self::CODEC_NAME;
  11. }
  12. public function encode( $object ) {
  13. return base64_encode( gzdeflate( $this->json_serialize( $object ) ) );
  14. }
  15. public function decode( $input ) {
  16. return $this->json_unserialize( gzinflate( base64_decode( $input ) ) );
  17. }
  18. // @see https://gist.github.com/muhqu/820694
  19. protected function json_serialize( $any ) {
  20. if ( function_exists( 'jetpack_json_wrap' ) ) {
  21. return wp_json_encode( jetpack_json_wrap( $any ) );
  22. }
  23. // This prevents fatal error when updating pre 6.0 via the cli command
  24. return wp_json_encode( $this->json_wrap( $any ) );
  25. }
  26. protected function json_unserialize( $str ) {
  27. return $this->json_unwrap( json_decode( $str, true ) );
  28. }
  29. private function json_wrap( &$any, $seen_nodes = array() ) {
  30. if ( is_object( $any ) ) {
  31. $input = get_object_vars( $any );
  32. $input['__o'] = 1;
  33. } else {
  34. $input = &$any;
  35. }
  36. if ( is_array( $input ) ) {
  37. $seen_nodes[] = &$any;
  38. $return = array();
  39. foreach ( $input as $k => &$v ) {
  40. if ( ( is_array( $v ) || is_object( $v ) ) ) {
  41. if ( in_array( $v, $seen_nodes, true ) ) {
  42. continue;
  43. }
  44. $return[ $k ] = $this->json_wrap( $v, $seen_nodes );
  45. } else {
  46. $return[ $k ] = $v;
  47. }
  48. }
  49. return $return;
  50. }
  51. return $any;
  52. }
  53. private function json_unwrap( $any ) {
  54. if ( is_array( $any ) ) {
  55. foreach ( $any as $k => $v ) {
  56. if ( '__o' === $k ) {
  57. continue;
  58. }
  59. $any[ $k ] = $this->json_unwrap( $v );
  60. }
  61. if ( isset( $any['__o'] ) ) {
  62. unset( $any['__o'] );
  63. $any = (object) $any;
  64. }
  65. }
  66. return $any;
  67. }
  68. }