-
Notifications
You must be signed in to change notification settings - Fork 15
/
EEavBehavior.php
550 lines (510 loc) · 17.2 KB
/
EEavBehavior.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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
<?php
/**
* EEavBehavior class file.
*
* Entity-Attribute-Value behavior.
* Allows model to work with custom fields on the fly (EAV pattern).
*
* @author Veaceslav Medvedev <[email protected]>
* @link http://code.google.com/p/yiiext/
*
* @version 0.5
*/
class EEavBehavior extends CActiveRecordBehavior {
/**
* @access public
* @var string name of the table where data is stored. Required to be set on init behavior.
* @default ''
*/
public $tableName = '';
/**
* @access public
* @var string prefix for each attribute.
* @default ''
*/
public $attributesPrefix = '';
/**
* @access protected
* @var string owner model FK name. If not set automatically assign to model's primaryKey.
* @default ''
*/
protected $modelTableFk = '';
/**
* @access public
* @var string name of the column to store entity name.
* @default 'entity'
*/
public $entityField = 'entity';
/**
* @access public
* @var string name of the column to store attribute key.
* @default 'attribute'
*/
public $attributeField = 'attribute';
/**
* @access public
* @var string name of the column to store value.
* @default 'value'
*/
public $valueField = 'value';
/**
* @access public
* @var string caching component Id.
* @default ''
*/
public $cacheId = '';
/**
* @access protected
* @var ICache cache component object.
* @default NULL
*/
protected $cache = NULL;
/**
* @access protected
* @var CAttributeCollection attributes store.
* @default new CAttributeCollection
*/
protected $attributes = NULL;
/**
* @access protected
* @var CList changed attributes list.
* @default new CList
*/
protected $changedAttributes = NULL;
/**
* @access protected
* @var CList safe attributes list.
* @default new CList
*/
protected $safeAttributes = NULL;
/**
* @access public
* @var boolean loaded attributes after find model.
* @default TRUE
*/
public $preload = TRUE;
/**
* Returns owner model id.
* @access protected
* @return mixed
*/
protected function getModelId() {
return $this->getOwner()->{$this->getModelTableFk()};
}
/**
* Returns key for caching model attributes.
* @access protected
* @return string
*/
protected function getCacheKey() {
return __CLASS__ . $this->tableName . $this->attributesPrefix . $this->getOwner()->tableName() . $this->getModelId();
}
/**
* Set owner model FK name.
* @param string owner model FK name.
* @return void
*/
public function setModelTableFk($modelTableFk) {
if (is_string($modelTableFk) && !empty($modelTableFk)) {
$this->modelTableFk = $modelTableFk;
}
}
/**
* Returns owner model FK name.
* @access protected
* @throws CException
* @return string
*/
protected function getModelTableFk() {
// Check required property modelTableFk.
if (empty($this->modelTableFk) || !$this->getOwner()->hasAttribute($this->modelTableFk)) {
// If property modelTableFk not set, trying to get a primary key from model table.
$this->modelTableFk = $this->getOwner()->getTableSchema()->primaryKey;
if(!is_string($this->modelTableFk)) {
throw new CException(Yii::t('yiiext', 'Table "{table}" does not have a primary key defined.',
array('{table}' => $this->getOwner()->getTableSchema())));
}
}
return $this->modelTableFk;
}
/**
* Strip prefix from attribute key.
* @access protected
* @param string attribute key
* @return string
*/
protected function stripPrefix($attribute) {
// Remove prefix if exists.
if (!empty($this->attributesPrefix) && strpos($attribute, $this->attributesPrefix) === 0) {
$attribute = substr($attribute, strlen($this->attributesPrefix));
}
return $attribute;
}
/**
* Set safe attributes array.
* @param array safe attributes.
* @return void
*/
public function setSafeAttributes($safeAttributes) {
$this->safeAttributes->copyFrom($safeAttributes);
}
/**
* Return safe attributes key. If not set returns all keys.
* @access protected
* @return array
*/
protected function getSafeAttributesArray() {
return $this->safeAttributes->count() == 0 ? $this->attributes->keys : $this->safeAttributes->toArray();
}
/**
* @access protected
* @param string attribute key
* @return boolean
*/
protected function hasSafeAttribute($attribute) {
if ($this->safeAttributes->count() > 0) {
return $this->safeAttributes->contains($attribute);
}
return TRUE;
}
/**
* @return void
*/
public function __construct() {
// Prepare attributes collection.
$this->attributes = new CAttributeCollection;
$this->attributes->caseSensitive = TRUE;
// Prepare safe attributes list.
$this->safeAttributes = new CList;
// Prepare changed attributes list.
$this->changedAttributes = new CList;
}
/**
* @throws CException
* @param CComponent
* @return void
*/
public function attach($owner) {
// Check required property tableName.
if (!is_string($this->tableName) || empty($this->tableName)) {
throw new CException(self::t('yii', 'Property "{class}.{property}" is not defined.',
array('{class}' => get_class($this), '{property}' => 'tableName')));
}
// Prepare translate component for behavior messages.
if (!Yii::app()->hasComponent(__CLASS__ . 'Messages')) {
Yii::app()->setComponents(array(
__CLASS__ . 'Messages' => array(
'class' => 'CPhpMessageSource',
'basePath' => dirname(__FILE__) . DIRECTORY_SEPARATOR . 'messages',
)
));
}
// Prepare cache component.
$this->cache = Yii::app()->getComponent($this->cacheId);
if (!($this->cache instanceof ICache)) {
// If not set cache component, use dummy cache.
$this->cache = new CDummyCache;
}
// Call parent method for convenience.
parent::attach($owner);
}
/**
* @param CEvent
* @return void
*/
public function afterSave($event) {
// TODO afterSave не срабатывает если модель не была изменена
// Save changed attributes.
if ($this->changedAttributes->count > 0) {
$this->saveEavAttributes($this->changedAttributes->toArray());
}
// Call parent method for convenience.
parent::afterSave($event);
}
/**
* @param CEvent
* @return void
*/
public function afterDelete($event) {
// Delete all attributes.
$this->deleteEavAttributes(array(), TRUE);
// Call parent method for convenience.
parent::afterDelete($event);
}
/**
* @param CEvent
* @return void
*/
public function afterFind($event) {
// Load attributes for model.
if ($this->preload) {
$this->loadEavAttributes($this->getSafeAttributesArray());
}
// Call parent method for convenience.
parent::afterFind($event);
}
/**
* @param array attributes key for save.
* @return CActiveRecord
*/
public function saveEavAttributes($attributes) {
// Delete old attributes values from DB.
$this->getDeleteCommand($attributes)->execute();
// Process each attributes.
foreach ($attributes as $attribute) {
// Skip if null attributes.
if (!is_null($values = $this->attributes->itemAt($attribute))) {
// Create array of values for convenience.
if (!is_array($values)) {
$values = array($values);
}
// Save each value of attribute into DB.
foreach ($values as $value) {
$this->getSaveEavAttributeCommand($this->attributesPrefix . $attribute, $value)->execute();
}
// Remove from changed list.
$this->changedAttributes->remove($attribute);
}
}
// Save attributes to cache.
if ($this->attributes->count > 0) {
$this->cache->set($this->getCacheKey(), $this->attributes->toArray());
}
// Or delete cache is attributes not exists.
else {
$this->cache->delete($this->getCacheKey());
}
// Return model.
return $this->getOwner();
}
/**
* @access public
* @param array attributes key for load.
* @return CActiveRecord
*/
public function loadEavAttributes($attributes) {
// If exists cache, return it.
$data = $this->cache->get($this->getCacheKey());
if ($data !== FALSE) {
$this->attributes->mergeWith($data, FALSE);
return $this->getOwner();
}
// Query DB.
$data = $this->getLoadEavAttributesCommand($attributes)->query();
foreach($data as $row) {
$attribute = $this->stripPrefix($row[$this->attributeField]);
$value = $row[$this->valueField];
// Check if value exists.
if (!is_null($current = $this->attributes->itemAt($attribute)) && $current != $value) {
$value = is_array($current) ? $current[] = $value : array($current, $value);
}
$this->attributes->add($attribute, $value);
}
// Save loaded attributes to cache.
$this->cache->set($this->getCacheKey(), $this->attributes->toArray());
// Return model.
return $this->getOwner();
}
/**
* @param array attributes key for delete.
* @param boolean whether auto save attributes.
* @return CActiveRecord
*/
public function deleteEavAttributes($attributes = array(), $save = FALSE) {
// If not set attributes for deleting, delete all.
if (empty($attributes)) {
$attributes = $this->attributes->keys;
}
// Delete each attributes.
foreach ($attributes as $attribute) {
$this->attributes->remove($attribute);
$this->changedAttributes->add($attribute);
}
// Auto save if set.
if ($save) {
$this->saveEavAttributes($attributes);
}
// Return model.
return $this->getOwner();
}
/**
* @param array attributes values for change.
* @param boolean whether auto save attributes.
* @return CActiveRecord
*/
public function setEavAttributes($attributes, $save = FALSE) {
foreach ($attributes as $attribute => $value) {
$this->attributes->add($attribute, $value);
$this->changedAttributes->add($attribute);
}
// Auto save if set.
if ($save) {
$this->saveEavAttributes(array_keys($attributes));
}
// Return model.
return $this->getOwner();
}
/**
* @param string attribute key.
* @param mixed attribute value.
* @param boolean whether auto save attributes.
* @return CActiveRecord
*/
public function setEavAttribute($attribute, $value, $save = FALSE) {
return $this->setEavAttributes(array($attribute => $value), $save);
}
/**
* @param array attributes key for get.
* @return array
*/
public function getEavAttributes($attributes = array()) {
// Get all attributes if not specified.
if (empty($attributes)) {
$attributes = $this->getSafeAttributesArray();
}
// Values array.
$values = array();
// Queue for load.
$loadQueue = new CList;
foreach ($attributes as $attribute) {
// Check is safe.
if ($this->hasSafeAttribute($attribute)) {
$values[$attribute] = $this->attributes->itemAt($attribute);
// If attribute not set and not load, prepare array for loaded.
if (!$this->preload && $values[$attribute] === NULL) {
$loadQueue->add($attribute);
}
}
}
// If array for loaded not empty, load attributes.
if (!$this->preload && $loadQueue->count() > 0) {
$this->loadEavAttributes($loadQueue->toArray());
foreach ($loadQueue as $attribute) {
$values[$attribute] = $this->attributes->itemAt($attribute);
}
}
// Delete load queue.
unset($loadQueue);
// Return values.
return $values;
}
/**
* @param string attribute for get.
* @return mixed
*/
public function getEavAttribute($attribute) {
$values = $this->getEavAttributes(array($attribute));
return $this->attributes->itemAt($attribute);
}
/**
* Limit current AR query to have all attributes and values specified.
* @param array attributes values or key for filter models.
* @return CActiveRecord
*/
public function withEavAttributes($attributes = array()) {
// If not set attributes, search models with anything attributes exists.
if (empty($attributes)) {
$attributes = $this->getSafeAttributesArray();
}
// $attributes be array of elements: $attribute => $values
$criteria = $this->getFindByEavAttributesCriteria($attributes);
// Merge model criteria.
$this->getOwner()->getDbCriteria()->mergeWith($criteria);
// Return model.
return $this->getOwner();
}
/**
* @access protected
* @param $attribute
* @param $value
* @return CDbCommand
*/
protected function getSaveEavAttributeCommand($attribute, $value) {
$data = array(
$this->entityField => $this->getModelId(),
$this->attributeField => $attribute,
$this->valueField => $value,
);
return $this->getOwner()
->getCommandBuilder()
->createInsertCommand($this->tableName, $data);
}
/**
* @access protected
* @param $attributes
* @return CDbCommand
*/
protected function getLoadEavAttributesCommand($attributes) {
return $this->getOwner()
->getCommandBuilder()
->createFindCommand($this->tableName, $this->getLoadEavAttributesCriteria($attributes));
}
/**
* @access protected
* @param $attributes
* @return CDbCommand
*/
protected function getDeleteCommand($attributes = array()) {
return $this->getOwner()
->getCommandBuilder()
->createDeleteCommand($this->tableName, $this->getDeleteEavAttributesCriteria($attributes));
}
/**
* @access protected
* @param $attributes
* @return CDbCriteria
*/
protected function getLoadEavAttributesCriteria($attributes = array()) {
$criteria = new CDbCriteria;
$criteria->compare($this->entityField, $this->getModelId());
if (!empty($attributes)) {
$criteria->addInCondition($this->attributeField, $attributes);
}
return $criteria;
}
/**
* @access protected
* @param $attributes
* @return CDbCriteria
*/
protected function getDeleteEavAttributesCriteria($attributes = array()) {
return $this->getLoadEavAttributesCriteria($attributes);
}
/**
* @access protected
* @param $attributes
* @return CDbCriteria
*/
protected function getFindByEavAttributesCriteria($attributes){
$criteria = new CDbCriteria();
$pk = $this->getModelTableFk();
$conn = $this->getOwner()->getDbConnection();
$i = 0;
foreach ($attributes as $attribute => $values) {
// If search models with attribute name with specified values.
if (is_string($attribute)) {
$attribute = $conn->quoteValue($attribute);
if (!is_array($values)) $values = array($values);
foreach ($values as $value) {
$value = $conn->quoteValue($value);
$criteria->join .= "\nJOIN {$this->tableName} eavb$i"
. "\nON t.{$pk} = eavb$i.{$this->entityField}"
. "\nAND eavb$i.{$this->attributeField} = $attribute"
. "\nAND eavb$i.{$this->valueField} = $value";
$i++;
}
}
// If search models with attribute name with anything values.
elseif (is_int($attribute)) {
$values = $conn->quoteValue($values);
$criteria->join .= "\nJOIN {$this->tableName} eavb$i"
. "\nON t.{$pk} = eavb$i.{$this->entityField}"
. "\nAND eavb$i.{$this->attributeField} = $values";
$i++;
}
}
$criteria->distinct = TRUE;
$criteria->group .= "t.{$pk}";
return $criteria;
}
}