Completed
Push — master ( 685eb3...3e4363 )
by Freek
02:33
created

DetectsChanges::getPropertiesToBeLogged()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 7
nc 3
nop 0
dl 0
loc 14
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace Spatie\Activitylog\Traits;
4
5
use Illuminate\Database\Eloquent\Model;
6
7
trait DetectsChanges
8
{
9
    protected $oldAttributes = [];
10
11
    protected static function bootDetectsChanges()
12
    {
13
        if (static::eventsToBeRecorded()->contains('updated')) {
14
            static::updating(function (Model $model) {
15
16
                $oldValues = $model->replicate()->setRawAttributes($model->getOriginal());
17
18
                $model->oldAttributes = static::logChanges($oldValues);
19
            });
20
        }
21
    }
22
23
    public function attributesToBeLogged(): array
24
    {
25
        if (!isset(static::$logAttributes)) {
26
            return [];
27
        }
28
29
        return static::$logAttributes;
30
    }
31
32
    public function getPropertiesToBeLogged(): array
33
    {
34
        if (!count($this->attributesToBeLogged())) {
35
            return [];
36
        }
37
38
        $properties['values'] = static::logChanges($this);
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...
39
40
        if (static::eventsToBeRecorded()->contains('updated')) {
41
            $properties['old'] = $this->oldAttributes;
42
        }
43
44
        return $properties;
45
    }
46
47
    public static function logChanges(Model $model): array
48
    {
49
        return collect($model)->only($model->attributesToBeLogged())->toArray();
50
    }
51
}
52