Completed
Pull Request — master (#23)
by ARCANEDEV
08:07
created

User::setupModel()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.6666
c 0
b 0
f 0
ccs 6
cts 6
cp 1
cc 2
eloc 5
nc 2
nop 0
crap 2
1
<?php namespace Arcanedev\LaravelAuth\Models;
2
3
use Arcanedev\LaravelAuth\Bases\User as Authenticatable;
4
use Arcanedev\LaravelAuth\Exceptions\UserConfirmationException;
5
use Arcanedev\LaravelAuth\Services\SocialAuthenticator;
6
use Arcanedev\LaravelAuth\Services\UserConfirmator;
7
use Arcanedev\LaravelAuth\Models\Traits\Activatable;
8
use Arcanedev\LaravelAuth\Models\Traits\AuthUserTrait;
9
use Arcanedev\Support\Traits\PrefixedModel;
10
use Arcanesoft\Contracts\Auth\Models\User as UserContract;
11
use Carbon\Carbon;
12
use Illuminate\Database\Eloquent\SoftDeletes;
13
use Illuminate\Support\Str;
14
15
/**
16
 * Class     User
17
 *
18
 * @package  Arcanedev\LaravelAuth\Models
19
 * @author   ARCANEDEV <[email protected]>
20
 *
21
 * @property  int                                       id
22
 * @property  string                                    username
23
 * @property  string                                    first_name
24
 * @property  string                                    last_name
25
 * @property  string                                    full_name
26
 * @property  string                                    email
27
 * @property  string                                    password
28
 * @property  string                                    remember_token
29
 * @property  bool                                      is_admin
30
 * @property  bool                                      is_active
31
 * @property  bool                                      is_confirmed       (Optional)
32
 * @property  string                                    confirmation_code  (Optional)
33
 * @property  \Carbon\Carbon                            confirmed_at       (Optional)
34
 * @property  \Carbon\Carbon                            last_activity
35
 * @property  \Carbon\Carbon                            created_at
36
 * @property  \Carbon\Carbon                            updated_at
37
 * @property  \Carbon\Carbon                            deleted_at
38
 *
39
 * @property  \Illuminate\Database\Eloquent\Collection       roles
40
 * @property  \Illuminate\Database\Eloquent\Collection       permissions
41
 * @property  \Arcanedev\LaravelAuth\Models\Pivots\RoleUser  pivot
42
 *
43
 * @method  static  bool                                   insert(array $values)
44
 * @method          \Illuminate\Database\Eloquent\Builder  unconfirmed(string $code)
45
 * @method          \Illuminate\Database\Eloquent\Builder  lastActive(int $minutes = null)
46
 */
47
class User extends Authenticatable implements UserContract
0 ignored issues
show
Bug introduced by
There is at least one abstract method in this class. Maybe declare it as abstract, or implement the remaining methods: can, getAuthIdentifier, getAuthIdentifierName, getAuthPassword, getEmailForPasswordReset, getRememberToken, getRememberTokenName, sendPasswordResetNotification, setAttribute, setRememberToken
Loading history...
48
{
49
    /* ------------------------------------------------------------------------------------------------
50
     |  Traits
51
     | ------------------------------------------------------------------------------------------------
52
     */
53
    use AuthUserTrait,
54
        Activatable,
55
        SoftDeletes;
56
57
    /* ------------------------------------------------------------------------------------------------
58
     |  Properties
59
     | ------------------------------------------------------------------------------------------------
60
     */
61
    /**
62
     * The attributes that are mass assignable.
63
     *
64
     * @var array
65
     */
66
    protected $fillable = [
67
        'username',
68
        'first_name',
69
        'last_name',
70
        'email',
71
        'password',
72
    ];
73
74
    /**
75
     * The attributes excluded from the model's JSON form.
76
     *
77
     * @var array
78
     */
79
    protected $hidden   = [
80
        'password',
81
        'remember_token',
82
        'confirmation_code',
83
    ];
84
85
    /**
86
     * The attributes that should be casted to native types.
87
     *
88
     * @var array
89
     */
90
    protected $casts = [
91
        'is_admin'     => 'boolean',
92
        'is_active'    => 'boolean',
93
        'is_confirmed' => 'boolean',
94
    ];
95
96
    /**
97
     * The attributes that should be mutated to dates.
98
     *
99
     * @var array
100
     */
101
    protected $dates = [
102
        'confirmed_at',
103
        'last_activity',
104
        'deleted_at',
105
    ];
106
107
    /* ------------------------------------------------------------------------------------------------
108
     |  Constructor
109
     | ------------------------------------------------------------------------------------------------
110
     */
111
    /**
112
     * Create a new Eloquent model instance.
113
     *
114
     * @param  array  $attributes
115
     */
116 225
    public function __construct(array $attributes = [])
117
    {
118 225
        parent::__construct($attributes);
119
120 225
        $this->setupModel();
121 225
    }
122
123
    /**
124
     * Setup the model.
125
     */
126 225
    protected function setupModel()
127
    {
128 225
        $this->setTable(config('laravel-auth.users.table', 'users'));
129
130 225
        if (SocialAuthenticator::isEnabled()) {
131 225
            $this->hidden   = array_merge($this->hidden, ['social_provider_id']);
132 225
            $this->fillable = array_merge($this->fillable, ['social_provider', 'social_provider_id']);
133
        }
134 225
    }
135
136
    /* ------------------------------------------------------------------------------------------------
137
     |  Relationships
138
     | ------------------------------------------------------------------------------------------------
139
     */
140
    /**
141
     * User belongs to many roles.
142
     *
143
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
144
     */
145 39
    public function roles()
146
    {
147
        return $this
148 39
            ->belongsToMany(
149 39
                config('laravel-auth.roles.model', Role::class),
150 39
                config('laravel-auth.database.prefix').'role_user',
151 39
                'user_id',
152 39
                'role_id'
153
            )
154 39
            ->using(Pivots\RoleUser::class)
155 39
            ->withTimestamps();
156
    }
157
158
    /* ------------------------------------------------------------------------------------------------
159
     |  Scopes
160
     | ------------------------------------------------------------------------------------------------
161
     */
162
    /**
163
     * Scope unconfirmed users by code.
164
     *
165
     * @param  \Illuminate\Database\Eloquent\Builder  $query
166
     * @param  string                                 $code
167
     *
168
     * @return \Illuminate\Database\Eloquent\Builder
169
     */
170 12
    public function scopeUnconfirmed($query, $code)
171
    {
172 12
        return $query->where('is_confirmed', false)
173 12
                     ->where('confirmation_code', $code)
174 12
                     ->whereNull('confirmed_at');
175
    }
176
177
    /**
178
     * Scope last active users.
179
     *
180
     * @param  \Illuminate\Database\Eloquent\Builder  $query
181
     * @param  int|null                               $minutes
182
     *
183
     * @return \Illuminate\Database\Eloquent\Builder
184
     */
185 3
    public function scopeLastActive($query, $minutes = null)
186
    {
187 3
        $minutes = $minutes ?: config('laravel_auth.track-activity.minutes', 5);
188
189 3
        $date = Carbon::now()->subMinutes($minutes);
190
191 3
        return $query->where('last_activity', '>=', $date->toDateTimeString());
192
    }
193
194
    /* ------------------------------------------------------------------------------------------------
195
     |  Getters & Setters
196
     | ------------------------------------------------------------------------------------------------
197
     */
198
    /**
199
     * Set the `username` attribute.
200
     *
201
     * @param  string  $username
202
     */
203 69
    public function setUsernameAttribute($username)
204
    {
205 69
        $this->attributes['username'] = $this->slugify($username);
206 69
    }
207
208
    /**
209
     * Get the `full_name` attribute.
210
     *
211
     * @return string
212
     */
213 3
    public function getFullNameAttribute()
214
    {
215 3
        return $this->first_name.' '.$this->last_name;
216
    }
217
218
    /**
219
     * Set the `password` attribute.
220
     *
221
     * @param  string  $password
222
     */
223 69
    public function setPasswordAttribute($password)
224
    {
225 69
        $this->attributes['password'] = bcrypt($password);
226 69
    }
227
228
    /* ------------------------------------------------------------------------------------------------
229
     |  CRUD Functions
230
     | ------------------------------------------------------------------------------------------------
231
     */
232
    /**
233
     * Confirm the unconfirmed user account by confirmation code.
234
     *
235
     * @param  string  $code
236
     *
237
     * @return \Arcanesoft\Contracts\Auth\Models\User
238
     *
239
     * @throws \Arcanedev\LaravelAuth\Exceptions\UserConfirmationException
240
     */
241 12
    public function findUnconfirmed($code)
242
    {
243 12
        $unconfirmedUser = self::unconfirmed($code)->first();
244
245 12
        if ( ! $unconfirmedUser instanceof self)
246 3
            throw (new UserConfirmationException)->setModel(self::class);
247
248 9
        return $unconfirmedUser;
249
    }
250
251
    /**
252
     * Confirm the new user account.
253
     *
254
     * @param  \Arcanesoft\Contracts\Auth\Models\User|string  $code
255
     *
256
     * @return \Arcanesoft\Contracts\Auth\Models\User
257
     */
258 6
    public function confirm($code)
259
    {
260 6
        if ($code instanceof self)
261 3
            $code = $code->confirmation_code;
262
263 6
        $user = $this->findUnconfirmed($code);
264
265 6
        return (new UserConfirmator)->confirm($user);
266
    }
267
268
    /**
269
     * Update the user's last activity.
270
     *
271
     * @param  bool  $save
272
     */
273 6
    public function updateLastActivity($save = true)
274
    {
275 6
        $this->forceFill(['last_activity' => Carbon::now()]);
276
277 6
        if ($save) $this->save();
278 6
    }
279
280
    /* ------------------------------------------------------------------------------------------------
281
     |  Check Functions
282
     | ------------------------------------------------------------------------------------------------
283
     */
284
    /**
285
     * Check if user is an administrator.
286
     *
287
     * @return bool
288
     */
289 18
    public function isAdmin()
290
    {
291 18
        return $this->is_admin;
292
    }
293
294
    /**
295
     * Check if user is a moderator.
296
     *
297
     * @return bool
298
     */
299 6
    public function isModerator()
300
    {
301
        // Override this method to give more privileges than members.
302 6
        return false;
303
    }
304
305
    /**
306
     * Check if user is a member.
307
     *
308
     * @return bool
309
     */
310 9
    public function isMember()
311
    {
312 9
        return ! $this->isAdmin();
313
    }
314
315
    /**
316
     * Check if user has a confirmed account.
317
     *
318
     * @return bool
319
     */
320 9
    public function isConfirmed()
321
    {
322 9
        return $this->is_confirmed;
323
    }
324
325
    /**
326
     * Check if user can be impersonated.
327
     *
328
     * @return bool
329
     */
330 3
    public function canBeImpersonated()
331
    {
332 3
        return $this->isMember();
333
    }
334
335
    /* ------------------------------------------------------------------------------------------------
336
     |  Other Functions
337
     | ------------------------------------------------------------------------------------------------
338
     */
339
    /**
340
     * Slugify the value.
341
     *
342
     * @param  string  $value
343
     *
344
     * @return string
345
     */
346 69
    protected function slugify($value)
347
    {
348 69
        return Str::slug($value, config('laravel-auth.users.slug-separator', '.'));
349
    }
350
}
351