Passed
Push — master ( d79a37...05d8cd )
by Dan Michael O.
01:59
created

UsersController::upsert()   B

Complexity

Conditions 8
Paths 18

Size

Total Lines 69
Code Lines 43

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 43
c 0
b 0
f 0
nc 18
nop 2
dl 0
loc 69
rs 7.9875

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace App\Http\Controllers;
4
5
use App\Alma\AlmaUsers;
6
use App\Alma\User as AlmaUser;
7
use App\User;
8
use App\UserIdentifier;
9
use Carbon\Carbon;
0 ignored issues
show
Bug introduced by
The type Carbon\Carbon 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 Illuminate\Http\Request;
0 ignored issues
show
Bug introduced by
The type Illuminate\Http\Request 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
use Illuminate\Http\Response;
0 ignored issues
show
Bug introduced by
The type Illuminate\Http\Response 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...
12
use Illuminate\Support\Arr;
0 ignored issues
show
Bug introduced by
The type Illuminate\Support\Arr 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...
13
use LimitIterator;
14
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...
15
16
class UsersController extends Controller
17
{
18
19
    private $messages = [
20
        'lastname.required' => 'Etternavn må fylles inn.',
21
        'firstname.required' => 'Fornavn må fylles inn.',
22
        'email.required_without' => 'Enten e-post eller telefonnummer må fylles inn.',
23
        'lang.required' => 'Språk må fylles inn.'
24
    ];
25
26
    /**
27
     * Display a listing of the resource.
28
     *
29
     * @param  Request $request
30
     * @return Response
31
     */
32
    public function getIndex(Request $request)
33
    {
34
        $users = User::with('loans', 'identifiers')
35
            ->where('lastname', '!=', '(anonymisert)')
36
            ->orderBy('lastname')
37
            ->get()
38
            ->map(function ($user) {
39
                return [
40
                    'id' => $user->id,
41
                    'primaryId' => $user->alma_primary_id,
42
                    'group' => $user->alma_user_group,
43
                    'name' => $user->lastname . ', ' . $user->firstname,
44
                    'identifiers' => $user->getAllIdentifierValues(),
45
                    'in_alma' => $user->in_alma,
46
                    'created_at' => $user->created_at->toDateTimestring(),
47
                    'note' => $user->note,
48
                    'blocks' => $user->blocks,
49
                    'fees' => $user->fees,
50
                ];
51
            });
52
53
        return response()->view('users.index', [
0 ignored issues
show
Bug introduced by
The function response 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

53
        return /** @scrutinizer ignore-call */ response()->view('users.index', [
Loading history...
54
            'users' => $users,
55
        ]);
56
    }
57
58
    /**
59
     * Display a listing of the resource as json.
60
     *
61
     * @param  Request $request
62
     * @return Response
63
     */
64
    public function json(Request $request)
65
    {
66
        $users = [];
67
        foreach (User::with('identifiers')->get() as $user) {
68
            $users[] = [
69
                'id' => $user->alma_primary_id ?? $user->id,
70
                // 'primaryId' => $user->alma_primary_id,
71
                'group' => $user->alma_user_group,
72
                'name' => $user->lastname . ', ' . $user->firstname,
73
                'identifiers' => $user->identifiers,
74
                'type' => 'local',
75
            ];
76
        }
77
78
        return response()->json($users);
0 ignored issues
show
Bug introduced by
The function response 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

78
        return /** @scrutinizer ignore-call */ response()->json($users);
Loading history...
79
    }
80
81
    /**
82
     * Display a listing of the resource.
83
     *
84
     * @param AlmaClient $alma
85
     * @param  Request $request
86
     * @return Response
87
     */
88
    public function searchAlma(AlmaClient $alma, Request $request)
89
    {
90
        if (is_null($alma->key)) {
91
            \Log::warning('Cannot search Alma users since no Alma API key is configured.');
92
            return response()->json([]);
0 ignored issues
show
Bug introduced by
The function response 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

92
            return /** @scrutinizer ignore-call */ response()->json([]);
Loading history...
93
        }
94
        $query = 'ALL~' . $request->input('query');
95
        $users = collect($alma->users->search($query, ['limit' => 5]))->map(function ($result) {
0 ignored issues
show
Bug introduced by
The function collect 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

95
        $users = /** @scrutinizer ignore-call */ collect($alma->users->search($query, ['limit' => 5]))->map(function ($result) {
Loading history...
96
            return [
97
                'id' => $result->primary_id,
98
                'name' => "{$result->last_name}, {$result->first_name}",
99
            ];
100
        });
101
102
        return response()->json($users);
103
    }
104
105
    /**
106
     * Display the specified resource.
107
     *
108
     * @param User $user
109
     * @return Response
110
     */
111
    public function getShow(User $user)
112
    {
113
        return response()->view('users.show', [
0 ignored issues
show
Bug introduced by
The function response 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

113
        return /** @scrutinizer ignore-call */ response()->view('users.show', [
Loading history...
114
            'user' => $user,
115
        ]);
116
    }
117
118
    /**
119
     * Display form for connecting local user to external user.
120
     *
121
     * @param User $user
122
     * @return Response
123
     */
124
    public function connectForm(User $user)
125
    {
126
        $ident = $user->identifiers()->first();
127
        return response()->view('users.connect', [
0 ignored issues
show
Bug introduced by
The function response 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

127
        return /** @scrutinizer ignore-call */ response()->view('users.connect', [
Loading history...
128
            'user' => $user,
129
            'user_identifier' => is_null($ident) ? null : $ident->value,
130
        ]);
131
    }
132
133
    /**
134
     * Connect local user to external user.
135
     *
136
     * @param AlmaUsers $almaUsers
137
     * @param Request $request
138
     * @param User $user
139
     * @return Response
140
     */
141
    public function connect(AlmaUsers $almaUsers, Request $request, User $user)
142
    {
143
        $identifier = $request->identifier;
144
        if (empty($identifier)) {
145
            return back()->with('error', 'Du må registrere låne-ID.');
0 ignored issues
show
Bug introduced by
The function back 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

145
            return /** @scrutinizer ignore-call */ back()->with('error', 'Du må registrere låne-ID.');
Loading history...
146
        }
147
148
        $other = User::fromIdentifier($identifier);
149
        if (!is_null($other) && $other->id != $user->id) {
150
            return back()->with('error', 'Låne-ID-en er allerede koblet til en annen Bibrex-bruker ' .
151
                '(' . $other->name . '). Du kan slå dem sammen fra brukeroversikten.');
152
        }
153
154
        $almaUser = $almaUsers->findById($identifier);
155
156
        if (!$almaUser) {
157
            return back()->with('error', 'Fant ikke noen bruker med identifikator ' . $identifier . ' i Alma 😭 ');
158
        }
159
160
        try {
161
            $almaUsers->updateLocalUserFromAlmaUser($user, $almaUser);
162
        } catch (\RuntimeException $ex) {
163
            return back()->with('error', $ex->getMessage());
164
        }
165
        $user->save();
166
167
        return redirect()->action('UsersController@getShow', $user->id)
0 ignored issues
show
Bug introduced by
The function redirect 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

167
        return /** @scrutinizer ignore-call */ redirect()->action('UsersController@getShow', $user->id)
Loading history...
168
            ->with('status', 'Bibrex-brukeren ble koblet med Alma-brukeren!');
169
    }
170
171
    /**
172
     * Import user data from Alma.
173
     *
174
     * @param AlmaUsers $almaUsers
175
     * @param User $user
176
     * @return Response
177
     */
178
    public function sync(AlmaUsers $almaUsers, User $user)
179
    {
180
        if (!$user->alma_primary_id && !$user->identifiers->count()) {
181
            return back()->with('error', 'Du må registrere minst én identifikator for brukeren før du kan importere.');
0 ignored issues
show
Bug introduced by
The function back 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

181
            return /** @scrutinizer ignore-call */ back()->with('error', 'Du må registrere minst én identifikator for brukeren før du kan importere.');
Loading history...
182
        }
183
184
        if (!$almaUsers->updateLocalUserFromAlmaUser($user)) {
185
            $user->save();
186
187
            return back()->with('error', 'Fant ikke brukeren i Alma 😭');
188
        }
189
        $user->save();
190
191
        return back()->with('status', 'Brukeropplysninger ble oppdatert fra Alma.');
192
    }
193
194
    /**
195
     * Show the form for editing the specified resource.
196
     *
197
     * @param User $user
198
     * @param Request $request
199
     * @return Response
200
     */
201
    public function getEdit(User $user, Request $request)
202
    {
203
        if (!$user->id) {
204
            $identifiers = [];
205
            if ($request->barcode) {
206
                $identifiers[] = UserIdentifier::make([
207
                    'value' => $request->barcode,
208
                    'type' => 'barcode',
209
                ]);
210
            }
211
            if ($request->university_id) {
212
                $identifiers[] = UserIdentifier::make([
213
                    'value' => $request->university_id,
214
                    'type' => 'university_id',
215
                ]);
216
            }
217
            $user->identifiers = $identifiers;
218
            $user->lastname = $request->lastname;
219
            $user->firstname = $request->firstname;
220
            $user->phone = $request->phone;
221
            $user->email = $request->email;
222
        }
223
224
        return response()->view('users.edit', array(
0 ignored issues
show
Bug introduced by
The function response 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

224
        return /** @scrutinizer ignore-call */ response()->view('users.edit', array(
Loading history...
225
            'user' => $user
226
        ));
227
    }
228
229
    /**
230
     * Update the specified resource in storage.
231
     *
232
     * @param User $user
233
     * @param Request $request
234
     * @return Response
235
     * @throws \Illuminate\Validation\ValidationException
236
     */
237
    public function upsert(User $user, Request $request)
238
    {
239
        //  TODO: Move to a new UserUpsertRequest --------------------------------------------------------------------
240
241
        $validators = [
242
            'lastname' => 'required',
243
            'firstname' => 'required',
244
            'email' => 'requiredWithout:phone',
245
            'lang' => 'required',
246
        ];
247
248
        $identifiers = [];
249
        $messages = $this->messages;
250
        foreach ($request->all() as $key => $val) {
251
            if (preg_match('/identifier_type_(new|[0-9]+)/', $key, $matches)) {
252
                $identifierId = $matches[1];
253
254
                if (empty($request->{"identifier_value_{$identifierId}"})) {
255
                    continue;
256
                }
257
258
                $identifiers[] = [
259
                    'type' => $request->{"identifier_type_{$identifierId}"},
260
                    'value' => $request->{"identifier_value_{$identifierId}"},
261
                ];
262
263
                if (!empty($request->{"identifier_value_{$identifierId}"})) {
264
                    $validators["identifier_value_{$identifierId}"] =
265
                        'unique:user_identifiers,value' . ($identifierId == 'new' ? '' : ",$identifierId");
266
                    $validators["identifier_type_{$identifierId}"] = 'in:barcode,university_id';
267
                    $messages["identifier_value_{$identifierId}.unique"] =
268
                        'Det finnes allerede en annen bruker med denne identifikatoren.';
269
                    $messages["identifier_type_{$identifierId}.in"] = 'Identifikatoren har ugyldig type.';
270
                }
271
            }
272
        }
273
274
        \Validator::make($request->input(), $validators, $messages)->validate();
0 ignored issues
show
Bug introduced by
The type Validator 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...
275
276
        // ------------------------------------------------------------------------------------------------
277
278
        $user->lastname = $request->input('lastname');
279
        $user->firstname = $request->input('firstname');
280
        $user->phone = $request->input('phone');
281
        $user->email = $request->input('email');
282
        $user->note = $request->input('note');
283
        $user->lang = $request->input('lang');
284
        $user->last_loan_at = Carbon::now();
285
        $newUser = !$user->exists;
286
        if (!$user->save()) {
287
            throw new \RuntimeException('Ukjent feil under lagring av bruker!');
288
        }
289
290
        // Defer uniqueness check in case values are swapped
291
292
        $user->setIdentifiers($identifiers);
293
294
        if ($newUser) {
295
            return redirect()->action('LoansController@getIndex')
0 ignored issues
show
Bug introduced by
The function redirect 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

295
            return /** @scrutinizer ignore-call */ redirect()->action('LoansController@getIndex')
Loading history...
296
                ->with('status', 'Brukeren ble opprettet.')
297
                ->with('user', [
298
                    'type' => 'local',
299
                    'id' => $user->id,
300
                    'name' => $user->lastname . ', ' . $user->firstname,
301
                ]);
302
        }
303
304
        return redirect()->action('UsersController@getShow', $user->id)
305
            ->with('status', 'Brukeren ble lagret.');
306
    }
307
308
    /**
309
     * Display form to merge two users.
310
     *
311
     * @param User $user1
312
     * @param User $user2
313
     * @return Response
314
     */
315
    public function getMerge(User $user1, User $user2)
316
    {
317
        $merged = $user1->getMergeData($user2);
318
319
        return response()->view('users.merge', array(
0 ignored issues
show
Bug introduced by
The function response 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

319
        return /** @scrutinizer ignore-call */ response()->view('users.merge', array(
Loading history...
320
            'user1' => $user1,
321
            'user2' => $user2,
322
            'merged' => $merged
323
        ));
324
    }
325
326
    /**
327
     * Merge $user2 into $user1
328
     *
329
     * @param Request $request
330
     * @param User $user1
331
     * @param User $user2
332
     * @return Response
333
     */
334
    public function postMerge(Request $request, User $user1, User $user2)
335
    {
336
        $mergedAttributes = array();
337
        foreach (User::$editableAttributes as $attr) {
338
            $mergedAttributes[$attr] = $request->input($attr);
339
        }
340
341
        $mergedAttributes['identifiers'] = [];
342
        foreach ($request->all() as $key => $val) {
343
            if (preg_match('/identifier_type_([0-9]+)/', $key, $matches)) {
344
                $identifierId = $matches[1];
345
346
                if (empty($request->{"identifier_value_{$identifierId}"})) {
347
                    continue;
348
                }
349
350
                $mergedAttributes['identifiers'][] = [
351
                    'type' => $request->{"identifier_type_{$identifierId}"},
352
                    'value' => $request->{"identifier_value_{$identifierId}"},
353
                ];
354
            }
355
        }
356
357
        $errors = $user1->merge($user2, $mergedAttributes);
358
359
        if (!is_null($errors)) {
360
            return redirect()->action('UsersController@getMerge', array($user1->id, $user2->id))
0 ignored issues
show
Bug introduced by
The function redirect 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

360
            return /** @scrutinizer ignore-call */ redirect()->action('UsersController@getMerge', array($user1->id, $user2->id))
Loading history...
361
                ->withErrors($errors);
362
        }
363
364
        return redirect()->action('UsersController@getShow', $user1->id)
365
            ->with('status', 'Brukerne ble flettet.');
366
    }
367
368
    /**
369
     * Show the form for creating the specified resource.
370
     *
371
     * @param Request $request
372
     * @return Response
373
     */
374
    public function createForm(Request $request)
375
    {
376
        $user = User::make();
377
378
        return response()->view('users.create', [
0 ignored issues
show
Bug introduced by
The function response 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

378
        return /** @scrutinizer ignore-call */ response()->view('users.create', [
Loading history...
379
            'user' => $user,
380
        ]);
381
    }
382
383
    /**
384
     * Show the form for deleting the specified resource.
385
     *
386
     * @param User $user
387
     * @param Request $request
388
     * @return Response
389
     */
390
    public function deleteForm(User $user, Request $request)
391
    {
392
        if ($user->loans()->count()) {
393
            return redirect()->action('UsersController@getShow', $user->id)
0 ignored issues
show
Bug introduced by
The function redirect 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

393
            return /** @scrutinizer ignore-call */ redirect()->action('UsersController@getShow', $user->id)
Loading history...
394
                ->with('error', 'Kan ikke slette en bruker med aktive lån.');
395
        }
396
397
        return response()->view('users.delete', [
0 ignored issues
show
Bug introduced by
The function response 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

397
        return /** @scrutinizer ignore-call */ response()->view('users.delete', [
Loading history...
398
            'user' => $user,
399
        ]);
400
    }
401
402
    /**
403
     * Delte the specified resource from storage.
404
     *
405
     * @param User $user
406
     * @param Request $request
407
     * @return Response
408
     */
409
    public function delete(User $user, Request $request)
410
    {
411
        if ($user->loans()->count()) {
412
            return redirect()->action('UsersController@getShow', $user->id)
0 ignored issues
show
Bug introduced by
The function redirect 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

412
            return /** @scrutinizer ignore-call */ redirect()->action('UsersController@getShow', $user->id)
Loading history...
413
                ->with('error', 'Kan ikke slette en bruker med aktive lån.');
414
        }
415
416
        $user_id = $user->id;
417
        $name = $user->name;
418
419
        $user->delete();
420
        \Log::info(sprintf('Slettet brukeren %s (ID %d)', $name, $user_id));
421
422
        return redirect()->action('UsersController@getIndex')
423
            ->with('status', "Brukeren $name ble slettet (men slapp av, du har ikke drept noen).");
424
    }
425
}
426