Completed
Push — master ( 83a66b...f280a8 )
by Tom
07:27 queued 02:27
created

DetectsChanges::getRelatedModelAttributeValue()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2.0185

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 2
dl 0
loc 12
ccs 5
cts 6
cp 0.8333
crap 2.0185
rs 9.8666
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 188
    protected static function bootDetectsChanges()
14
    {
15 188
        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 88
                $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 88
                $model->oldAttributes = static::logChanges($oldValues);
23 188
            });
24
        }
25 188
    }
26
27 180
    public function attributesToBeLogged(): array
28
    {
29 180
        $attributes = [];
30
31 180
        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 180
        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 180
        if (isset(static::$logAttributes) && is_array(static::$logAttributes)) {
40 108
            $attributes = array_merge($attributes, array_diff(static::$logAttributes, ['*']));
41
42 108
            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 180
        if (isset(static::$logAttributesToIgnore) && is_array(static::$logAttributesToIgnore)) {
48 8
            $attributes = array_diff($attributes, static::$logAttributesToIgnore);
49
        }
50
51 180
        return $attributes;
52
    }
53
54 112
    public function shouldLogOnlyDirty(): bool
55
    {
56 112
        if (! isset(static::$logOnlyDirty)) {
57 76
            return false;
58
        }
59
60 36
        return static::$logOnlyDirty;
61
    }
62
63 180
    public function shouldLogUnguarded(): bool
64
    {
65 180
        if (! isset(static::$logUnguarded)) {
66 172
            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 180
    public function attributeValuesToBeLogged(string $processingEvent): array
81
    {
82 180
        if (! count($this->attributesToBeLogged())) {
83 68
            return [];
84
        }
85
86 112
        $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 112
            $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 112
                ? $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 112
                : $this
90
        );
91
92 112
        if (static::eventsToBeRecorded()->contains('updated') && $processingEvent == 'updated') {
93 64
            $nullProperties = array_fill_keys(array_keys($properties['attributes']), null);
94
95 64
            $properties['old'] = array_merge($nullProperties, $this->oldAttributes);
96
97 64
            $this->oldAttributes = [];
98
        }
99
100 112
        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 112
        return $properties;
118
    }
119
120 136
    public static function logChanges(Model $model): array
121
    {
122 136
        $changes = [];
123 136
        $attributes = $model->attributesToBeLogged();
124
125 136
        foreach ($attributes as $attribute) {
126 112
            if (Str::contains($attribute, '.')) {
127 20
                $changes += self::getRelatedModelAttributeValue($model, $attribute);
128
            } else {
129 112
                $changes[$attribute] = $model->getAttribute($attribute);
130
131
                if (
132 112
                    in_array($attribute, $model->getDates())
133 112
                    && ! 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 136
        return $changes;
143
    }
144
145 20
    protected static function getRelatedModelAttributeValue(Model $model, string $attribute): array
146
    {
147 20
        if (substr_count($attribute, '.') > 1) {
148
            throw CouldNotLogChanges::invalidAttribute($attribute);
149
        }
150
151 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...
152
153 20
        $relatedModel = $model->$relatedModelName ?? $model->$relatedModelName();
154
155 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...
156
    }
157
}
158