Completed
Pull Request — master (#675)
by
unknown
05:20
created

DetectsChanges::getModelAttributeTranslation()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
cc 4
nc 2
nop 2
dl 0
loc 12
ccs 0
cts 0
cp 0
crap 20
rs 9.8666
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\Arr;
7
use Illuminate\Support\Str;
8
use Spatie\Activitylog\Exceptions\CouldNotLogChanges;
9
use Astrotomic\Translatable\Translatable;
10
11
trait DetectsChanges
12
{
13
    protected $oldAttributes = [];
14 216
15
    protected static function bootDetectsChanges()
16 216
    {
17
        if (static::eventsToBeRecorded()->contains('updated')) {
18
            static::updating(function (Model $model) {
19
20
                //temporary hold the original attributes on the model
21 112
                //as we'll need these in the updating event
22
                $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...
23 112
24 216
                $model->oldAttributes = static::logChanges($oldValues);
25
            });
26 216
        }
27
    }
28 208
29
    public function attributesToBeLogged(): array
30 208
    {
31
        $attributes = [];
32 208
33 8
        if (isset(static::$logFillable) && static::$logFillable) {
34
            $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...
35
        }
36 208
37 4
        if ($this->shouldLogUnguarded()) {
38
            $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...
39
        }
40 208
41 136
        if (isset(static::$logAttributes) && is_array(static::$logAttributes)) {
42
            $attributes = array_merge($attributes, array_diff(static::$logAttributes, ['*']));
43 136
44 32
            if (in_array('*', static::$logAttributes)) {
45
                $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...
46
            }
47
        }
48 208
49 8
        if (isset(static::$logAttributesToIgnore) && is_array(static::$logAttributesToIgnore)) {
50
            $attributes = array_diff($attributes, static::$logAttributesToIgnore);
51
        }
52 208
53
        return $attributes;
54
    }
55 140
56
    public function shouldLogOnlyDirty(): bool
57 140
    {
58 80
        if (! isset(static::$logOnlyDirty)) {
59
            return false;
60
        }
61 60
62
        return static::$logOnlyDirty;
63
    }
64 208
65
    public function shouldLogUnguarded(): bool
66 208
    {
67 200
        if (! isset(static::$logUnguarded)) {
68
            return false;
69
        }
70 8
71
        if (! static::$logUnguarded) {
72
            return false;
73
        }
74 8
75 4
        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...
76
            return false;
77
        }
78 4
79
        return true;
80
    }
81 208
82
    public function attributeValuesToBeLogged(string $processingEvent): array
83 208
    {
84 68
        if (! count($this->attributesToBeLogged())) {
85
            return [];
86
        }
87 140
88 140
        $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...
89 140
            $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...
90 140
                ? $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...
91
                : $this
92
        );
93 140
94 88
        if (static::eventsToBeRecorded()->contains('updated') && $processingEvent == 'updated') {
95
            $nullProperties = array_fill_keys(array_keys($properties['attributes']), null);
96 88
97
            $properties['attributes'] = static::logChanges(
98 88
                $this->exists
99
                    ? $this
100
                    : $this
101 140
            );
102 56
103 56
            $properties['old'] = array_merge($nullProperties, $this->oldAttributes);
104 56
105
            $this->oldAttributes = [];
106 56
        }
107 20
108
        if ($this->shouldLogOnlyDirty() && isset($properties['old'])) {
109
            $properties['attributes'] = array_udiff_assoc(
110 52
                $properties['attributes'],
111 56
                $properties['old'],
112
                function ($new, $old) {
113 56
                    if ($old === null || $new === null) {
114 56
                        return $new === $old ? 0 : 1;
115 56
                    }
116
117
                    return $new <=> $old;
118 140
                }
119
            );
120
            $properties['old'] = collect($properties['old'])
121 164
                ->only(array_keys($properties['attributes']))
122
                ->all();
123 164
        }
124 164
125
        return $properties;
126 164
    }
127 140
128 24
    public static function logChanges(Model $model): array
129 140
    {
130 24
        $changes = [];
131 24
        $attributes = $model->attributesToBeLogged();
132 24
133 24
        foreach ($attributes as $attribute) {
134
            if (Str::contains($attribute, '.')) {
135
                $changes += self::getRelatedModelAttributeValue($model, $attribute);
136 140
            } elseif (Str::contains($attribute, '->')) {
137
                Arr::set(
138
                    $changes,
139 140
                    str_replace('->', '.', $attribute),
140 140
                    static::getModelAttributeJsonValue($model, $attribute)
141
                );
142 32
            } elseif (collect(class_uses_recursive(static::class))->contains(Translatable::class) && $model->isTranslationAttribute($attribute)) {
143 32
                $changes += self::getModelAttributeTranslation($model, $attribute);
144
            } else {
145
                $changes[$attribute] = $model->getAttribute($attribute);
146
147
                if (
148
                    in_array($attribute, $model->getDates())
149 164
                    && ! is_null($changes[$attribute])
150
                ) {
151
                    $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...
152 24
                        $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...
153
                    );
154 24
                }
155
            }
156
        }
157
158 24
        return $changes;
159
    }
160 24
161
    protected static function getRelatedModelAttributeValue(Model $model, string $attribute): array
162 24
    {
163
        if (substr_count($attribute, '.') > 1) {
164 24
            throw CouldNotLogChanges::invalidAttribute($attribute);
165
        }
166
167 24
        [$relatedModelName, $relatedAttribute] = explode('.', $attribute);
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...
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...
168
169 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...
170 24
171 24
        $relatedModel = $model->$relatedModelName ?? $model->$relatedModelName();
172
173 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...
174
    }
175
176
    protected static function getModelAttributeJsonValue(Model $model, string $attribute)
177
    {
178
        $path = explode('->', $attribute);
179
        $modelAttribute = array_shift($path);
180
        $modelAttribute = collect($model->getAttribute($modelAttribute));
181
182
        return data_get($modelAttribute, implode('.', $path));
183
    }
184
185
    protected static function getModelAttributeTranslation(Model $model, string $attribute)
186
    {
187
        $attributes = [];
188
189
        if ($model->translations && count($model->translations->toArray())) {
190
            foreach ($model->translations as $translation) {
191
                $attributes[$attribute.':'.$translation->locale] = $translation->getAttribute($attribute);
192
            }
193
        }
194
195
        return $attributes;
196
    }
197
}
198