Completed
Push — master ( 03b0c4...8dfddb )
by Freek
09:53 queued 07:24
created

ActivityLogger::inLog()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Spatie\Activitylog;
4
5
use Illuminate\Config\Repository;
6
use Illuminate\Contracts\Auth\Guard;
7
use Illuminate\Database\Eloquent\Model;
8
use Spatie\Activitylog\Exceptions\CouldNotLogActivity;
9
use Spatie\Activitylog\Models\Activity;
10
11
class ActivityLogger
12
{
13
    /** @var \Illuminate\Contracts\Auth\Guard */
14
    protected $auth;
15
16
    protected $logName = '';
17
18
    /** @var \Illuminate\Database\Eloquent\Model */
19
    protected $performedOn;
20
21
    /** @var \Illuminate\Database\Eloquent\Model */
22
    protected $causedBy;
23
24
    /** @var \Illuminate\Support\Collection */
25
    protected $properties;
26
27
    public function __construct(Guard $auth, Repository $config)
28
    {
29
        $this->auth = $auth;
30
31
        $this->properties = collect();
32
33
        $this->causedBy = $auth->user();
0 ignored issues
show
Documentation Bug introduced by
It seems like $auth->user() can also be of type object<Illuminate\Contracts\Auth\Authenticatable>. However, the property $causedBy is declared as type object<Illuminate\Database\Eloquent\Model>. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
34
35
        $this->logName = $config['laravel-activitylog']['default_log_name'];
36
    }
37
38
    public function performedOn(Model $model)
39
    {
40
        $this->performedOn = $model;
41
42
        return $this;
43
    }
44
45
    public function on(Model $model)
46
    {
47
        return $this->performedOn($model);
48
    }
49
50
    /**
51
     * @param \Illuminate\Database\Eloquent\Model|int|string $modelOrId
52
     *
53
     * @return $this
54
     */
55
    public function causedBy($modelOrId)
56
    {
57
        $model = $this->normalizeCauser($modelOrId);
58
59
        $this->causedBy = $model;
60
61
        return $this;
62
    }
63
64
    public function by($modelOrId)
65
    {
66
        return $this->causedBy($modelOrId);
67
    }
68
69
    /**
70
     * @param array|\Illuminate\Support\Collection $properties
71
     *
72
     * @return $this
73
     */
74
    public function withProperties($properties)
75
    {
76
        $this->properties = collect($properties);
77
78
        return $this;
79
    }
80
81
    /**
82
     * @param string $key
83
     * @param mixed  $value
84
     *
85
     * @return $this
86
     */
87
    public function withProperty(string $key, $value)
88
    {
89
        $this->properties->put($key, $value);
90
91
        return $this;
92
    }
93
94
    public function useLog(string $logName)
95
    {
96
        $this->logName = $logName;
97
98
        return $this;
99
    }
100
101
    public function inLog(string $logName)
102
    {
103
        return $this->useLog($logName);
104
    }
105
106
    public function log(string $description)
107
    {
108
        $activity = new Activity();
109
110
        if ($this->performedOn) {
111
            $activity->subject()->associate($this->performedOn);
112
        }
113
114
        if ($this->causedBy) {
115
            $activity->causer()->associate($this->causedBy);
116
        }
117
118
        $activity->properties = $this->properties;
119
120
        $activity->description = $this->replacePlaceholders($description, $activity);
121
122
        $activity->log_name = $this->logName;
123
124
        $activity->save();
125
    }
126
127
    /**
128
     * @param \Illuminate\Database\Eloquent\Model|int|string $modelOrId
129
     *
130
     * @return \Illuminate\Database\Eloquent\Model
131
     *
132
     * @throws \Spatie\Activitylog\Exceptions\CouldNotLogActivity
133
     */
134
    protected function normalizeCauser($modelOrId): Model
135
    {
136
        if ($modelOrId instanceof Model) {
137
            return $modelOrId;
138
        }
139
140
        if ($model = $this->auth->getProvider()->retrieveById($modelOrId)) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Illuminate\Contracts\Auth\Guard as the method getProvider() does only exist in the following implementations of said interface: Illuminate\Auth\SessionGuard.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
141
            return $model;
142
        }
143
144
        throw CouldNotLogActivity::couldNotDetermineUser($modelOrId);
145
    }
146
147
    protected function replacePlaceholders(string $description, Activity $activity): string
148
    {
149
        return preg_replace_callback('/:[a-z0-9._-]+/i', function ($match) use ($activity) {
150
151
            $match = $match[0];
152
153
            $attribute = (string) string($match)->between(':', '.');
154
155
            if (!in_array($attribute, ['subject', 'causer', 'properties'])) {
156
                return $match;
157
            }
158
159
            $propertyName = substr($match, strpos($match, '.') + 1);
160
161
            $attributeValue = $activity->$attribute;
162
163
            if ($attributeValue instanceof Model) {
164
                $attributeValue = $attributeValue->toArray();
165
            }
166
167
            return array_get($attributeValue, $propertyName, $match);
168
        }, $description);
169
    }
170
}
171