Completed
Push — develop ( 9481b1...1c9b89 )
by Abdelrahman
02:54
created

Guardian::getRouteKey()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Cortex\Auth\Models;
6
7
use Vinkla\Hashids\Facades\Hashids;
8
use Illuminate\Auth\Authenticatable;
9
use Illuminate\Support\Facades\Hash;
10
use Rinvex\Auth\Traits\HasHashables;
11
use Cortex\Foundation\Traits\Auditable;
12
use Illuminate\Database\Eloquent\Model;
13
use Rinvex\Cacheable\CacheableEloquent;
14
use Rinvex\Support\Traits\ValidatingTrait;
15
use Spatie\Activitylog\Traits\LogsActivity;
16
use Illuminate\Foundation\Auth\Access\Authorizable;
17
use Illuminate\Database\Eloquent\Relations\MorphMany;
18
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
19
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
20
21
class Guardian extends Model implements AuthenticatableContract, AuthorizableContract
22
{
23
    // @TODO: Strangely, this issue happens only here!!!
0 ignored issues
show
Coding Style Best Practice introduced by
Comments for TODO tasks are often forgotten in the code; it might be better to use a dedicated issue tracker.
Loading history...
24
    // Duplicate trait usage to fire attached events for cache
25
    // flush before other events in other traits specially LogsActivity,
26
    // otherwise old cached queries used and no changelog recorded on update.
27
    use CacheableEloquent;
28
    use Auditable;
29
    use LogsActivity;
30
    use Authorizable;
31
    use HasHashables;
32
    use Authenticatable;
33
    use ValidatingTrait;
34
35
    /**
36
     * {@inheritdoc}
37
     */
38
    protected $fillable = [
39
        'username',
40
        'password',
41
        'email',
42
        'is_active',
43
    ];
44
45
    /**
46
     * {@inheritdoc}
47
     */
48
    protected $casts = [
49
        'username' => 'string',
50
        'password' => 'string',
51
        'email' => 'string',
52
        'is_active' => 'boolean',
53
        'deleted_at' => 'datetime',
54
    ];
55
56
    /**
57
     * {@inheritdoc}
58
     */
59
    protected $hidden = [
60
        'password',
61
        'remember_token',
62
    ];
63
64
    /**
65
     * {@inheritdoc}
66
     */
67
    protected $observables = [
68
        'validating',
69
        'validated',
70
    ];
71
72
    /**
73
     * The attributes to be encrypted before saving.
74
     *
75
     * @var array
76
     */
77
    protected $hashables = [
78
        'password',
79
    ];
80
81
    /**
82
     * The default rules that the model will validate against.
83
     *
84
     * @var array
85
     */
86
    protected $rules = [];
87
88
    /**
89
     * Whether the model should throw a
90
     * ValidationException if it fails validation.
91
     *
92
     * @var bool
93
     */
94
    protected $throwValidationExceptions = true;
95
96
    /**
97
     * Indicates whether to log only dirty attributes or all.
98
     *
99
     * @var bool
100
     */
101
    protected static $logOnlyDirty = true;
102
103
    /**
104
     * The attributes that are logged on change.
105
     *
106
     * @var array
107
     */
108
    protected static $logFillable = true;
109
110
    /**
111
     * The attributes that are ignored on change.
112
     *
113
     * @var array
114
     */
115
    protected static $ignoreChangedAttributes = [
116
        'password',
117
        'created_at',
118
        'updated_at',
119
        'deleted_at',
120
    ];
121
122
    /**
123
     * Create a new Eloquent model instance.
124
     *
125
     * @param array $attributes
126
     */
127
    public function __construct(array $attributes = [])
128
    {
129
        parent::__construct($attributes);
130
131
        $this->setTable(config('cortex.auth.tables.guardians'));
132
        $this->setRules([
133
            'username' => 'required|alpha_dash|min:3|max:150|unique:'.config('cortex.auth.tables.guardians').',username',
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 121 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
134
            'password' => 'sometimes|required|min:'.config('cortex.auth.password_min_chars'),
135
            'email' => 'required|email|min:3|max:150|unique:'.config('cortex.auth.tables.guardians').',email',
136
            'is_active' => 'sometimes|boolean',
137
            'tags' => 'nullable|array',
138
        ]);
139
    }
140
141
    /**
142
     * Get the value of the model's route key.
143
     *
144
     * @return mixed
145
     */
146
    public function getRouteKey()
147
    {
148
        return Hashids::encode($this->getAttribute($this->getRouteKeyName()));
149
    }
150
151
    /**
152
     * Retrieve the model for a bound value.
153
     *
154
     * @param  mixed  $value
155
     * @return \Illuminate\Database\Eloquent\Model|null
156
     */
157
    public function resolveRouteBinding($value)
158
    {
159
        $value = Hashids::decode($value)[0];
160
161
        return $this->where($this->getRouteKeyName(), $value)->first();
162
    }
163
164
    /**
165
     * {@inheritdoc}
166
     */
167
    protected static function boot()
168
    {
169
        parent::boot();
170
171
        static::saving(function (self $user) {
172
            foreach (array_intersect($user->getHashables(), array_keys($user->getAttributes())) as $hashable) {
173
                if ($user->isDirty($hashable) && Hash::needsRehash($user->$hashable)) {
174
                    $user->$hashable = Hash::make($user->$hashable);
175
                }
176
            }
177
        });
178
    }
179
180
    /**
181
     * The user may have many sessions.
182
     *
183
     * @return \Illuminate\Database\Eloquent\Relations\MorphMany
184
     */
185
    public function sessions(): MorphMany
186
    {
187
        return $this->morphMany(config('cortex.auth.models.session'), 'user');
188
    }
189
190
    /**
191
     * Activate the user.
192
     *
193
     * @return $this
194
     */
195
    public function activate()
196
    {
197
        $this->update(['is_active' => true]);
198
199
        return $this;
200
    }
201
202
    /**
203
     * Deactivate the user.
204
     *
205
     * @return $this
206
     */
207
    public function deactivate()
208
    {
209
        $this->update(['is_active' => false]);
210
211
        return $this;
212
    }
213
}
214