|
1
|
|
|
<?php |
|
2
|
|
|
/************************************************************************** |
|
3
|
|
|
* Copyright (C) iFeras93, Inc - All Rights Reserved |
|
4
|
|
|
* |
|
5
|
|
|
* |
|
6
|
|
|
* @file BeHistroiable.php |
|
7
|
|
|
* @author Firas |
|
8
|
|
|
* @project HistoriableModel |
|
9
|
|
|
* @date 2/16/2020 |
|
10
|
|
|
*/ |
|
11
|
|
|
|
|
12
|
|
|
namespace Iferas93\HistoriableModel\Traits\History; |
|
13
|
|
|
|
|
14
|
|
|
use Illuminate\Database\Eloquent\Model; |
|
15
|
|
|
use Illuminate\Support\Arr; |
|
16
|
|
|
|
|
17
|
|
|
trait Histroiable |
|
18
|
|
|
{ |
|
19
|
|
|
public static function bootHistroiable() |
|
20
|
|
|
{ |
|
21
|
|
|
static::updated(function (Model $model) { |
|
22
|
|
|
$columns = $model->getChangedColumns($model); |
|
23
|
|
|
collect($columns)->each(function ($column) use ($model) { |
|
24
|
|
|
$model->saveChanges($column); |
|
25
|
|
|
}); |
|
26
|
|
|
}); |
|
27
|
|
|
} |
|
28
|
|
|
|
|
29
|
|
|
private function getChangedColumns(Model $model) |
|
|
|
|
|
|
30
|
|
|
{ |
|
31
|
|
|
$original = $model->getOriginal(); |
|
32
|
|
|
|
|
33
|
|
|
return collect(Arr::except($model->getChanges(), $this->ignoredColumns()))->map(function ($change, $column) use ($original) { |
|
34
|
|
|
return new ColumnChanges($column, Arr::get($original, $column), $change); |
|
35
|
|
|
}); |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
protected function ignoredColumns() |
|
39
|
|
|
{ |
|
40
|
|
|
return [ |
|
41
|
|
|
'updated_at', |
|
42
|
|
|
]; |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
private function saveChanges(ColumnChanges $column) |
|
|
|
|
|
|
46
|
|
|
{ |
|
47
|
|
|
$this->history()->create([ |
|
48
|
|
|
'changed_column' => $column->column, |
|
49
|
|
|
'value_from' => $column->from, |
|
50
|
|
|
'value_to' => $column->to, |
|
51
|
|
|
]); |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
|
|
public function history() |
|
55
|
|
|
{ |
|
56
|
|
|
return $this->morphMany(config('historiable.model'), 'Historiable'); |
|
|
|
|
|
|
57
|
|
|
} |
|
58
|
|
|
} |
|
59
|
|
|
|