Core  3.2
PHP API documentation
 All Data Structures Namespaces Files Functions Variables Pages
Class.JSONCodec.php
Go to the documentation of this file.
1 <?php
2 /*
3  * @author Anakeen
4  * @package FDL
5  */
6 /**
7  * The JSONCodec class simplify JSON encoding/decoding errors handling
8  * by throwing Dcp\Exceptions, with corresponding JSON error constant,
9  * instead of returning null on errors (which could be mistaken with
10  * valid JSON null values for example).
11  */
12 class JSONCodec
13 {
14  private $json_errors = null;
15  /**
16  * Decode JSON string
17  *
18  * @param string $json see $json from PHP's json_decode()
19  * @param bool $assoc see $assoc from PHP's json_decode()
20  * @param int $depth see $depth from PHP's json_decode()
21  * @return mixed|null returns the resulting PHP structure
22  * @throws Dcp\Exception Exception is throwned on error
23  */
24  public function decode($json, $assoc = false, $depth = 512)
25  {
26  /* Circumvent PHP bug 54484 <https://bugs.php.net/bug.php?id=54484> */
27  if ($json === '' || $json === null) {
28  return null;
29  }
30  $o = json_decode($json, $assoc, $depth);
31  if ($o === null) {
32  $errCode = json_last_error();
33  if ($errCode == JSON_ERROR_NONE) {
34  return null;
35  }
36  throw new Dcp\Exception($this->getErrorMsg($errCode));
37  }
38  return $o;
39  }
40  /**
41  * Encode value into JSON string
42  *
43  * @param mixed $value see $value from PHP's json_encode()
44  * @param int $options see $options from PHP's json_encode()
45  * @return string returnes the resulting JSON string
46  * @throws Dcp\Exception Exception is throwned on error
47  */
48  public function encode($value, $options = 0)
49  {
50  $str = json_encode($value, $options);
51  if ($str === false) {
52  $errCode = json_last_error();
53  throw new Dcp\Exception($this->getErrorMsg($errCode));
54  }
55  return $str;
56  }
57  /**
58  * Get the JSON error constant name for the given JSON error code.
59  *
60  * @param int $errCode The JSON last error code (from json_last_error())
61  * @return string The JSON error constant name (e.g. "JSON_ERROR_SYNTAX")
62  */
63  private function getErrorMsg($errCode)
64  {
65  if ($this->json_errors === null) {
66  $constants = get_defined_constants(true);
67  foreach ($constants["json"] as $name => $value) {
68  if (!strncmp($name, "JSON_ERROR_", 11)) {
69  $this->json_errors[$value] = $name;
70  }
71  }
72  }
73  return $this->json_errors[$errCode];
74  }
75 }
Exception class use exceptionCode to identifiy correctly exception.
Definition: exceptions.php:19
decode($json, $assoc=false, $depth=512)
if($dbaccess=="") $o
encode($value, $options=0)
$value
← centre documentaire © anakeen