Passed
Push — master ( 1fd74f...a7048c )
by Dan Michael O.
03:15
created

User::findAlmaUser()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 5
nc 4
nop 2
dl 0
loc 11
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace App;
4
5
use App\Alma\User as AlmaUser;
6
use App\Rules\NotGuestLtid;
7
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...
8
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...
9
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...
10
use Scriptotek\Alma\Client as AlmaClient;
0 ignored issues
show
Bug introduced by
The type Scriptotek\Alma\Client 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...
11
12
class User extends Authenticatable
13
{
14
15
    use Notifiable;
16
17
    /**
18
     * The attributes that are mass assignable.
19
     *
20
     * @var array
21
     */
22
    protected $fillable = ['barcode', 'university_id', 'in_alma', 'firstname', 'lastname', 'phone', 'email', 'lang'];
23
24
    /**
25
     * The attributes that should be cast to native types.
26
     *
27
     * @var array
28
     */
29
    protected $casts = [
30
        'blocks' => 'array',
31
    ];
32
33
   /**
34
     * The attributes that should be mutated to dates.
35
     *
36
     * @var array
37
     */
38
    protected $dates = ['last_loan_at'];
39
40
    /**
41
     * The accessors to append to the model's array form.
42
     *
43
     * @var array
44
     */
45
    protected $appends = ['name', 'url'];
46
47
    /**
48
     * Array of user-editable attributes (excluding machine-generated stuff)
49
     *
50
     * @static array
51
     */
52
    public static $editableAttributes = [
53
        'barcode', 'university_id','lastname', 'firstname', 'phone', 'email', 'lang', 'note'
54
    ];
55
56
    public function loans()
57
    {
58
        return $this->hasMany(Loan::class);
59
    }
60
61
    public function deliveredLoans()
62
    {
63
        return $this->hasMany(Loan::class)
64
            ->whereNotNull('deleted_at')
65
            ->with('item.thing')
66
            ->withTrashed()
67
            ->orderBy('created_at', 'desc');
68
    }
69
70
    public function getNameAttribute()
71
    {
72
        return $this->lastname . ', ' . $this->firstname;
73
    }
74
75
    public function getUrlAttribute()
76
    {
77
        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

77
        return /** @scrutinizer ignore-call */ action('UsersController@getShow', $this->id);
Loading history...
78
    }
79
80
    /**
81
     * Mutuator for the barcode field
82
     *
83
     * @param  string  $value
84
     * @return void
85
     */
86
    public function setBarcodeAttribute($value)
87
    {
88
        if (is_null($value)) {
0 ignored issues
show
introduced by
The condition is_null($value) is always false.
Loading history...
89
            $this->attributes['barcode'] = null;
90
        } else {
91
            $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...
92
        }
93
    }
94
95
    /**
96
     * Merge in UserResponse data
97
     *
98
     * @param AlmaUser $au
99
     * @return void
100
     */
101
    public function mergeFromAlmaResponse(AlmaUser $au)
102
    {
103
        $this->in_alma = true;
0 ignored issues
show
Bug Best Practice introduced by
The property in_alma does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
104
        $this->alma_primary_id = $au->primaryId;
0 ignored issues
show
Bug Best Practice introduced by
The property alma_primary_id does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
105
        $this->alma_user_group = $au->group;
0 ignored issues
show
Bug Best Practice introduced by
The property alma_user_group does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
106
        $this->barcode = $au->getBarcode();
0 ignored issues
show
Bug Best Practice introduced by
The property barcode does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
107
        $this->university_id = $au->getUniversityId();
0 ignored issues
show
Bug Best Practice introduced by
The property university_id does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
108
        $this->lastname = $au->lastName;
0 ignored issues
show
Bug Best Practice introduced by
The property lastname does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
109
        $this->firstname = $au->firstName;
0 ignored issues
show
Bug Best Practice introduced by
The property firstname does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
110
        $this->email = $au->email;
0 ignored issues
show
Bug Best Practice introduced by
The property email does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
111
        $this->phone = $au->phone;
0 ignored issues
show
Bug Best Practice introduced by
The property phone does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
112
        $this->lang = $au->lang;
0 ignored issues
show
Bug Best Practice introduced by
The property lang does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
113
        $this->blocks = $au->blocks;
0 ignored issues
show
Bug Best Practice introduced by
The property blocks does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
114
        $this->fees = $au->getFees();
0 ignored issues
show
Bug Best Practice introduced by
The property fees does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
115
    }
116
117
    protected function mergeAttribute($key, User $user)
118
    {
119
        return strlen($user->$key) > strlen($this->$key) ? $user->$key : $this->$key;
120
    }
121
122
    /**
123
     * Get data for merging $user into the current user. The returned
124
     * array can be passed directly to mergeWith or presented to a user
125
     * for review first.
126
     *
127
     * @param  User  $user
128
     * @return array
129
     */
130
    public function getMergeData($user)
131
    {
132
        $merged = array();
133
        foreach (static::$editableAttributes as $attr) {
134
            $merged[$attr] = $this->mergeAttribute($attr, $user);
135
        }
136
        return $merged;
137
    }
138
139
    /**
140
     * Merge in another user $user
141
     *
142
     * @param  User  $user
143
     * @param  array  $data  An array of merged attributes (optional)
144
     * @return \Illuminate\Support\MessageBag
145
     */
146
    public function merge(User $user, array $data = null)
147
    {
148
149
        if (is_null($data)) {
150
            $data = $this->getMergeData($user);
151
        }
152
153
        // Validate
154
        $errors = new MessageBag();
155
        $barcode = $data['barcode'];
0 ignored issues
show
Unused Code introduced by
The assignment to $barcode is dead and can be removed.
Loading history...
156
157
        // if (!empty($ltid) && !empty($user->ltid) && ($ltid != $user->ltid)) {
158
        //  $errors->add('ltid_conflict', "Kan ikke flette nytt LTID $ltid med eksisterende $user->ltid.");
159
        // }
160
161
        // if (!empty($ltid) && !empty($this->ltid) && ($ltid != $this->ltid)) {
162
        //  $errors->add('ltid_conflict', "Kan ikke flette nytt LTID $ltid med eksisterende $this->ltid.");
163
        // }
164
165
        if ($errors->count() > 0) {
166
            return $errors;
167
        }
168
169
        \Log::info('Slo sammen to brukere (' . $user->id . ' og ' . $this->id . ')');
170
171
        foreach ($user->loans as $loan) {
172
            $loan->user_id = $this->id;
173
            $loan->save();
174
            \Log::info('Lån ' . $loan->id . ' flyttet fra bruker ' . $user->id . ' til ' . $this->id);
175
        }
176
177
        // Delete other user first to avoid database integrity conflicts
178
        $user->delete();
179
180
        // Update properties of the current user with merge data
181
        foreach ($data as $key => $val) {
182
            $this->$key = $val;
183
        }
184
185
        $this->save();
186
187
        return null;
188
    }
189
190
    /**
191
     * Find the first Alma user matching a query.
192
     * @param AlmaClient $alma
193
     * @param array $queries
194
     * @return AlmaUser|null
195
     */
196
    protected function findAlmaUser(AlmaClient $alma, array $queries)
197
    {
198
        foreach ($queries as $query) {
199
            if (!empty($query[1])) {
200
                foreach ($alma->users->search($query[0] . '~' . $query[1], ['limit' => 1]) as $user) {
201
                    return new AlmaUser($user);
202
                }
203
            }
204
        }
205
206
        return null;
207
    }
208
209
    /**
210
     * Update the user object with fresh user data from Alma.
211
     * Returns true if successful, false if the user could no longer be found in Alma.
212
     *
213
     * @param AlmaClient $alma
214
     * @return bool
215
     */
216
    public function updateFromAlma(AlmaClient $alma)
217
    {
218
        $queries = [
219
            ['identifiers', $this->university_id],
220
            ['identifiers', $this->barcode],
221
            ['ALL', $this->university_id],
222
            ['ALL', $this->barcode],
223
        ];
224
225
        $almaUser = $this->findAlmaUser($alma, $queries);
226
        if (is_null($almaUser)) {
227
            $this->in_alma = false;
0 ignored issues
show
Bug Best Practice introduced by
The property in_alma does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
228
            return false;
229
        }
230
231
        $this->mergeFromAlmaResponse($almaUser);
232
        return true;
233
    }
234
}
235