1 <?php
2
3 4 5 6 7 8 9 10
11
12 namespace Icybee\Modules\Registry;
13
14 class Model extends \ICanBoogie\ActiveRecord\Model
15 {
16 static private function flatten($values, $prefix)
17 {
18 if ($prefix)
19 {
20 $prefix .= '.';
21 }
22
23 $flatten = [];
24
25 foreach ($values as $key => $value)
26 {
27 if (is_array($value))
28 {
29 $flatten = array_merge($flatten, self::flatten($value, $prefix . $key));
30
31 continue;
32 }
33
34 $flatten[$prefix . $key] = $value;
35 }
36
37 return $flatten;
38 }
39
40 protected $cached_values = [];
41
42 public function get($name, $default=null)
43 {
44 if ($default || !array_key_exists($name, $this->cached_values))
45 {
46 $length = strlen($name);
47
48 if ($name{$length - 1} == '.')
49 {
50 $rows = $this->where('name LIKE ?', $name . '%')->all(\PDO::FETCH_NUM);
51
52 $rc = $default ? $default : [];
53
54 foreach ($rows as $row)
55 {
56 list($name, $value) = $row;
57
58 $name = substr($name, $length);
59
60
61
62 $name = '[\'' . str_replace('.', "']['", $name) . '\']';
63
64
65
66 eval('$rc' . $name . ' = $value;');
67 }
68
69
70
71 $this->cached_values[$name] = $rc;
72 }
73 else
74 {
75 $rc = $this->select('value')->filter_by_name($name)->rc;
76
77 if ($rc === false)
78 {
79 $rc = $default;
80 }
81
82 $this->cached_values[$name] = $rc;
83 }
84 }
85
86 return $this->cached_values[$name];
87 }
88
89 90 91 92 93 94 95 96 97
98
99 public function set($name, $value)
100 {
101 $this->cached_values = [];
102
103 $name = (string) $name;
104
105 if (is_array($value))
106 {
107 $values = self::flatten($value, $name);
108
109 foreach ($values as $name => $value)
110 {
111 $this->set($name, $value);
112 }
113
114 return;
115 }
116
117 if ($value === null)
118 {
119 $this->where('name = ? OR name LIKE ?', $name, $name . '.%')->delete();
120
121 return;
122 }
123
124 $this->insert([ 'name' => $name, 'value' => $value ], [ 'on duplicate' => true ]);
125 }
126
127 public function offsetSet($offset, $value)
128 {
129 $this->set($offset, $value);
130 }
131
132 public function offsetExists($offset)
133 {
134 return $this->get($offset) !== null;
135 }
136
137 public function offsetUnset($offset)
138 {
139 $this->set($offset, null);
140 }
141
142 public function offsetGet($offset)
143 {
144 return $this->get($offset);
145 }
146 }