-
Notifications
You must be signed in to change notification settings - Fork 100
/
Copy pathVersionableTrait.php
293 lines (251 loc) · 7.57 KB
/
VersionableTrait.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
<?php
namespace Mpociot\Versionable;
use Illuminate\Support\Facades\Auth;
use Illuminate\Database\Eloquent\Relations\MorphMany;
/**
* Class VersionableTrait
* @package Mpociot\Versionable
*/
trait VersionableTrait
{
/**
* Retrieve, if exists, the property that define that Version model.
* If no property defined, use the default Version model.
*
* Trait cannot share properties whth their class !
* http://php.net/manual/en/language.oop5.traits.php
* @return unknown|string
*/
protected function getVersionClass()
{
if( property_exists( self::class, 'versionClass') ) {
return $this->versionClass;
}
return config('versionable.version_model', Version::class);
}
/**
* Private variable to detect if this is an update
* or an insert.
* @var bool
*/
private $updating;
/**
* Contains all dirty data that is valid for versioning.
*
* @var array
*/
private $versionableDirtyData;
/**
* Optional reason, why this version was created.
* @var string
*/
private $reason;
/**
* Flag that determines if the model allows versioning at all.
* @var bool
*/
protected $versioningEnabled = true;
/**
* @return $this
*/
public function enableVersioning()
{
$this->versioningEnabled = true;
return $this;
}
/**
* @return $this
*/
public function disableVersioning()
{
$this->versioningEnabled = false;
return $this;
}
/**
* Attribute mutator for "reason".
* Prevent "reason" to become a database attribute of model.
*
* @param string $value
*/
public function setReasonAttribute($value)
{
$this->reason = $value;
}
/**
* Initialize model events.
*/
public static function bootVersionableTrait()
{
static::saving(function ($model) {
$model->versionablePreSave();
});
static::saved(function ($model) {
$model->versionablePostSave();
});
}
/**
* Return all versions of the model.
* @return MorphMany
*/
public function versions()
{
return $this->morphMany( $this->getVersionClass(), 'versionable');
}
/**
* Returns the latest version available.
* @return Version
*/
public function currentVersion()
{
return $this->getLatestVersions()->first();
}
/**
* Returns the previous version.
* @return Version
*/
public function previousVersion()
{
return $this->getLatestVersions()->limit(1)->offset(1)->first();
}
/**
* Get a model based on the version id.
*
* @param $version_id
*
* @return $this|null
*/
public function getVersionModel($version_id)
{
$version = $this->versions()->where("version_id", "=", $version_id)->first();
if (!is_null($version)) {
return $version->getModel();
}
return null;
}
/**
* Pre save hook to determine if versioning is enabled and if we're updating
* the model.
* @return void
*/
protected function versionablePreSave()
{
if ($this->versioningEnabled === true) {
$this->versionableDirtyData = $this->getDirty();
$this->updating = $this->exists;
}
}
/**
* Save a new version.
* @return void
*/
protected function versionablePostSave()
{
/**
* We'll save new versions on updating and first creation.
*/
if (
( $this->versioningEnabled === true && $this->updating && $this->isValidForVersioning() ) ||
( $this->versioningEnabled === true && !$this->updating && !is_null($this->versionableDirtyData) && count($this->versionableDirtyData))
) {
// Save a new version
$class = $this->getVersionClass();
$version = new $class();
$version->versionable_id = $this->getKey();
$version->versionable_type = method_exists($this, 'getMorphClass') ? $this->getMorphClass() : get_class($this);
$version->user_id = $this->getAuthUserId();
$versionedHiddenFields = $this->versionedHiddenFields ?? [];
$this->makeVisible($versionedHiddenFields);
$version->model_data = serialize($this->attributesToArray());
$this->makeHidden($versionedHiddenFields);
if (!empty( $this->reason )) {
$version->reason = $this->reason;
}
$version->save();
$this->purgeOldVersions();
}
}
/**
* Initialize a version on every instance of a model.
* @return void
*/
public static function initializeVersions()
{
foreach (self::all() as $obj) {
$obj->createInitialVersion();
}
}
/**
* Save a new version.
* @return void
*/
public function createInitialVersion()
{
if( true === $this->fresh()->versions->isEmpty() &&
true === $this->versioningEnabled
) {
$class = $this->getVersionClass();
$version = new $class();
$version->versionable_id = $this->getKey();
$version->versionable_type = method_exists($this, 'getMorphClass') ? $this->getMorphClass() : get_class($this);
$version->user_id = $this->getAuthUserId();
$versionedHiddenFields = $this->versionedHiddenFields ?? [];
$this->makeVisible($versionedHiddenFields);
$version->model_data = serialize($this->attributesToArray());
$this->makeHidden($versionedHiddenFields);
if (!empty( $this->reason )) {
$version->reason = $this->reason;
}
$version->save();
}
}
/**
* Delete old versions of this model when they reach a specific count.
*
* @return void
*/
private function purgeOldVersions()
{
$keep = isset($this->keepOldVersions) ? $this->keepOldVersions : 0;
if ((int)$keep > 0) {
$count = $this->versions()->count();
if ($count > $keep) {
$this->getLatestVersions()
->take($count)
->skip($keep)
->get()
->each(function ($version) {
$version->delete();
});
}
}
}
/**
* Determine if a new version should be created for this model.
* Checks if appropriate fields have been changed.
*
* @return bool
*/
private function isValidForVersioning()
{
$dontVersionFields = isset( $this->dontVersionFields ) ? $this->dontVersionFields : [];
$removeableKeys = array_merge($dontVersionFields, [$this->getUpdatedAtColumn()]);
if (method_exists($this, 'getDeletedAtColumn')) {
$removeableKeys[] = $this->getDeletedAtColumn();
}
return ( count(array_diff_key($this->versionableDirtyData, array_flip($removeableKeys))) > 0 );
}
/**
* @return int|null
*/
protected function getAuthUserId()
{
return Auth::check() ? Auth::id() : null;
}
/**
* @return \Illuminate\Database\Eloquent\Builder
*/
protected function getLatestVersions()
{
return $this->versions()->orderByDesc('version_id');
}
}