Completed
Push — AddActivityLog ( 5659a6 )
by D.
07:17
created

User::arrayRecursiveDiff()   B

Complexity

Conditions 8
Paths 7

Size

Total Lines 20
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

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