Completed
Push — master ( 6374b3...243f6e )
by D.
17:36 queued 12:41
created

User::setAttribute()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 8
Ratio 100 %

Code Coverage

Tests 4
CRAP Score 3

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 8
loc 8
ccs 4
cts 4
cp 1
rs 9.4285
cc 3
eloc 4
nc 2
nop 2
crap 3
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', ];
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', ];
45
46
    /**
47
     * make destroyed_date a Carbon instance.
48
     */
49
    protected $dates = ['destroyed_date'];
50
51 6
    public function supervisor()
52
    {
53 6
        return $this->belongsTo('SET\User', 'supervisor_id');
54
    }
55
56 3
    public function subordinates()
57
    {
58 3
        return $this->hasMany('SET\User', 'supervisor_id');
59
    }
60
61 3
    public function attachments()
62
    {
63 3
        return $this->morphMany('SET\Attachment', 'imageable');
64
    }
65
66 4
    public function notes()
67
    {
68 4
        return $this->hasMany('SET\Note');
69
    }
70
71 4
    public function travels()
72
    {
73 4
        return $this->hasMany('SET\Travel');
74
    }
75
76 51
    public function visits()
77
    {
78 51
        return $this->hasMany('SET\Visit');
79
    }
80
81 5
    public function assignedTrainings()
82
    {
83 5
        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 4
    public function trainings()
95
    {
96 4
        return $this->belongsToMany('SET\Training');
97
    }
98
99
    /**
100
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
101
     */
102 6
    public function groups()
103
    {
104 6
        return $this->belongsToMany('SET\Group')->withPivot('access');
105
    }
106
107
    /**
108
     * @return \Illuminate\Database\Eloquent\Relations\MorphMany
109
     */
110 3
    public function duties()
111
    {
112 3
        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 62
    public function getUserFullNameAttribute()
121
    {
122 62
        if ($this->attributes['id'] == 1) {
123 10
            return 'system';
124
        }
125
126 62
        $firstName = $this->attributes['first_name'];
127
128 62
        if ($this->attributes['nickname']) {
129 60
            $firstName = $this->attributes['first_name'].' ('.$this->attributes['nickname'].')';
130
        }
131
132 62
        if (Setting::get('full_name_format') == 'first_last') {
133 1
            return $firstName.' '.$this->attributes['last_name'];
134
        }
135
136 61
        return $this->attributes['last_name'].', '.$firstName;
137
    }
138
139
    /**
140
     * @param $query
141
     * @param $input
142
     */
143 3
    public function scopeSearchUsers($query, $input)
144
    {
145 3
        return $query->where('first_name', 'LIKE', "%$input%")
146 3
            ->orWhere('last_name', 'LIKE', "%$input%")
147 3
            ->orWhere('emp_num', 'LIKE', "%$input%");
148
    }
149
150
    /**
151
     * @param $query
152
     *
153
     * @return mixed
154
     */
155 67
    public function scopeActive($query)
156
    {
157 67
        return $query->where('status', 'active');
158
    }
159
160 18
    public function scopeSkipSystem($query)
161
    {
162 18
        return $query->where('id', '>', 1);
163
    }
164
165
    /**
166
     * Store empty values as null in the DB.
167
     *
168
     * @param string $key
169
     * @param mixed  $value
170
     *
171
     * @return $this
172
     */
173 149 View Code Duplication
    public function setAttribute($key, $value)
174
    {
175 149
        if (is_scalar($value) && $value === '') {
176 1
            $value = null;
177
        }
178
179 149
        return parent::setAttribute($key, $value);
180
    }
181
182
    /**
183
     * @param $user
184
     * Obtain the Activitylog for the designated user or for all users.
185
     * Populate log array values ["comment", "updated_at", "user_fullname"]
186
     *
187
     * @return Log collection
188
     */
189 18
    public function getUserLog($user = null)
190
    {
191 18
        $ignoreList = ['password', 'last_logon', 'remember_token', 'ip'];
192 18
        $record = $logs = []; // define arrays
193
194 18
      foreach (($user) ? $user->activity : Activity::all() as $entry) {
195 18
          $record['updated_at'] = $entry->updated_at;
196 18
          $record['user_fullname'] = $entry->properties['attributes']['last_name']
197 18
            .', '.$entry->properties['attributes']['first_name'];
198
199 18
          $record['comment'] = '';
200 18
          if ($entry->description == 'updated') { // Report all changes on each update
201 5
          $result = $this->arrayRecursiveDiff($entry->changes->get('attributes'),
202 5
              $entry->changes->get('old'));
203 5
              foreach ($result as $key => $value) {
204 5
                  if (!in_array($key, $ignoreList)) {
205 5
                      $record['comment'] .=
206 5
                ucfirst($key).' '.$entry->description." from '"
207 5
                .$entry->changes->get('old')[$key]."' to '".$value."'.\n";
208
                  }
209
              }
210
          } else { // description == 'created' ||  'deleted'
211 18
            $record['comment'] .= $entry->description." user '".$record['user_fullname']."'.\n";
212
          }
213
214
        // Append only non-ignored record entries to log
215 18
        if ($record['comment']) {
216 18
            array_push($logs, $record);
217
        }
218
      }
219
220 18
        return collect($logs)->sortByDesc('updated_at');  // return latest -> earliest
221
    }
222
223
    /**
224
     * @param Array1 Array2
225
     * As array_diff function only checks one dimension of a n-dimensional array.
226
     * arrayRecursiveDiff will compare n-dimensional.
227
     * Will insure compared objects are arrays.
228
     *
229
     * @return DiffsArray
230
     */
231 5
    private function arrayRecursiveDiff($aArray1, $aArray2)
232
    {
233 5
        $aReturn = [];
234 5
        if (!is_array($aArray1) || !is_array($aArray2)) {
235
            return $aReturn;
236
        }
237 5
        foreach ($aArray1 as $mKey => $mValue) {
238 5
            if (array_key_exists($mKey, $aArray2)) {
239 5
                if (is_array($mValue)) {
240
                    $aRecursiveDiff = $this->arrayRecursiveDiff($mValue, $aArray2[$mKey]);
241
                    if (count($aRecursiveDiff)) {
242
                        $aReturn[$mKey] = $aRecursiveDiff;
243
                    }
244
                } else {
245 5
                    if ($mValue != $aArray2[$mKey]) {
246 5
                        $aReturn[$mKey] = $mValue;
247
                    }
248
                }
249
            } else {
250 5
                $aReturn[$mKey] = $mValue;
251
            }
252
        }
253
254 5
        return $aReturn;
255
    }
256
257 4
    public function getDestroyDate($status)
258
    {
259 4
        if ($status == 'active') {
260 2
            return;
261
        }
262
263 2
        if ($status == 'separated') {
264 1
            return Carbon::today()->addYears(2)->startOfWeek();
265
        }
266
267 1
        return Carbon::today()->addWeek()->startOfWeek();
268
    }
269
}
270