Completed
Push — master ( 1f5a13...370bf5 )
by Freek
02:09
created

ActivityLogger::getActivityModel()   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 0
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\ModelMismatchException;
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
    /** @var \Spatie\Activitylog\Models\Activity */
29
    protected $activityModel;
30
31
    public function __construct(AuthManager $auth, Repository $config)
32
    {
33
        $this->auth = $auth;
34
35
        $this->properties = collect();
36
37
        $model = config('laravel-activitylog.activity_model');
38
39
        if($model == null) {
40
            throw new ModelMismatchException("Model not set in laravel-activitylog.php");
41
        }
42
43
        if(  (!($model instanceof Activity) && !($model == Activity::class)) && (!(is_subclass_of($model, Activity::class))) ) {
44
            throw new ModelMismatchException("Model `{$model}` is not extending \\Spatie\\Activitylog\\Models\\Activity");
45
        }
46
47
        $this->activityModel = config('laravel-activitylog.activity_model') ?? Activity::class;
48
49
        $authDriver = $config['laravel-activitylog']['default_auth_driver'] ?? $auth->getDefaultDriver();
50
51
        $this->causedBy = $auth->guard($authDriver)->user();
52
53
        $this->logName = $config['laravel-activitylog']['default_log_name'];
54
    }
55
56
    public function performedOn(Model $model)
57
    {
58
        $this->performedOn = $model;
59
60
        return $this;
61
    }
62
63
    public function on(Model $model)
64
    {
65
        return $this->performedOn($model);
66
    }
67
68
    /**
69
     * @param \Illuminate\Database\Eloquent\Model|int|string $modelOrId
70
     *
71
     * @return $this
72
     */
73
    public function causedBy($modelOrId)
74
    {
75
        $model = $this->normalizeCauser($modelOrId);
76
77
        $this->causedBy = $model;
78
79
        return $this;
80
    }
81
82
    public function by($modelOrId)
83
    {
84
        return $this->causedBy($modelOrId);
85
    }
86
87
    /**
88
     * @param array|\Illuminate\Support\Collection $properties
89
     *
90
     * @return $this
91
     */
92
    public function withProperties($properties)
93
    {
94
        $this->properties = collect($properties);
95
96
        return $this;
97
    }
98
99
    /**
100
     * @param string $key
101
     * @param mixed  $value
102
     *
103
     * @return $this
104
     */
105
    public function withProperty(string $key, $value)
106
    {
107
        $this->properties->put($key, $value);
108
109
        return $this;
110
    }
111
112
    public function useLog(string $logName)
113
    {
114
        $this->logName = $logName;
115
116
        return $this;
117
    }
118
119
120
    public function inLog(string $logName)
121
    {
122
        return $this->useLog($logName);
123
    }
124
125
    public function log(string $description)
126
    {
127
        $activity = new $this->activityModel;
128
129
        if ($this->performedOn) {
130
            $activity->subject()->associate($this->performedOn);
131
        }
132
133
        if ($this->causedBy) {
134
            $activity->causer()->associate($this->causedBy);
135
        }
136
137
        $activity->properties = $this->properties;
138
139
        $activity->description = $this->replacePlaceholders($description, $activity);
140
141
        $activity->log_name = $this->logName;
142
143
        $activity->save();
144
        return $this;
145
    }
146
147
    /**
148
     * @param \Illuminate\Database\Eloquent\Model|int|string $modelOrId
149
     *
150
     * @return \Illuminate\Database\Eloquent\Model
151
     *
152
     * @throws \Spatie\Activitylog\Exceptions\CouldNotLogActivity
153
     */
154
    protected function normalizeCauser($modelOrId): Model
155
    {
156
        if ($modelOrId instanceof Model) {
157
            return $modelOrId;
158
        }
159
160
        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...
161
            return $model;
162
        }
163
164
        throw CouldNotLogActivity::couldNotDetermineUser($modelOrId);
165
    }
166
167
    protected function replacePlaceholders(string $description, Activity $activity): string
168
    {
169
        return preg_replace_callback('/:[a-z0-9._-]+/i', function ($match) use ($activity) {
170
171
            $match = $match[0];
172
173
            $attribute = (string) string($match)->between(':', '.');
174
175
            if (!in_array($attribute, ['subject', 'causer', 'properties'])) {
176
                return $match;
177
            }
178
179
            $propertyName = substr($match, strpos($match, '.') + 1);
180
181
            $attributeValue = $activity->$attribute;
182
183
            $attributeValue = $attributeValue->toArray();
184
185
            return array_get($attributeValue, $propertyName, $match);
186
        }, $description);
187
    }
188
189
    public function getActivityModel() : string
190
    {
191
        return $this->activityModel;
192
    }
193
}
194