ManyToManyBehavior.php
16.8 KB
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
<?php
namespace thread\app\model\behaviors;
use Yii;
use yii\base\Behavior;
use yii\db\{
ActiveRecord, Exception
};
use yii\base\ErrorException;
use yii\helpers\ArrayHelper;
/**
* Class ManyToManyBehavior
* @package voskobovich\behaviors
*
* See README.md for examples
*/
class ManyToManyBehavior extends Behavior
{
/**
* Stores a list of relations, affected by the behavior. Configurable property.
* @var array
*/
public $relations = [];
/**
* Stores values of relation attributes. All entries in this array are considered
* dirty (changed) attributes and will be saved in saveRelations().
* @var array
*/
private $_values = [];
/**
* Used to store fields that this behavior creates. Each field refers to a relation
* and has optional getters and setters.
* @var array
*/
private $_fields = [];
/**
* namespace на Таблицу Many to Many . !! ОБЯЗАТЕЛЬНЫЙ ПАРАМЕТР ДЛЯ
* @var null
*/
const REL_TABLE = 'relTable';
/**
* Events list
* @return array
*/
public function events()
{
return [
ActiveRecord::EVENT_AFTER_INSERT => 'saveRelations',
ActiveRecord::EVENT_AFTER_UPDATE => 'saveRelations',
];
}
/**
* Invokes init of parent class and assigns proper values to internal _fields variable
*/
public function init()
{
parent::init();
//configure _fields
foreach ($this->relations as $attributeName => $params) {
//add primary field
$this->_fields[$attributeName] = [
'attribute' => $attributeName,
];
if (isset($params['get'])) {
$this->_fields[$attributeName]['get'] = $params['get'];
}
if (isset($params['set'])) {
$this->_fields[$attributeName]['set'] = $params['set'];
}
//add secondary fields
if (isset($params['fields'])) {
foreach ($params['fields'] as $fieldName => $params) {
$fullFieldName = $attributeName . '_' . $fieldName;
if (isset($this->_fields[$fullFieldName])) {
throw new ErrorException("Ambiguous field name definition: {$fullFieldName}");
}
$this->_fields[$fullFieldName] = [
'attribute' => $attributeName,
];
if (isset($params['get'])) {
$this->_fields[$fullFieldName]['get'] = $params['get'];
}
if (isset($params['set'])) {
$this->_fields[$fullFieldName]['set'] = $params['set'];
}
}
}
}
}
/**
* Save all dirty (changed) relation values ($this->_values) to the database
* @param $event
* @throws ErrorException
* @throws Exception
*/
public function saveRelations($event)
{
/**
* @var $primaryModel \yii\db\ActiveRecord
*/
$primaryModel = $this->owner;
if (is_array($primaryModelPk = $primaryModel->getPrimaryKey())) {
throw new ErrorException("This behavior does not support composite primary keys");
}
// Save relations data
foreach ($this->relations as $attributeName => $params) {
$relationName = $this->getRelationName($attributeName);
$relation = $primaryModel->getRelation($relationName);
/** Переписать бы на deleteAll но хз... как это сделать) */
$relTable = $params[self::REL_TABLE];
/** Чистим бд если нет не одного параметра */
if (!$this->hasNewValue($attributeName)) {
if (Yii::$app->getRequest()->isPost) {
if (is_array($relation->via)) {
$via = $relation->via[1];
list($junctionColumn) = array_keys($via->link);
} else {
list($junctionColumn) = array_keys($relation->via->link);
}
$relTable::deleteAll([$junctionColumn => $primaryModelPk]);
}
continue;
}
$newValue = $this->getNewValue($attributeName);
$bindingKeys = $newValue;
// many-to-many
if (!empty($relation->via) && $relation->multiple) {
//Assuming junction column is visible from the primary model connection
if (is_array($relation->via)) {
//via()
$via = $relation->via[1];
$junctionModelClass = $via->modelClass;
$junctionTable = $junctionModelClass::tableName();
list($junctionColumn) = array_keys($via->link);
} else {
//viaTable()
list($junctionTable) = array_values($relation->via->from);
list($junctionColumn) = array_keys($relation->via->link);
}
list($relatedColumn) = array_values($relation->link);
$connection = $primaryModel::getDb();
$transaction = $connection->beginTransaction();
try {
$delModels = $relTable::find()
->andWhere([$junctionColumn => $primaryModelPk])
->andWhere($this->getCustomDeleteCondition($attributeName))
->andWhere(['NOT IN', $relatedColumn, $newValue])
->all();
if ($delModels) {
foreach ($delModels as $model) {
$model->delete(false);
}
}
/** Получаем список $relatedColumn из бд */
$listCurrentModels = $relTable::find()->andWhere([$junctionColumn => $primaryModelPk])->all();
$relatedColumnIds = [];
if ($listCurrentModels) {
$relatedColumnIds = ArrayHelper::map($listCurrentModels, $relatedColumn, $relatedColumn);
}
// Write new relations
if (!empty($bindingKeys)) {
$junctionRows = [];
$viaTableParams = $this->getViaTableParams($attributeName);
foreach ($bindingKeys as $relatedPk) {
/** Не добавляем существующие поля */
if (!isset($relatedColumnIds[$relatedPk])) {
$row = [$primaryModelPk, $relatedPk];
// calculate additional viaTable values
foreach (array_keys($viaTableParams) as $viaTableColumn) {
$row[] = $this->getViaTableValue($attributeName, $viaTableColumn, $relatedPk);
}
array_push($junctionRows, $row);
}
}
$cols = [$junctionColumn, $relatedColumn];
// additional viaTable columns
foreach (array_keys($viaTableParams) as $viaTableColumn) {
$cols[] = $viaTableColumn;
}
if ($junctionRows) {
$connection->createCommand()
->batchInsert($junctionTable, $cols, $junctionRows)
->execute();
}
}
$transaction->commit();
} catch (Exception $ex) {
$transaction->rollback();
throw $ex;
}
// one-to-many on the many side
} elseif (!empty($relation->link) && $relation->multiple) {
//HasMany, primary model HAS MANY foreign models, must update foreign model table
$foreignModel = new $relation->modelClass();
$manyTable = $foreignModel->tableName();
list($manyTableFkColumn) = array_keys($relation->link);
$manyTableFkValue = $primaryModelPk;
list($manyTablePkColumn) = ($foreignModel->primaryKey());
$connection = $foreignModel::getDb();
$transaction = $connection->beginTransaction();
$defaultValue = $this->getDefaultValue($attributeName);
try {
// Remove old relations
$connection->createCommand()
->update(
$manyTable,
[$manyTableFkColumn => $defaultValue],
[$manyTableFkColumn => $manyTableFkValue])
->execute();
// Write new relations
if (!empty($bindingKeys)) {
$connection->createCommand()
->update(
$manyTable,
[$manyTableFkColumn => $manyTableFkValue],
['in', $manyTablePkColumn, $bindingKeys])
->execute();
}
$transaction->commit();
} catch (Exception $ex) {
$transaction->rollback();
throw $ex;
}
} else {
throw new ErrorException('Relationship type not supported.');
}
}
}
/**
* Call user function
* @param $function
* @param $value
* @return mixed
* @throws ErrorException
*/
private function callUserFunction($function, $value)
{
if (!is_array($function) && !$function instanceof \Closure) {
throw new ErrorException("This value is not a function");
}
return call_user_func($function, $value);
}
/**
* Check if an attribute is dirty and must be saved (its new value exists)
* @param string $attributeName
* @return null
*/
private function hasNewValue($attributeName)
{
return isset($this->_values[$attributeName]);
}
/**
* Get value of a dirty attribute by name
* @param string $attributeName
* @return null
*/
private function getNewValue($attributeName)
{
return $this->_values[$attributeName];
}
/**
* Get default value for an attribute (used for 1-N relations)
* @param string $attributeName
* @return mixed
*/
private function getDefaultValue($attributeName)
{
$relationParams = $this->getRelationParams($attributeName);
if (!isset($relationParams['default'])) {
return null;
} elseif ($relationParams['default'] instanceof \Closure) {
$function = $relationParams['default'];
$relationName = $this->getRelationName($attributeName);
return call_user_func($function, $this->owner, $relationName, $attributeName);
} else {
return $relationParams['default'];
}
}
/**
* Calculate additional value of viaTable
* @param string $attributeName
* @param string $viaTableAttribute
* @param integer $relatedPk
* @return mixed
*/
private function getViaTableValue($attributeName, $viaTableAttribute, $relatedPk)
{
$viaTableParams = $this->getViaTableParams($attributeName);
if (!isset($viaTableParams[$viaTableAttribute])) {
return null;
} elseif ($viaTableParams[$viaTableAttribute] instanceof \Closure) {
$closure = $viaTableParams[$viaTableAttribute];
$relationName = $this->getRelationName($attributeName);
return call_user_func($closure, $this->owner, $relationName, $attributeName, $relatedPk);
}
return $viaTableParams[$viaTableAttribute];
}
/**
* Get additional parameters of viaTable
* @param string $attributeName
* @return array
*/
private function getViaTableParams($attributeName)
{
$params = $this->getRelationParams($attributeName);
return isset($params['viaTableValues']) ? $params['viaTableValues'] : [];
}
/**
* Get custom condition used to delete old records.
* @param string $attributeName
* @return array
*/
private function getCustomDeleteCondition($attributeName)
{
$params = $this->getRelationParams($attributeName);
return isset($params['customDeleteCondition']) ? $params['customDeleteCondition'] : [];
}
/**
* Get parameters of a field
* @param string $fieldName
* @return mixed
* @throws ErrorException
*/
private function getFieldParams($fieldName)
{
if (empty($this->_fields[$fieldName])) {
throw new ErrorException("Parameter \"{$fieldName}\" does not exist");
}
return $this->_fields[$fieldName];
}
/**
* Get parameters of a relation
* @param string $attributeName
* @return mixed
* @throws ErrorException
*/
private function getRelationParams($attributeName)
{
if (empty($this->relations[$attributeName])) {
throw new ErrorException("Parameter \"{$attributeName}\" does not exist");
}
return $this->relations[$attributeName];
}
/**
* Get name of a relation
* @param string $attributeName
* @return null
*/
private function getRelationName($attributeName)
{
$params = $this->getRelationParams($attributeName);
if (is_string($params)) {
return $params;
} elseif (is_array($params) && !empty($params[0])) {
return $params[0];
}
return null;
}
/**
* Returns a value indicating whether a property can be read.
* We return true if it is one of our properties and pass the
* params on to the parent class otherwise.
*
* @param string $name the property name
* @param boolean $checkVars whether to treat member variables as properties
* @return boolean whether the property can be read
* @see canSetProperty()
*/
public function canGetProperty($name, $checkVars = true)
{
return array_key_exists($name, $this->_fields) ?
true : parent::canGetProperty($name, $checkVars);
}
/**
* Returns a value indicating whether a property can be set.
* We return true if it is one of our properties and pass the
* params on to the parent class otherwise.
*
* @param string $name the property name
* @param boolean $checkVars whether to treat member variables as properties
* @param boolean $checkBehaviors whether to treat behaviors' properties as properties of this component
* @return boolean whether the property can be written
* @see canGetProperty()
*/
public function canSetProperty($name, $checkVars = true, $checkBehaviors = true)
{
return array_key_exists($name, $this->_fields) ?
true : parent::canSetProperty($name, $checkVars, $checkBehaviors);
}
/**
* Returns the value of an object property.
* Get it from our local temporary variable if we have it,
* get if from DB otherwise.
*
* @param string $name the property name
* @return mixed the property value
* @see __set()
*/
public function __get($name)
{
$fieldParams = $this->getFieldParams($name);
$attributeName = $fieldParams['attribute'];
$relationName = $this->getRelationName($attributeName);
if ($this->hasNewValue($attributeName)) {
$value = $this->getNewValue($attributeName);
} else {
$relation = $this->owner->getRelation($relationName);
$foreignModel = new $relation->modelClass();
$value = $relation->select($foreignModel->getPrimaryKey())->column();
}
if (empty($fieldParams['get'])) {
return $value;
} else {
return $this->callUserFunction($fieldParams['get'], $value);
}
}
/**
* Sets the value of a component property. The data is passed
*
* @param string $name the property name or the event name
* @param mixed $value the property value
* @see __get()
*/
public function __set($name, $value)
{
$fieldParams = $this->getFieldParams($name);
$attributeName = $fieldParams['attribute'];
if (!empty($fieldParams['set'])) {
$this->_values[$attributeName] = $this->callUserFunction($fieldParams['set'], $value);
} else {
$this->_values[$attributeName] = $value;
}
}
}