-
Notifications
You must be signed in to change notification settings - Fork 2
/
ReadonlyBehavior.php
executable file
·74 lines (66 loc) · 1.51 KB
/
ReadonlyBehavior.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
<?php
namespace synatree\behavior;
use yii\db\ActiveRecord;
use yii\base\Behavior;
use Yii;
/**
* Read Only Behavior
* @property ActiveRecord $owner
* @author David Baltusavich <david@synatree.com>
*/
class ReadonlyBehavior extends Behavior
{
public $attribute;
public $onError; // callback
private $locked = false;
private $locker = [];
private $stopEvent = true;
public function checkLock($event){
if( $this->owner->__get($this->attribute) )
$this->grabAllAttributes();
else
$this->releaseAllAttributes();
}
private function grabAllAttributes()
{
if(! $this->locked)
{
foreach($this->owner->attributes as $name=>$value)
{
$this->locker[$name] = $value;
}
}
$this->locked = true;
}
private function releaseAllAttributes()
{
$this->locker = [];
$this->locked = false;
}
public function restoreIfLocked($event)
{
if($this->locked)
{
if($this->stopEvent)
$event->handled = true;
foreach($this->owner->attributes as $name=>$value)
{
if( isset($this->locker[$name]) && $this->locker[$name] != $value )
{
$this->owner->$name = $this->locker[$name];
call_user_func( $this->onError, $name, $value);
}
}
}
}
public function events()
{
return [
ActiveRecord::EVENT_AFTER_INSERT => 'checkLock',
ActiveRecord::EVENT_AFTER_UPDATE => 'checkLock',
ActiveRecord::EVENT_AFTER_FIND => 'checkLock',
ActiveRecord::EVENT_BEFORE_INSERT => 'restoreIfLocked',
ActiveRecord::EVENT_BEFORE_UPDATE => 'restoreIfLocked',
];
}
}