Completed
Push — AddActivityLog ( afa80e...195157 )
by D.
45:05 queued 35:04
created

User::getUserLog()   C

Complexity

Conditions 7
Paths 5

Size

Total Lines 33
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 33
rs 6.7272
c 0
b 0
f 0
cc 7
eloc 21
nc 5
nop 1
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 51 and the first side effect is on line 14.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
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
0 ignored issues
show
Bug introduced by
Possible parse error: class missing opening or closing brace
Loading history...
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
    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
    /**
166
     * Store empty values as null in the DB.
167
     *
168
     * @param string $key
169
     * @param mixed  $value
170
     *
171
     * @return $this
172
     */
173
    public function setAttribute($key, $value)
174
    {
175
        if (is_scalar($value) && $value === '') {
176
            $value = null;
177
        }
178
179
        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
    public function getUserLog($user = null)
190
    {
191
        $ignoreList = ['password', 'last_logon', 'remember_token', 'ip'];
192
        $record = $logs = []; // define arrays
193
194
      foreach (($user) ? $user->activity : Activity::all() as $entry) {
195
          $record['updated_at'] = $entry->updated_at;
196
          $record['user_fullname'] = $entry->properties['attributes']['last_name']
197
            .', '.$entry->properties['attributes']['first_name'];
198
199
          $record['comment'] = '';
200
          if ($entry->description == 'updated') { // Report all changes on each update
201
          $result = $this->arrayRecursiveDiff($entry->changes->get('attributes'),
202
              $entry->changes->get('old'));
203
              foreach ($result as $key => $value) {
204
                  if (!in_array($key, $ignoreList)) {
205
                      $record['comment'] .=
206
                ucfirst($key).' '.$entry->description." from '"
207
                .$entry->changes->get('old')[$key]."' to '".$value."'.\n";
208
                  }
209
              }
210
          } else { // description == 'created' ||  'deleted'
211
            $record['comment'] .= $entry->description." user '".$record['user_fullname']."'.\n";
212
          }
213
214
        // Append only non-ignored record entries to log
215
        if ($record['comment']) {
216
            array_push($logs, $record);
217
        }
218
      }
219
220
        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
    private function arrayRecursiveDiff($aArray1, $aArray2)
232
    {
233
        $aReturn = [];
234
        if (!is_array($aArray1) || !is_array($aArray2)) {
235
            return $aReturn;
236
        }
237
        foreach ($aArray1 as $mKey => $mValue) {
238
            if (array_key_exists($mKey, $aArray2)) {
239
                if (is_array($mValue)) {
240
                    $aRecursiveDiff = $this->arrayRecursiveDiff($mValue, $aArray2[$mKey]);
241
                    if (count($aRecursiveDiff)) {
242
                        $aReturn[$mKey] = $aRecursiveDiff;
243
                    }
244
                } else {
245
                    if ($mValue != $aArray2[$mKey]) {
246
                        $aReturn[$mKey] = $mValue;
247
                    }
248
                }
249
            } else {
250
                $aReturn[$mKey] = $mValue;
251
            }
252
        }
253
254
        return $aReturn;
255
256
    public function getDestroyDate($status)
0 ignored issues
show
Bug introduced by
This code did not parse for me. Apparently, there is an error somewhere around this line:

Syntax error, unexpected T_PUBLIC
Loading history...
257
    {
258
        if ($status == 'active') {
259
            return;
260
        }
261
262
        if ($status == 'separated') {
263
            return Carbon::today()->addYears(2)->startOfWeek();
264
        }
265
266
        return Carbon::today()->addWeek()->startOfWeek();
267
268
    }
269
}
270