-
Notifications
You must be signed in to change notification settings - Fork 21
/
WithRelatedBehavior.php
442 lines (379 loc) · 13.4 KB
/
WithRelatedBehavior.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
<?php
/**
* WithRelatedBehavior class file.
*
* @author Alexander Kochetov <[email protected]>
* @link https://github.com/yiiext/with-related-behavior
*/
/**
* Allows you to save related models along with the main model.
* All relation types are supported.
*
* @property CActiveRecord $owner
* @method CActiveRecord getOwner()
*
* @version 0.65
* @package yiiext.with-related-behavior
*/
class WithRelatedBehavior extends CActiveRecordBehavior
{
/**
* Validate main model and all it's related models recursively.
* @param array $data attributes and relations.
* @param boolean $clearErrors whether to call {@link CModel::clearErrors} before performing validation.
* @param CActiveRecord $owner for internal needs.
* @return boolean whether the validation is successful without any error.
*/
public function validate($data=null,$clearErrors=true,$owner=null)
{
if($owner===null)
$owner=$this->getOwner();
if($data===null)
{
$attributes=null;
$newData=array();
}
else
{
// retrieve real class attributes that was specified in the class declaration
$classAttributes=get_class_vars(get_class($owner));
unset($classAttributes['db']); // has nothing in common with the application logic
$classAttributes=array_keys($classAttributes);
// mixing virtual attributes that represents database table columns with real class attributes
$attributeNames=array_merge($classAttributes,$owner->attributeNames());
// array_intersect must not be used here because when error_reporting is -1 notice will happen
// since $data array contains not just scalar string values
$attributes=array_uintersect($data,$attributeNames,
create_function('$x,$y','return !is_string($x) || !is_string($y) ? -1 : strcmp($x,$y);'));
if($attributes===array())
$attributes=null;
// array_udiff must not be used here because when error_reporting is -1 notice will happen
// since $data array contains not just scalar string values
$newData=array_udiff($data,$attributeNames,
create_function('$x,$y','return !is_string($x) || !is_string($y) ? -1 : strcmp($x,$y);'));
}
$valid=$owner->validate($attributes,$clearErrors);
foreach($newData as $name=>$data)
{
if(!is_array($data))
$name=$data;
if(!$owner->hasRelated($name))
continue;
/** @var CActiveRecord|CActiveRecord[] $related */
$related=$owner->getRelated($name);
if(is_array($related))
{
foreach($related as $model)
{
if(is_array($data))
$valid=$this->validate($data,$clearErrors,$model) && $valid;
else
$valid=$model->validate(null,$clearErrors) && $valid;
}
}
else
{
if(is_array($data))
$valid=$this->validate($data,$clearErrors,$related) && $valid;
else
$valid=$related->validate(null,$clearErrors) && $valid;
}
}
return $valid;
}
/**
* @param array|string $foreignKey
* @param CDbTableSchema $ownerTableSchema
* @param CDbTableSchema $dependentTableSchema
* @return array
*/
protected function getDependencyAttributes($foreignKey, $ownerTableSchema, $dependentTableSchema)
{
$dbSchema = $this->getOwner()->getDbConnection()->getSchema();
$map = array();
if(is_string($foreignKey))
$foreignKey=preg_split('/\s*,\s*/',$foreignKey,-1,PREG_SPLIT_NO_EMPTY);
foreach($foreignKey as $fk=>$pk)
{
if(is_int($fk))
{
$index = $fk;
$fk = $pk;
if(isset($ownerTableSchema->foreignKeys[$fk]) && $dbSchema->compareTableNames($dependentTableSchema->rawName,$ownerTableSchema->foreignKeys[$fk][0]))
$pk=$ownerTableSchema->foreignKeys[$fk][1];
else // FK constraints undefined
{
if(is_array($dependentTableSchema->primaryKey)) // composite PK
$pk=$dependentTableSchema->primaryKey[$index];
else
$pk=$dependentTableSchema->primaryKey;
}
}
$map[$fk] = $pk;
}
return $map;
}
/**
* Save main model and all it's related models recursively.
* @param bool $runValidation whether to perform validation before saving the record.
* @param array $data attributes and relations.
* @param CActiveRecord $owner for internal needs.
* @return boolean whether the saving succeeds.
* @throws CDbException
* @throws Exception
*/
public function save($runValidation=true,$data=null,$owner=null)
{
if($owner===null)
{
if($runValidation && !$this->validate($data))
return false;
$owner=$this->getOwner();
}
/** @var CDbConnection $db */
$db=$owner->getDbConnection();
if($db->getCurrentTransaction()===null)
$transaction=$db->beginTransaction();
try
{
if($data===null)
{
$attributes=null;
$newData=array();
}
else
{
// not mixing virtual attributes that represents database table columns with real class attributes
// since real class attributes shouldn't be persisted in the database, it's actual only for validation part
$attributeNames=$owner->attributeNames();
// array_intersect must not be used here because when error_reporting is -1 notice will happen
// since $data array contains not just scalar string values
$attributes=array_uintersect($data,$attributeNames,
create_function('$x,$y','return !is_string($x) || !is_string($y) ? -1 : strcmp($x,$y);'));
if($attributes===array())
$attributes=null;
// array_diff must not be used here because when error_reporting is -1 notice will happen
// since $data array contains not just scalar string values
$newData=array_udiff($data,$attributeNames,
create_function('$x,$y','return !is_string($x) || !is_string($y) ? -1 : strcmp($x,$y);'));
}
$ownerTableSchema=$owner->getTableSchema();
/** @var CDbCommandBuilder $builder */
$builder=$owner->getCommandBuilder();
$schema=$builder->getSchema();
$relations=$owner->getMetaData()->relations;
$queue=array();
foreach($newData as $name=>$data)
{
if(!is_array($data))
{
$name=$data;
$data=null;
}
if(!$owner->hasRelated($name))
continue;
$relationClass=get_class($relations[$name]);
$relatedClass=$relations[$name]->className;
if($relationClass===CActiveRecord::BELONGS_TO)
{
/** @var CActiveRecord|CActiveRecord[] $related */
$related=$owner->getRelated($name);
$relatedTableSchema=$related->getTableSchema();
if($data!==null)
$this->save(false,$data,$related);
else
$related->getIsNewRecord() ? $related->insert() : $related->update();
$fks = $relations[$name]->foreignKey;
$map = $this->getDependencyAttributes($fks, $relatedTableSchema, $ownerTableSchema);
foreach ($map as $fk => $pk) {
$owner->$fk = $related->$pk;
}
}
else
$queue[]=array($relationClass,$relatedClass,$relations[$name]->foreignKey,$name,$data);
}
if(!($owner->getIsNewRecord() ? $owner->insert($attributes) : $owner->update($attributes)))
return false;
foreach($queue as $pack)
{
list($relationClass,$relatedClass,$fks,$name,$data)=$pack;
$related=$owner->getRelated($name);
$relatedTableSchema=CActiveRecord::model($relatedClass)->getTableSchema();
switch($relationClass)
{
case CActiveRecord::HAS_ONE:
$map = $this->getDependencyAttributes($fks, $ownerTableSchema, $relatedTableSchema);
foreach ($map as $fk => $pk) {
$related->$fk = $owner->$pk;
}
if($data===null)
$related->getIsNewRecord() ? $related->insert() : $related->update();
else
$this->save(false,$data,$related);
break;
case CActiveRecord::HAS_MANY:
$map = $this->getDependencyAttributes($fks, $ownerTableSchema, $relatedTableSchema);
foreach($related as $model)
{
foreach($map as $fk=>$pk)
$model->$fk = $owner->$pk;
if($data===null)
$model->getIsNewRecord() ? $model->insert() : $model->update();
else
$this->save(false,$data,$model);
}
break;
case CActiveRecord::MANY_MANY:
if(!preg_match('/^\s*(.*?)\((.*)\)\s*$/',$fks,$matches))
throw new CDbException(Yii::t('yiiext','The relation "{relation}" in active record class "{class}" is specified with an invalid foreign key. The format of the foreign key must be "joinTable(fk1,fk2,...)".',
array('{class}'=>get_class($owner),'{relation}'=>$name)));
if(($joinTable=$schema->getTable($matches[1]))===null)
throw new CDbException(Yii::t('yiiext','The relation "{relation}" in active record class "{class}" is not specified correctly: the join table "{joinTable}" given in the foreign key cannot be found in the database.',
array('{class}'=>get_class($owner),'{relation}'=>$name,'{joinTable}'=>$matches[1])));
$fks=preg_split('/\s*,\s*/',$matches[2],-1,PREG_SPLIT_NO_EMPTY);
$ownerMap=array();
$relatedMap=array();
$fkDefined=true;
foreach($fks as $fk)
{
if(!isset($joinTable->columns[$fk]))
throw new CDbException(Yii::t('yii','The relation "{relation}" in active record class "{class}" is specified with an invalid foreign key "{key}". There is no such column in the table "{table}".',
array('{class}'=>get_class($owner),'{relation}'=>$name,'{key}'=>$fk,'{table}'=>$joinTable->name)));
if(isset($joinTable->foreignKeys[$fk]))
{
list($tableName,$pk)=$joinTable->foreignKeys[$fk];
if(!isset($ownerMap[$pk]) && $schema->compareTableNames($ownerTableSchema->rawName,$tableName))
$ownerMap[$pk]=$fk;
else if(!isset($relatedMap[$pk]) && $schema->compareTableNames($relatedTableSchema->rawName,$tableName))
$relatedMap[$pk]=$fk;
else
{
$fkDefined=false;
break;
}
}
else
{
$fkDefined=false;
break;
}
}
if(!$fkDefined)
{
$ownerMap=array();
$relatedMap=array();
foreach($fks as $i=>$fk)
{
if($i<count($ownerTableSchema->primaryKey))
{
$pk=is_array($ownerTableSchema->primaryKey) ? $ownerTableSchema->primaryKey[$i] : $ownerTableSchema->primaryKey;
$ownerMap[$pk]=$fk;
}
else
{
$j=$i-count($ownerTableSchema->primaryKey);
$pk=is_array($relatedTableSchema->primaryKey) ? $relatedTableSchema->primaryKey[$j] : $relatedTableSchema->primaryKey;
$relatedMap[$pk]=$fk;
}
}
}
if($ownerMap===array() && $relatedMap===array())
throw new CDbException(Yii::t('yii','The relation "{relation}" in active record class "{class}" is specified with an incomplete foreign key. The foreign key must consist of columns referencing both joining tables.',
array('{class}'=>get_class($owner),'{relation}'=>$name)));
$insertAttributes=array();
$deleteAttributes=array();
foreach($related as $model)
{
$newFlag=$model->getIsNewRecord();
if($data===null)
$newFlag ? $model->insert() : $model->update();
else
$this->save(false,$data,$model);
$joinTableAttributes=array();
foreach($ownerMap as $pk=>$fk)
$joinTableAttributes[$fk]=$owner->$pk;
foreach($relatedMap as $pk=>$fk)
$joinTableAttributes[$fk]=$model->$pk;
if(!$newFlag)
$deleteAttributes[]=$joinTableAttributes;
$insertAttributes[]=$joinTableAttributes;
}
if($deleteAttributes!==array())
{
$condition=$builder->createInCondition($joinTable,array_merge(array_values($ownerMap),array_values($relatedMap)),$deleteAttributes);
$criteria=$builder->createCriteria($condition);
$builder->createDeleteCommand($joinTable,$criteria)->execute();
}
foreach($insertAttributes as $attributes)
$builder->createInsertCommand($joinTable,$attributes)->execute();
break;
}
}
if(isset($transaction))
$transaction->commit();
return true;
}
catch(Exception $e)
{
if(isset($transaction))
$transaction->rollback();
throw $e;
}
}
/**
* @param string $name
* @param mixed $keys
*/
public function link($name,$keys)
{
$owner=$this->getOwner();
if(!$owner->getMetaData()->hasRelation($name))
throw new CDbException(Yii::t('yiiext','The relation "{relation}" in active record class "{class}" is not specified.',
array('{class}'=>get_class($owner),'{relation}'=>$name)));
$ownerTableSchema=$owner->getTableSchema();
$builder=$owner->getCommandBuilder();
$schema=$builder->getSchema();
$relation=$owner->getMetaData()->relations[$name];
$relationClass=get_class($relation);
$relatedClass=$relation->className;
switch($relationClass)
{
case CActiveRecord::BELONGS_TO:
break;
case CActiveRecord::HAS_ONE:
break;
case CActiveRecord::HAS_MANY:
break;
case CActiveRecord::MANY_MANY:
break;
}
}
/**
* @param string $name
* @param mixed $keys
*/
public function unlink($name,$keys=null)
{
$owner=$this->getOwner();
if(!$owner->getMetaData()->hasRelation($name))
throw new CDbException(Yii::t('yiiext','The relation "{relation}" in active record class "{class}" is not specified.',
array('{class}'=>get_class($owner),'{relation}'=>$name)));
$ownerTableSchema=$owner->getTableSchema();
$builder=$owner->getCommandBuilder();
$schema=$builder->getSchema();
$relation=$owner->getMetaData()->relations[$name];
$relationClass=get_class($relation);
$relatedClass=$relation->className;
switch($relationClass)
{
case CActiveRecord::BELONGS_TO:
break;
case CActiveRecord::HAS_ONE:
break;
case CActiveRecord::HAS_MANY:
break;
case CActiveRecord::MANY_MANY:
break;
}
}
}