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

DetectsChanges   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 2

Importance

Changes 0
Metric Value
dl 0
loc 44
rs 10
c 0
b 0
f 0
wmc 4
lcom 2
cbo 2

3 Methods

Rating   Name   Duplication   Size   Complexity  
A bootDetectsChanges() 0 13 1
A getChangedAttributeNames() 0 4 1
A getChangedValues() 0 18 2
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