Completed
Push — master ( acdaf0...7b4292 )
by
unknown
02:14
created

User::scopeUserStatus()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 0
cts 0
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 2
1
<?php
2
3
namespace SET;
4
5
use Carbon\Carbon;
6
use Illuminate\Foundation\Auth\User as Authenticatable;
7
use Illuminate\Notifications\Notifiable;
8
use Spatie\Activitylog\Models\Activity;
9
use Spatie\Activitylog\Traits\LogsActivity;
10
11
/**
12
 * Class User.
13
 */
14
class User extends Authenticatable
15
{
16
    use Notifiable;
17
18
    /**
19
     * @var string
20
     */
21
    protected $table = 'users';
22
    /**
23
     * @var bool
24
     */
25
    public $timestamps = true;
26
    /**
27
     * @var array
28
     */
29
    protected $fillable = ['username', 'emp_num', 'first_name', 'nickname', 'last_name',
30
        'email', 'phone', 'status', 'clearance', 'elig_date', 'inv', 'inv_close', 'destroyed_date',
31
        'supervisor_id', 'access_level', 'password', 'separated_date', 'cont_eval', 'cont_eval_date', ];
32
    /**
33
     * @var array
34
     */
35
    protected $hidden = ['username', 'password', 'remember_token'];
36
37
    /*
38
     * @var array $logAttributes defines will log the changed attributes
39
     */
40
    use LogsActivity;
41
    protected static $logAttributes = ['username', 'emp_num', 'first_name', 'nickname',
42
         'last_name', 'email', 'phone', 'jpas_name', 'status', 'clearance',
43
         'elig_date', 'inv', 'inv_close', 'destroyed_date', 'role', 'supervisor_id', 'access_level',
44
         'last_logon', 'ip', 'cont_eval', 'cont_eval_date', ];
45
46
    /**
47
     * make destroyed_date a Carbon instance.
48
     */
49
    protected $dates = ['destroyed_date'];
50
51
    public function supervisor()
52
    {
53
        return $this->belongsTo('SET\User', 'supervisor_id');
54
    }
55
56
    public function subordinates()
57
    {
58
        return $this->hasMany('SET\User', 'supervisor_id');
59
    }
60
61
    public function attachments()
62
    {
63
        return $this->morphMany('SET\Attachment', 'imageable');
64
    }
65
66
    public function notes()
67
    {
68
        return $this->hasMany('SET\Note');
69
    }
70
71
    public function travels()
72
    {
73
        return $this->hasMany('SET\Travel');
74
    }
75
76
    public function visits()
77
    {
78
        return $this->hasMany('SET\Visit');
79
    }
80
81
    public function assignedTrainings()
82
    {
83
        return $this->hasMany('SET\TrainingUser', 'user_id');
84
    }
85
86
    public function trainingUsers()
87
    {
88
        return $this->hasMany('SET\TrainingUser', 'user_id');
89
    }
90
91
    /**
92
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
93
     */
94
    public function trainings()
95
    {
96
        return $this->belongsToMany('SET\Training');
97
    }
98
99
    /**
100
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
101
     */
102
    public function groups()
103
    {
104
        return $this->belongsToMany('SET\Group')->withPivot('access');
105
    }
106
107
    /**
108
     * @return \Illuminate\Database\Eloquent\Relations\MorphMany
109
     */
110
    public function duties()
111
    {
112
        return $this->belongsToMany('SET\Duty');
113
    }
114
115
    /**
116
     * If we have a nickname, return 'lastname, nickname' otherwise return 'lastname, firstname'.
117
     *
118
     * @return string
119
     */
120
    public function getUserFullNameAttribute()
121
    {
122
        if ($this->attributes['id'] == 1) {
123
            return 'system';
124
        }
125
126
        $firstName = $this->attributes['first_name'];
127
128
        if ($this->attributes['nickname']) {
129
            $firstName = $this->attributes['first_name'].' ('.$this->attributes['nickname'].')';
130
        }
131
132
        if (Setting::get('full_name_format') == 'first_last') {
133
            return $firstName.' '.$this->attributes['last_name'];
134
        }
135
136
        return $this->attributes['last_name'].', '.$firstName;
137
    }
138
139
    /**
140
     * @param $query
141
     * @param $input
142
     */
143
    public function scopeSearchUsers($query, $input)
144
    {
145
        return $query->where('first_name', 'LIKE', "%$input%")
146
            ->orWhere('last_name', 'LIKE', "%$input%")
147
            ->orWhere('emp_num', 'LIKE', "%$input%");
148
    }
149
150
    /**
151
     * @param $query
152
     *
153
     * @return mixed
154
     */
155
    public function scopeActive($query)
156
    {
157
        return $query->where('status', 'active');
158
    }
159
160
    public function scopeSkipSystem($query)
161
    {
162
        return $query->where('id', '>', 1);
163
    }
164
165
    public function scopeUserStatus($query)
166
    {
167
        $query->when( session('userStatus'), function( $user ){ 
168
            return $user->where( 'status', session('userStatus') );
169
         });
170
    }
171
172
    /**
173
     * Store empty values as null in the DB.
174
     *
175
     * @param string $key
176
     * @param mixed  $value
177
     *
178
     * @return $this
179
     */
180 View Code Duplication
    public function setAttribute($key, $value)
181
    {
182
        if (is_scalar($value) && $value === '') {
183
            $value = null;
184
        }
185
186
        return parent::setAttribute($key, $value);
187
    }
188
189
    /**
190
     * @param $user
191
     * Obtain the Activitylog for the designated user or for all users.
192
     * Populate log array values ["comment", "updated_at", "user_fullname"]
193
     *
194
     * @return Log collection
195
     */
196
    public function getUserLog($user = null)
197
    {
198
        $ignoreList = ['password', 'last_logon', 'remember_token', 'ip'];
199
        $record = $logs = []; // define arrays
200
201
        foreach (($user) ? $user->activity : Activity::all() as $entry) {
202
            $record['updated_at'] = $entry->updated_at;
203
            $record['user_fullname'] = $entry->properties['attributes']['last_name']
204
            .', '.$entry->properties['attributes']['first_name'];
205
206
            $record['comment'] = '';
207
            if ($entry->description == 'updated') { // Report all changes on each update
208
                $result = $this->arrayRecursiveDiff($entry->changes->get('attributes'),
209
              $entry->changes->get('old'));
210
                foreach ($result as $key => $value) {
211
                    if (!in_array($key, $ignoreList)) {
212
                        $record['comment'] .=
213
                ucfirst($key).' '.$entry->description." from '"
214
                .$entry->changes->get('old')[$key]."' to '".$value."'.\n";
215
                    }
216
                }
217
            } else { // description == 'created' ||  'deleted'
218
                $record['comment'] .= $entry->description." user '".$record['user_fullname']."'.\n";
219
            }
220
221
            // Append only non-ignored record entries to log
222
            if ($record['comment']) {
223
                array_push($logs, $record);
224
            }
225
        }
226
227
        return collect($logs)->sortByDesc('updated_at');  // return latest -> earliest
228
    }
229
230
    /**
231
     * @param Array1 Array2
232
     * As array_diff function only checks one dimension of a n-dimensional array.
233
     * arrayRecursiveDiff will compare n-dimensional.
234
     * Will insure compared objects are arrays.
235
     *
236
     * @return DiffsArray
237
     */
238
    private function arrayRecursiveDiff($aArray1, $aArray2)
239
    {
240
        $aReturn = [];
241
        if (!is_array($aArray1) || !is_array($aArray2)) {
242
            return $aReturn;
243
        }
244
        foreach ($aArray1 as $mKey => $mValue) {
245
            if (array_key_exists($mKey, $aArray2)) {
246
                if (is_array($mValue)) {
247
                    $aRecursiveDiff = $this->arrayRecursiveDiff($mValue, $aArray2[$mKey]);
248
                    if (count($aRecursiveDiff)) {
249
                        $aReturn[$mKey] = $aRecursiveDiff;
250
                    }
251
                } else {
252
                    if ($mValue != $aArray2[$mKey]) {
253
                        $aReturn[$mKey] = $mValue;
254
                    }
255
                }
256
            } else {
257
                $aReturn[$mKey] = $mValue;
258
            }
259
        }
260
261
        return $aReturn;
262
    }
263
264
    public function getDestroyDate($status)
265
    {
266
        if ($status == 'active') {
267
            return;
268
        }
269
270
        if ($status == 'separated') {
271
            return Carbon::today()->addYears(2)->startOfWeek();
272
        }
273
274
        return Carbon::today()->addWeek()->startOfWeek();
275
    }
276
}
277