-
Notifications
You must be signed in to change notification settings - Fork 1
/
SoftDelete.php
87 lines (71 loc) · 2.14 KB
/
SoftDelete.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
<?php
namespace vyants\softdelete;
use yii\base\Behavior;
use yii\base\Event;
use yii\db\ActiveRecord;
/**
* Class SoftDelete
*
* @package vendor\vyants\softdelete
* @author Vladimir Yants <[email protected]>
* @property ActiveRecord $owner
*/
class SoftDelete extends Behavior
{
/**
* @var string delete time attribute
*/
public $timeAttribute = false;
/**
* @var string status attribute
*/
public $statusAttribute = "status";
/**
* @var string deleted status attribute
*/
public $deletedValue = -1;
/**
* @var string active status attribute
*/
public $activeValue = 1;
/**
* Удалить софтделитом. Возращает true/false в зависимости от того, успешно ли
* @return bool
*/
public function softDelete() {
if($this->timeAttribute) {
$attributes[0] = $this->timeAttribute;
$this->owner->{$attributes[0]} = time();
}
$attributes[1] = $this->statusAttribute;
$this->owner->{$attributes[1]} = $this->deletedValue;
// save record
return $this->owner->save(false, $attributes);
}
/**
* Restore soft-deleted record. Возращает true/false в зависимости от того, успешно ли
* @return bool
*/
public function restore() {
if($this->timeAttribute) {
$attributes[0] = $this->timeAttribute;
$this->owner->$attributes[0] = null;
}
$attributes[1] = $this->statusAttribute;
$this->owner->$attributes[1] = $this->activeValue;
// save record
return $this->owner->save(false, $attributes);
}
/**
* Force delete from database. Возращает true/false в зависимости от того, успешно ли
* @return bool
*/
public function forceDelete() {
// store model so that we can detach the behavior and delete as normal
$model = $this->owner;
$this->detach();
$result = $model->delete();
$this->attach($model);
return $result;
}
}