Completed
Push — master ( 94f95e...a17ed3 )
by Freek
02:08
created

DetectsChanges::bootRemembersOldValues()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 5
nc 1
nop 0
dl 0
loc 11
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace Spatie\Activitylog\Traits;
4
5
use Illuminate\Support\Collection;
6
7
trait DetectsChanges
8
{
9
    protected $oldValues = [];
10
11
    protected $newValues = [];
12
13
    protected static function bootRemembersOldValues()
14
    {
15
        collect(['updated', 'deleted'])->each(function ($eventName) {
16
17
            return static::$eventName(function (Model $model) {
18
                $model->oldValues = $model->fresh()->toArray();
19
20
                $model->newValues = $model->getDirty();
21
            });
22
        });
23
    }
24
25
    public function getChangedAttributeNames(): array
26
    {
27
        return array_keys(array_intersect_key($this->oldValues, $this->newValues));
28
    }
29
30
    public function getChangedValues(): Collection
31
    {
32
        if (!isset(static::$logChangesOnAttributes)) {
33
            return collect();
34
        }
35
36
        return collect($this->getChangedAttributeNames())
37
            ->filter(function (string $attributeName) {
38
               return collect(static::$logChangesOnAttributes)->contains($attributeName);
39
            })
40
            ->map(function (string $changedAttributeName) {
41
                return [
42
                    'old' => $this->oldValues[$changedAttributeName],
43
                    'new' => $this->newValues[$changedAttributeName],
44
                ];
45
            });
46
    }
47
}
48