Completed
Push — master ( 818bfa...99dc5b )
by Freek
02:41
created

ActivityLogger::by()   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\Auth\AuthManager;
6
use Illuminate\Contracts\Config\Repository;
7
use Illuminate\Database\Eloquent\Model;
8
use Spatie\Activitylog\Exceptions\CouldNotLogActivity;
9
use Spatie\Activitylog\Exceptions\InvalidConfiguration;
10
use Spatie\Activitylog\Models\Activity;
11
12
class ActivityLogger
13
{
14
    /** @var \Illuminate\Auth\AuthManager */
15
    protected $auth;
16
17
    protected $logName = '';
18
19
    /** @var \Illuminate\Database\Eloquent\Model */
20
    protected $performedOn;
21
22
    /** @var \Illuminate\Database\Eloquent\Model */
23
    protected $causedBy;
24
25
    /** @var \Illuminate\Support\Collection */
26
    protected $properties;
27
28
    public function __construct(AuthManager $auth, Repository $config)
29
    {
30
        $this->auth = $auth;
31
32
        $this->properties = collect();
33
34
        $authDriver = $config['laravel-activitylog']['default_auth_driver'] ?? $auth->getDefaultDriver();
35
36
        $this->causedBy = $auth->guard($authDriver)->user();
37
38
        $this->logName = $config['laravel-activitylog']['default_log_name'];
39
    }
40
41
    public function performedOn(Model $model)
42
    {
43
        $this->performedOn = $model;
44
45
        return $this;
46
    }
47
48
    public function on(Model $model)
49
    {
50
        return $this->performedOn($model);
51
    }
52
53
    /**
54
     * @param \Illuminate\Database\Eloquent\Model|int|string $modelOrId
55
     *
56
     * @return $this
57
     */
58
    public function causedBy($modelOrId)
59
    {
60
        $model = $this->normalizeCauser($modelOrId);
61
62
        $this->causedBy = $model;
63
64
        return $this;
65
    }
66
67
    public function by($modelOrId)
68
    {
69
        return $this->causedBy($modelOrId);
70
    }
71
72
    /**
73
     * @param array|\Illuminate\Support\Collection $properties
74
     *
75
     * @return $this
76
     */
77
    public function withProperties($properties)
78
    {
79
        $this->properties = collect($properties);
80
81
        return $this;
82
    }
83
84
    /**
85
     * @param string $key
86
     * @param mixed  $value
87
     *
88
     * @return $this
89
     */
90
    public function withProperty(string $key, $value)
91
    {
92
        $this->properties->put($key, $value);
93
94
        return $this;
95
    }
96
97
    public function useLog(string $logName)
98
    {
99
        $this->logName = $logName;
100
101
        return $this;
102
    }
103
104
    public function inLog(string $logName)
105
    {
106
        return $this->useLog($logName);
107
    }
108
109
    public function log(string $description)
110
    {
111
        $activityModelClassName = $this->determineActivityModel();
112
113
        $activity = new $activityModelClassName();
114
115
        if ($this->performedOn) {
116
            $activity->subject()->associate($this->performedOn);
117
        }
118
119
        if ($this->causedBy) {
120
            $activity->causer()->associate($this->causedBy);
121
        }
122
123
        $activity->properties = $this->properties;
124
125
        $activity->description = $this->replacePlaceholders($description, $activity);
126
127
        $activity->log_name = $this->logName;
128
129
        $activity->save();
130
131
        return $this;
132
    }
133
134
    /**
135
     * @param \Illuminate\Database\Eloquent\Model|int|string $modelOrId
136
     *
137
     * @return \Illuminate\Database\Eloquent\Model
138
     *
139
     * @throws \Spatie\Activitylog\Exceptions\CouldNotLogActivity
140
     */
141
    protected function normalizeCauser($modelOrId): Model
142
    {
143
        if ($modelOrId instanceof Model) {
144
            return $modelOrId;
145
        }
146
147
        if ($model = $this->auth->getProvider()->retrieveById($modelOrId)) {
0 ignored issues
show
Bug introduced by
The method getProvider() does not exist on Illuminate\Auth\AuthManager. Did you maybe mean provider()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
148
            return $model;
149
        }
150
151
        throw CouldNotLogActivity::couldNotDetermineUser($modelOrId);
152
    }
153
154
    protected function replacePlaceholders(string $description, Activity $activity): string
155
    {
156
        return preg_replace_callback('/:[a-z0-9._-]+/i', function ($match) use ($activity) {
157
158
            $match = $match[0];
159
160
            $attribute = (string) string($match)->between(':', '.');
161
162
            if (!in_array($attribute, ['subject', 'causer', 'properties'])) {
163
                return $match;
164
            }
165
166
            $propertyName = substr($match, strpos($match, '.') + 1);
167
168
            $attributeValue = $activity->$attribute;
169
170
            $attributeValue = $attributeValue->toArray();
171
172
            return array_get($attributeValue, $propertyName, $match);
173
        }, $description);
174
    }
175
176
    /**
177
     * @return \Illuminate\Database\Eloquent\Model
178
     *
179
     * @throws \Spatie\Activitylog\Exceptions\InvalidConfiguration
180
     */
181
    public function determineActivityModel()
182
    {
183
        $activityModel = config('laravel-activitylog.activity_model') ?? Activity::class;
184
185
        if (!is_a($activityModel, Activity::class, true)) {
186
            throw InvalidConfiguration::modelIsNotValid($activityModel);
187
        }
188
189
        return $activityModel;
190
    }
191
}
192