Elgg  Version 2.2
 All Classes Namespaces Files Functions Variables Pages
EmptyKeyEncoding.php
Go to the documentation of this file.
1 <?php
2 namespace Elgg\Json;
3 
15 
19  protected $token;
20 
26  public function __construct($empty_key = '') {
27  if (!$empty_key) {
28  $empty_key = sha1(microtime(true) . mt_rand());
29  }
30  $this->token = $empty_key;
31  }
32 
38  public function getEmptyKey() {
39  return $this->token;
40  }
41 
53  public function decode($json, $assoc = false, $depth = 512, $options = 0) {
54  // Replace empty keys with the unique token
55  $json = preg_replace('~([^"\\\\])""\\s*\\:~', "$1\"{$this->token}\":", $json, -1, $count);
56 
57  return json_decode($json, $assoc, $depth, $options);
58  }
59 
69  public function encode($value, $options = 0, $depth = 512) {
70  if ($depth == 512) {
71  // PHP 5.4 and earlier will choke if depth is passed in
72  $json = json_encode($value, $options);
73  } else {
74  $json = json_encode($value, $options, $depth);
75  }
76 
77  // Replace unique tokens with empty strings
78  if (is_string($json)) {
79  $json = str_replace("\"{$this->token}\"", '""', $json);
80  }
81 
82  return $json;
83  }
84 }
$value
Definition: longtext.php:26
$options
Elgg admin footer.
Definition: footer.php:6
getEmptyKey()
Get the key that represents an empty string key in JSON.
__construct($empty_key= '')
Constructor.
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.