Completed
Push — master ( 35a93c...fb9520 )
by Tom
14:09 queued 12:42
created

DetectsChanges   A

Complexity

Total Complexity 30

Size/Duplication

Total Lines 138
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 97.06%

Importance

Changes 0
Metric Value
dl 0
loc 138
ccs 66
cts 68
cp 0.9706
rs 10
c 0
b 0
f 0
wmc 30
lcom 1
cbo 4

7 Methods

Rating   Name   Duplication   Size   Complexity  
A bootDetectsChanges() 0 13 2
B attributesToBeLogged() 0 26 9
A shouldLogOnlyDirty() 0 8 2
A shouldLogUnguarded() 0 16 4
B attributeValuesToBeLogged() 0 33 7
A logChanges() 0 19 4
A getRelatedModelAttributeValue() 0 12 2
1
<?php
2
3
namespace Spatie\Activitylog\Traits;
4
5
use Illuminate\Support\Str;
6
use Illuminate\Database\Eloquent\Model;
7
use Spatie\Activitylog\Exceptions\CouldNotLogChanges;
8
9
trait DetectsChanges
10
{
11
    protected $oldAttributes = [];
12
13 172
    protected static function bootDetectsChanges()
14
    {
15 172
        if (static::eventsToBeRecorded()->contains('updated')) {
16
            static::updating(function (Model $model) {
17
18
                //temporary hold the original attributes on the model
19
                //as we'll need these in the updating event
20 76
                $oldValues = $model->replicate()->setRawAttributes($model->getOriginal());
21
22 76
                $model->oldAttributes = static::logChanges($oldValues);
23 172
            });
24
        }
25 172
    }
26
27 164
    public function attributesToBeLogged(): array
28
    {
29 164
        $attributes = [];
30
31 164
        if (isset(static::$logFillable) && static::$logFillable) {
32 8
            $attributes = array_merge($attributes, $this->getFillable());
0 ignored issues
show
Bug introduced by
It seems like getFillable() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
33
        }
34
35 164
        if ($this->shouldLogUnguarded()) {
36 4
            $attributes = array_merge($attributes, array_diff(array_keys($this->getAttributes()), $this->getGuarded()));
0 ignored issues
show
Bug introduced by
It seems like getAttributes() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
Bug introduced by
It seems like getGuarded() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
37
        }
38
39 164
        if (isset(static::$logAttributes) && is_array(static::$logAttributes)) {
40 96
            $attributes = array_merge($attributes, array_diff(static::$logAttributes, ['*']));
41
42 96
            if (in_array('*', static::$logAttributes)) {
43 24
                $attributes = array_merge($attributes, array_keys($this->getAttributes()));
0 ignored issues
show
Bug introduced by
It seems like getAttributes() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
44
            }
45
        }
46
47 164
        if (isset(static::$logAttributesToIgnore) && is_array(static::$logAttributesToIgnore)) {
48 8
            $attributes = array_diff($attributes, static::$logAttributesToIgnore);
49
        }
50
51 164
        return $attributes;
52
    }
53
54 100
    public function shouldLogOnlyDirty(): bool
55
    {
56 100
        if (! isset(static::$logOnlyDirty)) {
57 76
            return false;
58
        }
59
60 24
        return static::$logOnlyDirty;
61
    }
62
63 164
    public function shouldLogUnguarded(): bool
64
    {
65 164
        if (! isset(static::$logUnguarded)) {
66 156
            return false;
67
        }
68
69 8
        if (! static::$logUnguarded) {
70
            return false;
71
        }
72
73 8
        if (in_array('*', $this->getGuarded())) {
0 ignored issues
show
Bug introduced by
It seems like getGuarded() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
74 4
            return false;
75
        }
76
77 4
        return true;
78
    }
79
80 164
    public function attributeValuesToBeLogged(string $processingEvent): array
81
    {
82 164
        if (! count($this->attributesToBeLogged())) {
83 64
            return [];
84
        }
85
86 100
        $properties['attributes'] = static::logChanges(
0 ignored issues
show
Coding Style Comprehensibility introduced by
$properties was never initialized. Although not strictly required by PHP, it is generally a good practice to add $properties = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
87 100
            $this->exists
0 ignored issues
show
Bug introduced by
The property exists 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...
88 100
                ? $this->fresh() ?? $this
0 ignored issues
show
Bug introduced by
It seems like fresh() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
89 100
                : $this
90
        );
91
92 100
        if (static::eventsToBeRecorded()->contains('updated') && $processingEvent == 'updated') {
93 52
            $nullProperties = array_fill_keys(array_keys($properties['attributes']), null);
94
95 52
            $properties['old'] = array_merge($nullProperties, $this->oldAttributes);
96
        }
97
98 100
        if ($this->shouldLogOnlyDirty() && isset($properties['old'])) {
99 24
            $properties['attributes'] = array_udiff_assoc(
100 24
                $properties['attributes'],
101 24
                $properties['old'],
102
                function ($new, $old) {
103 24
                    return $new <=> $old;
104 24
                }
105
            );
106 24
            $properties['old'] = collect($properties['old'])
107 24
                ->only(array_keys($properties['attributes']))
108 24
                ->all();
109
        }
110
111 100
        return $properties;
112
    }
113
114 124
    public static function logChanges(Model $model): array
115
    {
116 124
        $changes = [];
117 124
        $attributes = $model->attributesToBeLogged();
118
119 124
        foreach ($attributes as $attribute) {
120 100
            if (Str::contains($attribute, '.')) {
121 20
                $changes += self::getRelatedModelAttributeValue($model, $attribute);
122 100
            } elseif (in_array($attribute, $model->getDates())) {
123 24
                $changes[$attribute] = $model->serializeDate(
0 ignored issues
show
Bug introduced by
The method serializeDate() cannot be called from this context as it is declared protected in class Illuminate\Database\Eloq...\Concerns\HasAttributes.

This check looks for access to methods that are not accessible from the current context.

If you need to make a method accessible to another context you can raise its visibility level in the defining class.

Loading history...
124 24
                    $model->asDateTime($model->getAttribute($attribute))
0 ignored issues
show
Bug introduced by
The method asDateTime() cannot be called from this context as it is declared protected in class Illuminate\Database\Eloq...\Concerns\HasAttributes.

This check looks for access to methods that are not accessible from the current context.

If you need to make a method accessible to another context you can raise its visibility level in the defining class.

Loading history...
125
                );
126
            } else {
127 100
                $changes[$attribute] = $model->getAttribute($attribute);
128
            }
129
        }
130
131 124
        return $changes;
132
    }
133
134 20
    protected static function getRelatedModelAttributeValue(Model $model, string $attribute): array
135
    {
136 20
        if (substr_count($attribute, '.') > 1) {
137
            throw CouldNotLogChanges::invalidAttribute($attribute);
138
        }
139
140 20
        [$relatedModelName, $relatedAttribute] = explode('.', $attribute);
0 ignored issues
show
Bug introduced by
The variable $relatedModelName does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $relatedAttribute does not exist. Did you mean $attribute?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
141
142 20
        $relatedModel = $model->$relatedModelName ?? $model->$relatedModelName();
143
144 20
        return ["{$relatedModelName}.{$relatedAttribute}" => $relatedModel->$relatedAttribute ?? null];
0 ignored issues
show
Bug introduced by
The variable $relatedAttribute does not exist. Did you mean $attribute?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
145
    }
146
}
147