Passed
Push — master ( f6b34e...90b0c1 )
by Dan Michael O.
03:15
created

User::updateFromAlma()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 17
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 11
nc 2
nop 1
dl 0
loc 17
rs 9.9
c 0
b 0
f 0
1
<?php
2
3
namespace App;
4
5
use Illuminate\Foundation\Auth\User as Authenticatable;
0 ignored issues
show
Bug introduced by
The type Illuminate\Foundation\Auth\User was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
6
use Illuminate\Notifications\Notifiable;
0 ignored issues
show
Bug introduced by
The type Illuminate\Notifications\Notifiable was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
7
use Illuminate\Support\MessageBag;
0 ignored issues
show
Bug introduced by
The type Illuminate\Support\MessageBag was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
8
9
class User extends Authenticatable
10
{
11
12
    use Notifiable;
13
14
    /**
15
     * The attributes that are mass assignable.
16
     *
17
     * @var array
18
     */
19
    protected $fillable = ['barcode', 'university_id', 'in_alma', 'firstname', 'lastname', 'phone', 'email', 'lang'];
20
21
    /**
22
     * The attributes that should be cast to native types.
23
     *
24
     * @var array
25
     */
26
    protected $casts = [
27
        'blocks' => 'array',
28
        'fees' => 'integer',
29
    ];
30
31
   /**
32
     * The attributes that should be mutated to dates.
33
     *
34
     * @var array
35
     */
36
    protected $dates = ['last_loan_at'];
37
38
    /**
39
     * The accessors to append to the model's array form.
40
     *
41
     * @var array
42
     */
43
    protected $appends = ['name', 'url'];
44
45
    /**
46
     * Array of user-editable attributes (excluding machine-generated stuff)
47
     *
48
     * @static array
49
     */
50
    public static $editableAttributes = [
51
        'barcode', 'university_id','lastname', 'firstname', 'phone', 'email', 'lang', 'note'
52
    ];
53
54
    public function loans()
55
    {
56
        return $this->hasMany(Loan::class);
57
    }
58
59
    public function deliveredLoans()
60
    {
61
        return $this->hasMany(Loan::class)
62
            ->whereNotNull('deleted_at')
63
            ->with('item.thing')
64
            ->withTrashed()
65
            ->orderBy('created_at', 'desc');
66
    }
67
68
    public function getNameAttribute()
69
    {
70
        return $this->lastname . ', ' . $this->firstname;
71
    }
72
73
    public function getUrlAttribute()
74
    {
75
        return action('UsersController@getShow', $this->id);
0 ignored issues
show
Bug introduced by
The function action was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

75
        return /** @scrutinizer ignore-call */ action('UsersController@getShow', $this->id);
Loading history...
76
    }
77
78
    /**
79
     * Mutuator for the barcode field
80
     *
81
     * @param  string  $value
82
     * @return void
83
     */
84
    public function setBarcodeAttribute($value)
85
    {
86
        if (is_null($value)) {
0 ignored issues
show
introduced by
The condition is_null($value) is always false.
Loading history...
87
            $this->attributes['barcode'] = null;
88
        } else {
89
            $this->attributes['barcode'] = strtolower($value);
0 ignored issues
show
Bug Best Practice introduced by
The property attributes does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
90
        }
91
    }
92
93
    protected function mergeAttribute($key, User $user)
94
    {
95
        return strlen($user->$key) > strlen($this->$key) ? $user->$key : $this->$key;
96
    }
97
98
    /**
99
     * Get data for merging $user into the current user. The returned
100
     * array can be passed directly to mergeWith or presented to a user
101
     * for review first.
102
     *
103
     * @param  User  $user
104
     * @return array
105
     */
106
    public function getMergeData($user)
107
    {
108
        $merged = array();
109
        foreach (static::$editableAttributes as $attr) {
110
            $merged[$attr] = $this->mergeAttribute($attr, $user);
111
        }
112
        return $merged;
113
    }
114
115
    /**
116
     * Merge in another user $user
117
     *
118
     * @param  User  $user
119
     * @param  array  $data  An array of merged attributes (optional)
120
     * @return \Illuminate\Support\MessageBag
121
     */
122
    public function merge(User $user, array $data = null)
123
    {
124
125
        if (is_null($data)) {
126
            $data = $this->getMergeData($user);
127
        }
128
129
        // Validate
130
        $errors = new MessageBag();
131
132
        // if (!empty($ltid) && !empty($user->ltid) && ($ltid != $user->ltid)) {
133
        //  $errors->add('ltid_conflict', "Kan ikke flette nytt LTID $ltid med eksisterende $user->ltid.");
134
        // }
135
136
        // if (!empty($ltid) && !empty($this->ltid) && ($ltid != $this->ltid)) {
137
        //  $errors->add('ltid_conflict', "Kan ikke flette nytt LTID $ltid med eksisterende $this->ltid.");
138
        // }
139
140
        if ($errors->count() > 0) {
141
            return $errors;
142
        }
143
144
        \Log::info('Slo sammen to brukere (ID ' . $user->id . ' og ' . $this->id . ')');
145
146
        foreach ($user->loans as $loan) {
147
            $loan->user_id = $this->id;
148
            $loan->save();
149
            \Log::info('Lån ' . $loan->id . ' flyttet fra bruker ' . $user->id . ' til ' . $this->id);
150
        }
151
152
        // Delete other user first to avoid database integrity conflicts
153
        $user->delete();
154
155
        // Update properties of the current user with merge data
156
        foreach ($data as $key => $val) {
157
            $this->$key = $val;
158
        }
159
160
        $this->save();
161
162
        return null;
163
    }
164
165
    public function hasFees()
166
    {
167
        return $this->fees !== 0;
168
    }
169
170
    /**
171
     * Update unique value. If the value clashes with another user, delete the other user if it has no loans.
172
     *
173
     * @param string $key
174
     * @param string $val
175
     */
176
    public function setUniqueValue(string $key, string $val)
177
    {
178
        // Check for uniqueness
179
        if (is_null($this->id)) {
180
            // Model not saved yet
181
            $otherUser = User::where($key, '=', $val)->first();
182
        } else {
183
            $otherUser = User::where($key, '=', $val)->where('id', '!=', $this->id)->first();
184
        }
185
186
        if (!is_null($otherUser)) {
187
            if (!$otherUser->loans->count()) {
188
                if (!is_null($this->id)) {
189
                    $localRef = "brukeren med ID {$this->id}";
190
                } else {
191
                    $localRef = "(ny bruker)";
192
                }
193
                \Log::warning(
194
                    "Verdien '{$val}' i bruk som {$key} for flere brukere. " .
195
                    "Sletter brukeren med ID {$otherUser->id} (som ikke hadde noen lån), beholder $localRef."
196
                );
197
                $otherUser->delete();
198
            } else {
199
                \Log::warning(
200
                    "Verdien '{$val}' i bruk som {$key} for flere brukere, men ".
201
                    "kan ikke slette brukeren {$otherUser->id}, fordi brukeren har lån."
202
                );
203
            }
204
        }
205
206
        $this->{$key} = $val;
207
    }
208
}
209