Completed
Pull Request — master (#20)
by ARCANEDEV
10:00
created

User::scopeLastActive()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

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