Completed
Pull Request — AddActivityLog (#69)
by D.
18:54 queued 08:51
created

User::arrayRecursiveDiff()   C

Complexity

Conditions 8
Paths 7

Size

Total Lines 25
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

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