Completed
Push — master ( ba36ea...c404ca )
by Freek
02:08
created

DetectsChanges::bootDetectsChanges()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 5
nc 1
nop 0
dl 0
loc 13
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace Spatie\Activitylog\Traits;
4
5
use Illuminate\Database\Eloquent\Model;
6
use Illuminate\Support\Collection;
7
8
trait DetectsChanges
9
{
10
    protected $oldValues = [];
11
12
    protected $newValues = [];
13
14
    protected static function bootDetectsChanges()
15
    {
16
        collect(['updating', 'deleting'])->each(function ($eventName) {
17
18
            return static::$eventName(function (Model $model) {
19
20
                $model->oldValues = $model->fresh()->toArray();
21
22
                $model->newValues = $model->getDirty();
23
24
            });
25
        });
26
    }
27
28
    public function getChangedAttributeNames(): array
29
    {
30
        return array_keys(array_intersect_key($this->oldValues, $this->newValues));
31
    }
32
33
    public function getChangedValues(): Collection
34
    {
35
36
        if (!isset($this->logChangesOnAttributes)) {
37
            return collect();
38
        }
39
40
        return collect($this->getChangedAttributeNames())
41
            ->filter(function (string $attributeName) {
42
               return collect($this->logChangesOnAttributes)->contains($attributeName);
0 ignored issues
show
Bug introduced by
The property logChangesOnAttributes does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
43
            })
44
            ->map(function (string $changedAttributeName) {
45
                return [
46
                    'old' => $this->oldValues[$changedAttributeName],
47
                    'new' => $this->newValues[$changedAttributeName],
48
                ];
49
            });
50
    }
51
}
52