TransactionBehavior.php
2.14 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
<?php
namespace common\modules\language\behaviors;
use yii\base\Behavior;
use yii\db\ActiveRecord;
use yii\db\Transaction;
/**
* Class Save Image Behavior
* @property ActiveRecord $owner
* @package common\behaviors
*/
class TransactionBehavior extends Behavior
{
/**
* @var Transaction $_transaction
*/
private $_transaction;
/**
* @var bool $_transaction_status
*/
private $_transaction_status = false;
/**
* @var ActiveRecord[] $model_langs
*/
public $model_langs = [];
public function events()
{
return [
ActiveRecord::EVENT_BEFORE_INSERT => 'beforeSave',
ActiveRecord::EVENT_BEFORE_UPDATE => 'beforeSave',
ActiveRecord::EVENT_AFTER_INSERT => 'afterSave',
ActiveRecord::EVENT_AFTER_UPDATE => 'afterSave',
];
}
public function beforeSave($event) {
/**
* @var ActiveRecord $owner
*/
$owner = $this->owner;
$db = $owner::getDb();
$this->_transaction = $db->beginTransaction();
}
public function afterSave($event) {
/**
* @var ActiveRecord $owner
*/
$owner = $this->owner;
if(!empty($this->model_langs) && $owner->getBehavior('language')) {
if($owner->linkLangs($this->model_langs) && $owner->saveLangs($this->model_langs)) {
$this->_transaction->commit();
$this->_transaction_status = true;
} else {
$this->_transaction->rollBack();
$this->_transaction_status = false;
}
} else {
$this->_transaction->commit();
$this->_transaction_status = true;
}
}
/**
* @return bool
*/
public function getTransactionStatus():bool {
return $this->_transaction_status;
}
}