1 <?php
2
3 4 5 6 7 8 9 10
11
12 namespace Icybee\Modules\Registry;
13
14 use ICanBoogie\Exception;
15 use ICanBoogie\ToArray;
16
17 18 19
20 class MetasHandler implements \ArrayAccess, ToArray
21 {
22 static private $models;
23
24 25 26 27 28
29 protected $targetid;
30
31 32 33 34 35
36 protected $values;
37
38 39 40 41 42
43 protected $model;
44
45 46 47 48 49 50 51
52 public function __construct(\ICanBoogie\ActiveRecord $target)
53 {
54 if ($target instanceof \Icybee\Modules\Nodes\Node)
55 {
56 $this->targetid = $target->nid;
57 $type = 'node';
58 }
59 else if ($target instanceof \Icybee\Modules\Users\User)
60 {
61 $this->targetid = $target->uid;
62 $type = 'user';
63 }
64 else if ($target instanceof \Icybee\Modules\Sites\Site)
65 {
66 $this->targetid = $target->siteid;
67 $type = 'site';
68 }
69 else
70 {
71 throw new Exception('Metadatas are not supported for instances of %class', [ '%class' => get_class($target) ]);
72 }
73
74 if (empty(self::$models[$type]))
75 {
76 self::$models[$type] = \ICanBoogie\ActiveRecord\get_model('registry/' . $type);
77 }
78
79 $this->model = self::$models[$type];
80 }
81
82 public function get($name, $default=null)
83 {
84 if ($this->values === null)
85 {
86 $this->values = $this->model
87 ->select('name, value')
88 ->filter_by_targetid($this->targetid)
89 ->order('name')
90 ->pairs;
91 }
92
93 if ($name == 'all')
94 {
95 return $this->values;
96 }
97
98 if (!isset($this->values[$name]))
99 {
100 return $default;
101 }
102
103 return $this->values[$name];
104 }
105
106 public function set($name, $value)
107 {
108 $this->values[$name] = $value;
109
110 if ($value === null)
111 {
112 $this->model->filter_by_targetid_and_name($this->targetid, $name)->delete();
113
114 return;
115 }
116
117 $this->model->insert([
118
119 'targetid' => $this->targetid,
120 'name' => $name,
121 'value' => $value
122
123 ], [ 'on duplicate' => true ]);
124 }
125
126 public function to_array()
127 {
128 return $this->get('all');
129 }
130
131 public function offsetSet($offset, $value)
132 {
133 $this->set($offset, $value);
134 }
135
136 public function offsetExists($offset)
137 {
138 return $this->get($offset) !== null;
139 }
140
141 public function offsetUnset($offset)
142 {
143 $this->set($offset, null);
144 }
145
146 public function offsetGet($offset)
147 {
148 return $this->get($offset);
149 }
150 }