-
Notifications
You must be signed in to change notification settings - Fork 0
/
TransactionBehavior.php
100 lines (90 loc) · 2.26 KB
/
TransactionBehavior.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
<?php
/**
* Created by JetBrains PhpStorm.
* User: Ekstazi
* Date: 21.02.13
* Time: 16:40
* To change this template use File | Settings | File Templates.
*/
/**
* This behavior allow to use transaction for model between onBeforeSave and onAfterSave events
*/
class TransactionBehavior extends CActiveRecordBehavior
{
/**
* Whether to autostart transaction on save.
* Note you must do your additional operations after onBeforeSave and before onAfterSave events
* @var bool
*/
public $autoStart=false;
/**
* @var CDbTransaction
*/
protected $_transaction;
/**
* Start the transaction
* @return CDbTransaction
*/
public function beginTransaction()
{
$db = $this->owner->dbConnection;
if($db->currentTransaction||$this->_transaction)
throw new CDbException(Yii::t('transaction','Already in transaction'));
Yii::app()->attachEventHandler('onException',array($this,'rollback'));
return $this->_transaction=$db->beginTransaction();
}
/**
* Rollback transaction
*/
public function rollback()
{
Yii::app()->detachEventHandler('onException',array($this,'rollback'));
if(!$this->_transaction)
throw new CDbException(Yii::t('transaction','Nothing to rollback'));
$this->_transaction->rollback();
$this->_transaction=null;
}
/**
* Commit transaction
*/
public function commit()
{
if(!$this->_transaction)
throw new CDbException(Yii::t('transaction','Nothing to commit'));
$this->_transaction->commit();
$this->_transaction=null;
Yii::app()->detachEventHandler('onException',array($this,'rollback'));
}
public function beforeSave($event)
{
if($this->autoStart)
$this->beginTransaction();
}
public function afterSave($event)
{
if($this->autoStart&&$this->_transaction)
$this->commit();
}
/**
* Save model with transaction handle
* @param bool $runValidation
* @param null $attributes
* @return bool Whether the transaction save was successful
*/
public function saveTransactional($runValidation=true,$attributes=null)
{
$autoStart=$this->autoStart;
$this->autoStart=false;
try {
$this->beginTransaction();
$this->owner->save($runValidation,$attributes);
$this->commit();
}catch (Exception $e)
{
$this->rollback();
return false;
}
$this->autoStart=$autoStart;
return true;
}
}