-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathMetaActiveRecord.php
299 lines (256 loc) · 6.54 KB
/
MetaActiveRecord.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
<?php
/**
* @author Chaim Leichman, MIPO Technologies Ltd
*/
namespace mipotech\metaActiveRecord;
use Yii;
use yii\db\ActiveRecord;
use yii\db\Query;
use yii\db\Schema;
abstract class MetaActiveRecord extends ActiveRecord
{
/** @var boolean $autoLoadMetaData Whether meta data should be loaded */
protected $autoLoadMetaData = true;
/** @var boolean $autoSaveMetaFields Whether meta data should be loaded */
protected $autoSaveMetaFields = false;
/** @var mixed $metaData Array of the this record's meta data */
protected $metaData = null;
/** @var array $metaDataUpdateQueue Queue of meta data key-value pairs to update */
protected $metaDataUpdateQueue = array();
/**
* Override __get of yii\db\ActiveRecord
*
* @param string $name the property name
* @return mixed
*/
public function __get($name)
{
if($this->hasAttribute($name))
return parent::__get($name);
else
return $this->getMetaAttribute($name);
}
/**
* Override __get of yii\db\ActiveRecord
*
* @param string $name the property name or the event name
* @param mixed $value the property value
*/
public function __set($name, $value)
{
if ($this->hasAttribute($name))
parent::__set($name, $value);
else
{
if ($this->autoSaveMetaFields && !$this->isNewRecord)
$this->setMetaAttribute($name, $value);
else
$this->enqueueMetaUpdate($name, $value);
}
}
/**
* Catch the afterFind event to load the meta data if the
* $autoLoadMetaData flag is set to true
*
*/
public function afterFind()
{
if ($this->autoLoadMetaData)
$this->loadMetaData();
parent::afterFind();
}
/**
* Catch the afterSave event to save all of the queued meta data
*
*/
public function afterSave($insert, $changedAttributes)
{
$queue = $this->metaDataUpdateQueue;
if (is_array($queue) && count($queue))
{
foreach ($queue as $name => $value)
$this->setMetaAttribute($name, $value);
$this->metaDataUpdateQueue = array();
}
parent::afterSave($insert, $changedAttributes);
}
/**
* Enqueue a meta key-value pair to be saved when the record is saved
*
* @param string $name the property name or the event name
* @param mixed $value the property value
*/
protected function enqueueMetaUpdate($name, $value)
{
if(!is_array($this->metaDataUpdateQueue))
$this->metaDataUpdateQueue = array();
$this->metaDataUpdateQueue[$name] = $value;
}
/**
* Load the meta data for this record
*
* @return void
*/
protected function loadMetaData()
{
$rows = (new Query)
->select('*')
->from($this->metaTableName())
->where([
'record_id' => $this->{$this->getPkName()}
])
->all();
$this->metaData = $rows;
}
/**
* Return the name of the meta table associated with this model
*
* @return string
*/
public function metaTableName()
{
$tblName = self::tableName();
// Add _meta prefix to parent table name
$tblName = str_replace('}}', '_meta}}', $tblName);
// Resolve the actual name of the meta table
$tblName = str_replace('{{%', Yii::$app->db->tablePrefix ?: '', $tblName);
$tblName = str_replace('}}', '', $tblName);
return $tblName;
}
/**
* @link https://github.com/yiisoft/yii2/issues/6533
* @return string
*/
public function getDbName()
{
$db = Yii::$app->db;
$dsn = $db->dsn;
$name = 'dbname';
if (preg_match('/' . $name . '=([^;]*)/', $dsn, $match)) {
return $match[1];
} else {
return null;
}
}
/**
* @param boolean $autoCreate Create the table if it does not exist
* @return boolean If table exists
*/
protected function assertMetaTable($autoCreate = false)
{
$row = (new Query)
->select('*')
->from('information_schema.tables')
->where([
'table_schema' => $this->getDbName(),
'table_name' => $this->metaTableName()
])
->limit(1)
->all();
if(null === $row)
{
if($autoCreate)
{
$this->createMetaTable();
return true;
}
else
return false;
}
else
return true;
}
/**
*
*/
protected function createMetaTable()
{
$db = Yii::$app->db;
$tbl = $this->metaTableName();
$ret = $db
->createCommand()
->createTable($tbl, [
'id' => Schema::TYPE_BIGPK,
'record_id' => Schema::TYPE_BIGINT.' NOT NULL default \'0\'',
'meta_key' => Schema::TYPE_STRING.' default NULL',
'meta_value'=> 'longtext',
], 'ENGINE=MyISAM DEFAULT CHARSET=utf8')
->execute();
if($ret)
{
$db
->createCommand()
->createIndex('UNIQUE_META_RECORD', $tbl, ['record_id', 'meta_key'], true)
->execute();
}
return $ret;
}
protected function getPkName()
{
$pk = $this->primaryKey();
$pk = $pk[0];
return $pk;
}
/**
* Return the value of the named meta attribute
*
* @param string $name Property name
* @return mixed Property value
*/
protected function getMetaAttribute($name)
{
if(!$this->assertMetaTable())
return null;
$row = (new Query)
->select('meta_value')
->from($this->metaTableName())
->where([
'record_id' => $this->{$this->getPkName()},
'meta_key' => $name
])
->limit(1)
->one();
return is_array($row) ? $row['meta_value'] : null;
}
/**
* Set the value of the named meta attribute
*
* @param string $name the property name or the event name
* @param mixed $value the property value
*/
protected function setMetaAttribute($name, $value)
{
// Assert that the meta table exists,
// and create it if it does not
$this->assertMetaTable(true);
$db = Yii::$app->db;
$tbl = $this->metaTableName();
$pk = $this->getPkName();
// Check if we need to create a new record or update an existing record
$currentVal = $this->getMetaAttribute($name);
if(is_null($currentVal))
{
$ret = $db
->createCommand()
->insert($tbl, [
'record_id' => $this->{$pk},
'meta_key' => $name,
'meta_value'=> is_scalar($value) ? $value : serialize($value)
])
->execute();
}
else
{
$ret = $db
->createCommand()
->update($tbl, [
'meta_value'=> is_scalar($value) ? $value : serialize($value)
], "record_id = '{$this->$pk}' AND meta_key = '{$name}'")
->execute();
}
// If update succeeded, save the new value right away
if($ret)
$this->metaData[$name] = $value;
return $ret;
}
}