Elgg  Version 3.0
EmptyKeyEncoding.php
Go to the documentation of this file.
1 <?php
2 
3 namespace Elgg\Json;
4 
16 
20  protected $token;
21 
27  public function __construct($empty_key = '') {
28  if (!$empty_key) {
29  $empty_key = sha1(microtime(true) . mt_rand());
30  }
31  $this->token = $empty_key;
32  }
33 
39  public function getEmptyKey() {
40  return $this->token;
41  }
42 
54  public function decode($json, $assoc = false, $depth = 512, $options = 0) {
55  // Replace empty keys with the unique token
56  $json = preg_replace('~([^"\\\\])""\\s*\\:~', "$1\"{$this->token}\":", $json, -1, $count);
57 
58  return json_decode($json, $assoc, $depth, $options);
59  }
60 
70  public function encode($value, $options = 0, $depth = 512) {
71  if ($depth == 512) {
72  // PHP 5.4 and earlier will choke if depth is passed in
73  $json = json_encode($value, $options);
74  } else {
75  $json = json_encode($value, $options, $depth);
76  }
77 
78  // Replace unique tokens with empty strings
79  if (is_string($json)) {
80  $json = str_replace("\"{$this->token}\"", '""', $json);
81  }
82 
83  return $json;
84  }
85 }
$options
Elgg admin footer.
Definition: footer.php:6
getEmptyKey()
Get the key that represents an empty string key in JSON.
__construct($empty_key= '')
Constructor.
$value
Definition: debugging.php:7
decode($json, $assoc=false, $depth=512, $options=0)
Decode JSON while converting empty keys to a unique token.
if(elgg_in_context('widget')) $count
Definition: pagination.php:21
encode($value, $options=0, $depth=512)
Encode JSON while converting unique token keys to empty strings.