1: <?php
2:
3: namespace Deimos\Helper\Helpers;
4:
5: use Deimos\Helper\AbstractHelper;
6:
7: class Json extends AbstractHelper
8: {
9:
10: const OPTIONS_ENCODE = 0;
11: const OPTIONS_DECODE = 1;
12:
13: /**
14: * first[level] array option type
15: * second[level] array option value
16: *
17: * @var int[][]
18: */
19: protected $options = [];
20:
21: /**
22: * @param int $value
23: * @param int $target
24: */
25: public function addOption($value, $target = self::OPTIONS_ENCODE)
26: {
27: $this->helper->arr()->initOrPush($this->options, $target, $value);
28: }
29:
30: /**
31: * @param array|int $data
32: * @param int $target
33: */
34: public function setOption($data, $target = self::OPTIONS_ENCODE)
35: {
36: $this->options[$target] = (array)$data;
37: }
38:
39: /**
40: * reset options
41: */
42: public function reset()
43: {
44: $this->options = [];
45: }
46:
47: /**
48: * @param $data
49: *
50: * @return string
51: */
52: public function encode($data)
53: {
54: return json_encode($data, $this->encodeOptions());
55: }
56:
57: /**
58: * @param string $data
59: * @param bool $assoc
60: *
61: * @return mixed
62: */
63: public function decode($data, $assoc = true)
64: {
65: return json_decode($data, $assoc, 512, $this->decodeOptions());
66: }
67:
68: /**
69: * @param int $target
70: *
71: * @return int
72: */
73: protected function options($target)
74: {
75: $options = JSON_ERROR_NONE;
76:
77: if (isset($this->options[$target]))
78: {
79: foreach ($this->options[$target] as $option)
80: {
81: $options |= $option;
82: }
83: }
84:
85: return $options;
86: }
87:
88: /**
89: * @return int
90: */
91: private function encodeOptions()
92: {
93: return $this->options(self::OPTIONS_ENCODE);
94: }
95:
96: /**
97: * @return int
98: */
99: private function decodeOptions()
100: {
101: return $this->options(self::OPTIONS_DECODE);
102: }
103:
104: }