Completed
Push — master ( 11f933...d32779 )
by Freek
01:17
created

DetectsChanges::attributesToBeLogged()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 20
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 11
nc 6
nop 0
dl 0
loc 20
rs 8.8571
c 0
b 0
f 0
1
<?php
2
3
namespace Spatie\Activitylog\Traits;
4
5
use Illuminate\Database\Eloquent\Model;
6
use Spatie\Activitylog\Exceptions\CouldNotLogChanges;
7
8
trait DetectsChanges
9
{
10
    protected $oldAttributes = [];
11
12
    protected static function bootDetectsChanges()
13
    {
14
        if (static::eventsToBeRecorded()->contains('updated')) {
15
            static::updating(function (Model $model) {
16
17
                //temporary hold the original attributes on the model
18
                //as we'll need these in the updating event
19
                $oldValues = $model->replicate()->setRawAttributes($model->getOriginal());
20
21
                $model->oldAttributes = static::logChanges($oldValues);
22
            });
23
        }
24
    }
25
26
    public function attributesToBeLogged(): array
27
    {
28
        $attributes = [];
29
30
        if (isset(static::$logFillable) && static::$logFillable) {
31
            $attributes = array_merge($attributes, $this->fillable);
0 ignored issues
show
Bug introduced by
The property fillable 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...
32
        }
33
34
        if (isset(static::$logAttributes) && is_array(static::$logAttributes)) {
35
            if (in_array('*', static::$logAttributes)) {
36
                $withoutWildcard = array_diff(static::$logAttributes, ['*']);
37
38
                $attributes = array_merge($attributes, array_keys($this->attributes), $withoutWildcard);
0 ignored issues
show
Bug introduced by
The property attributes does not seem to exist. Did you mean oldAttributes?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
39
            } else {
40
                $attributes = array_merge($attributes, static::$logAttributes);
41
            }
42
        }
43
44
        return $attributes;
45
    }
46
47
    public function shouldlogOnlyDirty(): bool
48
    {
49
        if (! isset(static::$logOnlyDirty)) {
50
            return false;
51
        }
52
53
        return static::$logOnlyDirty;
54
    }
55
56
    public function attributeValuesToBeLogged(string $processingEvent): array
57
    {
58
        if (! count($this->attributesToBeLogged())) {
59
            return [];
60
        }
61
62
        $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...
63
            $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...
64
                ? $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...
65
                : $this
66
        );
67
68
        if (static::eventsToBeRecorded()->contains('updated') && $processingEvent == 'updated') {
69
            $nullProperties = array_fill_keys(array_keys($properties['attributes']), null);
70
71
            $properties['old'] = array_merge($nullProperties, $this->oldAttributes);
72
        }
73
74
        if ($this->shouldlogOnlyDirty() && isset($properties['old'])) {
75
            $properties['attributes'] = array_udiff_assoc(
76
                $properties['attributes'],
77
                $properties['old'],
78
                function ($new, $old) {
79
                    return $new <=> $old;
80
                }
81
            );
82
            $properties['old'] = collect($properties['old'])
83
                ->only(array_keys($properties['attributes']))
84
                ->all();
85
        }
86
87
        return $properties;
88
    }
89
90
    public static function logChanges(Model $model): array
91
    {
92
        $changes = [];
93
        foreach ($model->attributesToBeLogged() as $attribute) {
94
            if (str_contains($attribute, '.')) {
95
                $changes += self::getRelatedModelAttributeValue($model, $attribute);
96
            } else {
97
                $changes += collect($model)->only($attribute)->toArray();
98
            }
99
        }
100
101
        return $changes;
102
    }
103
104
    protected static function getRelatedModelAttributeValue(Model $model, string $attribute): array
105
    {
106
        if (substr_count($attribute, '.') > 1) {
107
            throw CouldNotLogChanges::invalidAttribute($attribute);
108
        }
109
110
        list($relatedModelName, $relatedAttribute) = explode('.', $attribute);
111
112
        $relatedModel = $model->$relatedModelName ?? $model->$relatedModelName();
113
114
        return ["{$relatedModelName}.{$relatedAttribute}" => $relatedModel->$relatedAttribute ?? null];
115
    }
116
}
117