Completed
Push — master ( f280a8...a63f6c )
by Tom
09:06 queued 05:45
created

DetectsChanges::attributesToBeLogged()   B

Complexity

Conditions 9
Paths 24

Size

Total Lines 26

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 9

Importance

Changes 0
Metric Value
cc 9
nc 24
nop 0
dl 0
loc 26
ccs 13
cts 13
cp 1
crap 9
rs 8.0555
c 0
b 0
f 0
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 192
    protected static function bootDetectsChanges()
14
    {
15 192
        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 92
                $oldValues = (new static)->setRawAttributes($model->getOriginal());
0 ignored issues
show
Bug introduced by
It seems like setRawAttributes() 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...
21
22 92
                $model->oldAttributes = static::logChanges($oldValues);
23 192
            });
24
        }
25 192
    }
26
27 184
    public function attributesToBeLogged(): array
28
    {
29 184
        $attributes = [];
30
31 184
        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 184
        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 184
        if (isset(static::$logAttributes) && is_array(static::$logAttributes)) {
40 112
            $attributes = array_merge($attributes, array_diff(static::$logAttributes, ['*']));
41
42 112
            if (in_array('*', static::$logAttributes)) {
43 32
                $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 184
        if (isset(static::$logAttributesToIgnore) && is_array(static::$logAttributesToIgnore)) {
48 8
            $attributes = array_diff($attributes, static::$logAttributesToIgnore);
49
        }
50
51 184
        return $attributes;
52
    }
53
54 116
    public function shouldLogOnlyDirty(): bool
55
    {
56 116
        if (! isset(static::$logOnlyDirty)) {
57 80
            return false;
58
        }
59
60 36
        return static::$logOnlyDirty;
61
    }
62
63 184
    public function shouldLogUnguarded(): bool
64
    {
65 184
        if (! isset(static::$logUnguarded)) {
66 176
            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 184
    public function attributeValuesToBeLogged(string $processingEvent): array
81
    {
82 184
        if (! count($this->attributesToBeLogged())) {
83 68
            return [];
84
        }
85
86 116
        $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 116
            $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 116
                ? $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 116
                : $this
90
        );
91
92 116
        if (static::eventsToBeRecorded()->contains('updated') && $processingEvent == 'updated') {
93 68
            $nullProperties = array_fill_keys(array_keys($properties['attributes']), null);
94
95 68
            $properties['old'] = array_merge($nullProperties, $this->oldAttributes);
96
97 68
            $this->oldAttributes = [];
98
        }
99
100 116
        if ($this->shouldLogOnlyDirty() && isset($properties['old'])) {
101 36
            $properties['attributes'] = array_udiff_assoc(
102 36
                $properties['attributes'],
103 36
                $properties['old'],
104
                function ($new, $old) {
105 36
                    if ($old === null || $new === null) {
106 20
                        return $new === $old ? 0 : 1;
107
                    }
108
109 32
                    return $new <=> $old;
110 36
                }
111
            );
112 36
            $properties['old'] = collect($properties['old'])
113 36
                ->only(array_keys($properties['attributes']))
114 36
                ->all();
115
        }
116
117 116
        return $properties;
118
    }
119
120 140
    public static function logChanges(Model $model): array
121
    {
122 140
        $changes = [];
123 140
        $attributes = $model->attributesToBeLogged();
124
125 140
        foreach ($attributes as $attribute) {
126 116
            if (Str::contains($attribute, '.')) {
127 24
                $changes += self::getRelatedModelAttributeValue($model, $attribute);
128
            } else {
129 116
                $changes[$attribute] = $model->getAttribute($attribute);
130
131
                if (
132 116
                    in_array($attribute, $model->getDates())
133 116
                    && ! is_null($changes[$attribute])
134
                ) {
135 32
                    $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...
136 32
                        $model->asDateTime($changes[$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...
137
                    );
138
                }
139
            }
140
        }
141
142 140
        return $changes;
143
    }
144
145 24
    protected static function getRelatedModelAttributeValue(Model $model, string $attribute): array
146
    {
147 24
        if (substr_count($attribute, '.') > 1) {
148
            throw CouldNotLogChanges::invalidAttribute($attribute);
149
        }
150
151 24
        [$relatedModelName, $relatedAttribute] = explode('.', $attribute);
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...
Bug introduced by
The variable $relatedModelName seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
152
153 24
        $relatedModelName = Str::camel($relatedModelName);
0 ignored issues
show
Bug introduced by
The variable $relatedModelName seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
154
155 24
        $relatedModel = $model->$relatedModelName ?? $model->$relatedModelName();
156
157 24
        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...
158
    }
159
}
160