UsersController   A
last analyzed

Complexity

Total Complexity 41

Size/Duplication

Total Lines 373
Duplicated Lines 0 %

Importance

Changes 6
Bugs 0 Features 0
Metric Value
eloc 152
c 6
b 0
f 0
dl 0
loc 373
rs 9.1199
wmc 41

14 Methods

Rating   Name   Duplication   Size   Complexity  
A getIndex() 0 23 1
B connect() 0 32 7
A upsert() 0 29 3
A getEdit() 0 25 4
A postMerge() 0 32 6
A sync() 0 18 5
A searchAlma() 0 16 2
A json() 0 16 3
A getMerge() 0 8 1
A getShow() 0 4 1
A deleteForm() 0 9 2
A createForm() 0 6 1
A connectForm() 0 10 3
A delete() 0 15 2

How to fix   Complexity   

Complex Class

Complex classes like UsersController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use UsersController, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace App\Http\Controllers;
4
5
use App\Alma\AlmaUsers;
6
use App\Alma\User as AlmaUser;
7
use App\Http\Requests\UserUpsertRequest;
8
use App\User;
9
use App\UserIdentifier;
10
use Carbon\Carbon;
11
use Illuminate\Http\Request;
12
use Illuminate\Http\Response;
13
use Illuminate\Support\Arr;
14
use LimitIterator;
15
use Scriptotek\Alma\Client as AlmaClient;
16
17
class UsersController extends Controller
18
{
19
    /**
20
     * Display a listing of the resource.
21
     *
22
     * @param  Request $request
23
     * @return Response
24
     */
25
    public function getIndex(Request $request)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed. ( Ignorable by Annotation )

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

25
    public function getIndex(/** @scrutinizer ignore-unused */ Request $request)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
26
    {
27
        $users = User::with('loans', 'identifiers')
28
            ->where('lastname', '!=', '(anonymisert)')
29
            ->orderBy('lastname')
30
            ->get()
31
            ->map(function ($user) {
32
                return [
33
                    'id' => $user->id,
34
                    'primaryId' => $user->alma_primary_id,
35
                    'group' => $user->alma_user_group,
36
                    'name' => $user->lastname . ', ' . $user->firstname,
37
                    'identifiers' => $user->getAllIdentifierValues(),
38
                    'in_alma' => $user->in_alma,
39
                    'created_at' => $user->created_at->toDateTimestring(),
40
                    'note' => $user->note,
41
                    'blocks' => $user->blocks,
42
                    'fees' => $user->fees,
43
                ];
44
            });
45
46
        return response()->view('users.index', [
47
            'users' => $users,
48
        ]);
49
    }
50
51
    /**
52
     * Display a listing of the resource as json.
53
     *
54
     * @param  Request $request
55
     * @return Response
56
     */
57
    public function json(Request $request)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed. ( Ignorable by Annotation )

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

57
    public function json(/** @scrutinizer ignore-unused */ Request $request)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
58
    {
59
        $users = [];
60
        foreach (User::with('identifiers')->get() as $user) {
61
            $users[] = [
62
                'id' => $user->alma_primary_id ?? $user->id,
63
                'type' => $user->alma_primary_id ? 'alma' : 'local',
64
                'group' => $user->alma_user_group,
0 ignored issues
show
Bug introduced by
The property alma_user_group does not seem to exist on App\User. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
65
                'name' => $user->lastname . ', ' . $user->firstname,
66
                'identifiers' => $user->identifiers->map(function ($x) {
67
                    return $x->value;
68
                }),
69
            ];
70
        }
71
72
        return response()->json($users);
0 ignored issues
show
Bug Best Practice introduced by
The expression return response()->json($users) returns the type Illuminate\Http\JsonResponse which is incompatible with the documented return type Illuminate\Http\Response.
Loading history...
73
    }
74
75
    /**
76
     * Display a listing of the resource.
77
     *
78
     * @param AlmaClient $alma
79
     * @param  Request $request
80
     * @return Response
81
     */
82
    public function searchAlma(AlmaClient $alma, Request $request)
83
    {
84
        if (is_null($alma->key)) {
0 ignored issues
show
introduced by
The condition is_null($alma->key) is always false.
Loading history...
85
            \Log::warning('Cannot search Alma users since no Alma API key is configured.');
86
            return response()->json([]);
87
        }
88
        $query = 'ALL~' . $request->input('query');
89
        $users = collect($alma->users->search($query, ['limit' => 5]))->map(function ($result) {
90
            return [
91
                'type' => 'alma',
92
                'id' => $result->primary_id,
93
                'name' => "{$result->last_name}, {$result->first_name}",
94
            ];
95
        });
96
97
        return response()->json($users);
0 ignored issues
show
Bug Best Practice introduced by
The expression return response()->json($users) returns the type Illuminate\Http\JsonResponse which is incompatible with the documented return type Illuminate\Http\Response.
Loading history...
98
    }
99
100
    /**
101
     * Display the specified resource.
102
     *
103
     * @param User $user
104
     * @return Response
105
     */
106
    public function getShow(User $user)
107
    {
108
        return response()->view('users.show', [
109
            'user' => $user,
110
        ]);
111
    }
112
113
    /**
114
     * Display form for connecting local user to external user.
115
     *
116
     * @param User $user
117
     * @return Response
118
     */
119
    public function connectForm(AlmaUsers $almaUsers, User $user)
120
    {
121
        if (!$almaUsers->hasKey()) {
122
            return back()->with('error', 'Ingen API-nøkkel konfigurert, Bibrex kan ikke snakke med Alma.');
0 ignored issues
show
Bug Best Practice introduced by
The expression return back()->with('err...ikke snakke med Alma.') returns the type Illuminate\Http\RedirectResponse which is incompatible with the documented return type Illuminate\Http\Response.
Loading history...
123
        }
124
125
        $ident = $user->identifiers()->first();
126
        return response()->view('users.connect', [
127
            'user' => $user,
128
            'user_identifier' => is_null($ident) ? null : $ident->value,
129
        ]);
130
    }
131
132
    /**
133
     * Connect local user to external user.
134
     *
135
     * @param AlmaUsers $almaUsers
136
     * @param Request $request
137
     * @param User $user
138
     * @return Response
139
     */
140
    public function connect(AlmaUsers $almaUsers, Request $request, User $user)
141
    {
142
        if (!$almaUsers->hasKey()) {
143
            return back()->with('error', 'Ingen API-nøkkel konfigurert, Bibrex kan ikke snakke med Alma.');
0 ignored issues
show
Bug Best Practice introduced by
The expression return back()->with('err...ikke snakke med Alma.') returns the type Illuminate\Http\RedirectResponse which is incompatible with the documented return type Illuminate\Http\Response.
Loading history...
144
        }
145
146
        $identifier = $request->identifier;
147
        if (empty($identifier)) {
148
            return back()->with('error', 'Du må registrere låne-ID.');
0 ignored issues
show
Bug Best Practice introduced by
The expression return back()->with('err... registrere låne-ID.') returns the type Illuminate\Http\RedirectResponse which is incompatible with the documented return type Illuminate\Http\Response.
Loading history...
149
        }
150
151
        $other = User::fromIdentifier($identifier);
152
        if (!is_null($other) && $other->id != $user->id) {
153
            return back()->with('error', 'Låne-ID-en er allerede koblet til en annen Bibrex-bruker ' .
0 ignored issues
show
Bug Best Practice introduced by
The expression return back()->with('err...fra brukeroversikten.') returns the type Illuminate\Http\RedirectResponse which is incompatible with the documented return type Illuminate\Http\Response.
Loading history...
154
                '(' . $other->name . '). Du kan slå dem sammen fra brukeroversikten.');
155
        }
156
157
        $almaUser = $almaUsers->findById($identifier);
158
159
        if (!$almaUser) {
160
            return back()->with('error', 'Fant ikke noen bruker med identifikator ' . $identifier . ' i Alma 😭 ');
0 ignored issues
show
Bug Best Practice introduced by
The expression return back()->with('err...fier . ' i Alma 😭 ') returns the type Illuminate\Http\RedirectResponse which is incompatible with the documented return type Illuminate\Http\Response.
Loading history...
161
        }
162
163
        try {
164
            $almaUsers->updateLocalUserFromAlmaUser($user, $almaUser);
165
        } catch (\RuntimeException $ex) {
166
            return back()->with('error', $ex->getMessage());
0 ignored issues
show
Bug Best Practice introduced by
The expression return back()->with('error', $ex->getMessage()) returns the type Illuminate\Http\RedirectResponse which is incompatible with the documented return type Illuminate\Http\Response.
Loading history...
167
        }
168
        $user->save();
169
170
        return redirect()->action('UsersController@getShow', $user->id)
0 ignored issues
show
Bug Best Practice introduced by
The expression return redirect()->actio...et med Alma-brukeren!') returns the type Illuminate\Http\RedirectResponse which is incompatible with the documented return type Illuminate\Http\Response.
Loading history...
171
            ->with('status', 'Bibrex-brukeren ble koblet med Alma-brukeren!');
172
    }
173
174
    /**
175
     * Import user data from Alma.
176
     *
177
     * @param AlmaUsers $almaUsers
178
     * @param User $user
179
     * @return Response
180
     */
181
    public function sync(AlmaUsers $almaUsers, User $user)
182
    {
183
        if (!$almaUsers->hasKey()) {
184
            return back()->with('error', 'Ingen API-nøkkel konfigurert, Bibrex kan ikke snakke med Alma.');
0 ignored issues
show
Bug Best Practice introduced by
The expression return back()->with('err...ikke snakke med Alma.') returns the type Illuminate\Http\RedirectResponse which is incompatible with the documented return type Illuminate\Http\Response.
Loading history...
185
        }
186
187
        if (!$user->alma_primary_id && !$user->identifiers->count()) {
188
            return back()->with('error', 'Du må registrere minst én identifikator for brukeren før du kan importere.');
0 ignored issues
show
Bug Best Practice introduced by
The expression return back()->with('err...ør du kan importere.') returns the type Illuminate\Http\RedirectResponse which is incompatible with the documented return type Illuminate\Http\Response.
Loading history...
189
        }
190
191
        if (!$almaUsers->updateLocalUserFromAlmaUser($user)) {
192
            $user->save();
193
194
            return back()->with('error', 'Fant ikke brukeren i Alma 😭');
0 ignored issues
show
Bug Best Practice introduced by
The expression return back()->with('err... brukeren i Alma 😭') returns the type Illuminate\Http\RedirectResponse which is incompatible with the documented return type Illuminate\Http\Response.
Loading history...
195
        }
196
        $user->save();
197
198
        return back()->with('status', 'Brukeropplysninger ble oppdatert fra Alma.');
0 ignored issues
show
Bug Best Practice introduced by
The expression return back()->with('sta...e oppdatert fra Alma.') returns the type Illuminate\Http\RedirectResponse which is incompatible with the documented return type Illuminate\Http\Response.
Loading history...
199
    }
200
201
    /**
202
     * Show the form for editing the specified resource.
203
     *
204
     * @param User $user
205
     * @param Request $request
206
     * @return Response
207
     */
208
    public function getEdit(User $user, Request $request)
209
    {
210
        if (!$user->id) {
211
            $identifiers = [];
212
            if ($request->barcode) {
213
                $identifiers[] = UserIdentifier::make([
214
                    'value' => $request->barcode,
215
                    'type' => 'barcode',
216
                ]);
217
            }
218
            if ($request->university_id) {
219
                $identifiers[] = UserIdentifier::make([
220
                    'value' => $request->university_id,
221
                    'type' => 'university_id',
222
                ]);
223
            }
224
            $user->identifiers = $identifiers;
225
            $user->lastname = $request->lastname;
226
            $user->firstname = $request->firstname;
227
            $user->phone = $request->phone;
228
            $user->email = $request->email;
229
        }
230
231
        return response()->view('users.edit', array(
232
            'user' => $user
233
        ));
234
    }
235
236
    /**
237
     * Update the specified resource in storage.
238
     *
239
     * @param User $user
240
     * @param UserUpsertRequest $request
241
     * @return Response
242
     */
243
    public function upsert(User $user, UserUpsertRequest $request)
244
    {
245
        $isNewUser = !$user->exists;
246
247
        $user->lastname = $request->lastname;
248
        $user->firstname = $request->firstname;
249
        $user->phone = $request->phone;
250
        $user->email = $request->email;
251
        $user->note = $request->note;
252
        $user->lang = $request->lang;
253
        $user->last_loan_at = Carbon::now();
254
        if (!$user->save()) {
255
            throw new \RuntimeException('Ukjent feil under lagring av bruker!');
256
        }
257
258
        $user->setIdentifiers($request->identifiers);
259
260
        if ($isNewUser) {
261
            return redirect()->action('LoansController@getIndex')
0 ignored issues
show
Bug Best Practice introduced by
The expression return redirect()->actio... ' . $user->firstname)) returns the type Illuminate\Http\RedirectResponse which is incompatible with the documented return type Illuminate\Http\Response.
Loading history...
262
                ->with('status', 'Brukeren ble opprettet.')
263
                ->with('user', [
264
                    'type' => 'local',
265
                    'id' => $user->id,
266
                    'name' => $user->lastname . ', ' . $user->firstname,
267
                ]);
268
        }
269
270
        return redirect()->action('UsersController@getShow', $user->id)
0 ignored issues
show
Bug Best Practice introduced by
The expression return redirect()->actio...'Brukeren ble lagret.') returns the type Illuminate\Http\RedirectResponse which is incompatible with the documented return type Illuminate\Http\Response.
Loading history...
271
            ->with('status', 'Brukeren ble lagret.');
272
    }
273
274
    /**
275
     * Display form to merge two users.
276
     *
277
     * @param User $user1
278
     * @param User $user2
279
     * @return Response
280
     */
281
    public function getMerge(User $user1, User $user2)
282
    {
283
        $merged = $user1->getMergeData($user2);
284
285
        return response()->view('users.merge', array(
286
            'user1' => $user1,
287
            'user2' => $user2,
288
            'merged' => $merged
289
        ));
290
    }
291
292
    /**
293
     * Merge $user2 into $user1
294
     *
295
     * @param Request $request
296
     * @param User $user1
297
     * @param User $user2
298
     * @return Response
299
     */
300
    public function postMerge(Request $request, User $user1, User $user2)
301
    {
302
        $mergedAttributes = array();
303
        foreach (User::$editableAttributes as $attr) {
304
            $mergedAttributes[$attr] = $request->input($attr);
305
        }
306
307
        $mergedAttributes['identifiers'] = [];
308
        foreach ($request->all() as $key => $val) {
309
            if (preg_match('/identifier_type_([0-9]+)/', $key, $matches)) {
310
                $identifierId = $matches[1];
311
312
                if (empty($request->{"identifier_value_{$identifierId}"})) {
313
                    continue;
314
                }
315
316
                $mergedAttributes['identifiers'][] = [
317
                    'type' => $request->{"identifier_type_{$identifierId}"},
318
                    'value' => $request->{"identifier_value_{$identifierId}"},
319
                ];
320
            }
321
        }
322
323
        $errors = $user1->merge($user2, $mergedAttributes);
324
325
        if (!is_null($errors)) {
326
            return redirect()->action('UsersController@getMerge', array($user1->id, $user2->id))
0 ignored issues
show
Bug Best Practice introduced by
The expression return redirect()->actio...))->withErrors($errors) returns the type Illuminate\Http\RedirectResponse which is incompatible with the documented return type Illuminate\Http\Response.
Loading history...
327
                ->withErrors($errors);
328
        }
329
330
        return redirect()->action('UsersController@getShow', $user1->id)
0 ignored issues
show
Bug Best Practice introduced by
The expression return redirect()->actio...Brukerne ble flettet.') returns the type Illuminate\Http\RedirectResponse which is incompatible with the documented return type Illuminate\Http\Response.
Loading history...
331
            ->with('status', 'Brukerne ble flettet.');
332
    }
333
334
    /**
335
     * Show the form for creating the specified resource.
336
     *
337
     * @param Request $request
338
     * @return Response
339
     */
340
    public function createForm(Request $request)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed. ( Ignorable by Annotation )

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

340
    public function createForm(/** @scrutinizer ignore-unused */ Request $request)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
341
    {
342
        $user = User::make();
343
344
        return response()->view('users.create', [
345
            'user' => $user,
346
        ]);
347
    }
348
349
    /**
350
     * Show the form for deleting the specified resource.
351
     *
352
     * @param User $user
353
     * @param Request $request
354
     * @return Response
355
     */
356
    public function deleteForm(User $user, Request $request)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed. ( Ignorable by Annotation )

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

356
    public function deleteForm(User $user, /** @scrutinizer ignore-unused */ Request $request)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
357
    {
358
        if ($user->loans()->count()) {
359
            return redirect()->action('UsersController@getShow', $user->id)
0 ignored issues
show
Bug Best Practice introduced by
The expression return redirect()->actio...uker med aktive lån.') returns the type Illuminate\Http\RedirectResponse which is incompatible with the documented return type Illuminate\Http\Response.
Loading history...
360
                ->with('error', 'Kan ikke slette en bruker med aktive lån.');
361
        }
362
363
        return response()->view('users.delete', [
364
            'user' => $user,
365
        ]);
366
    }
367
368
    /**
369
     * Delte the specified resource from storage.
370
     *
371
     * @param User $user
372
     * @param Request $request
373
     * @return Response
374
     */
375
    public function delete(User $user, Request $request)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed. ( Ignorable by Annotation )

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

375
    public function delete(User $user, /** @scrutinizer ignore-unused */ Request $request)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
376
    {
377
        if ($user->loans()->count()) {
378
            return redirect()->action('UsersController@getShow', $user->id)
0 ignored issues
show
Bug Best Practice introduced by
The expression return redirect()->actio...uker med aktive lån.') returns the type Illuminate\Http\RedirectResponse which is incompatible with the documented return type Illuminate\Http\Response.
Loading history...
379
                ->with('error', 'Kan ikke slette en bruker med aktive lån.');
380
        }
381
382
        $user_id = $user->id;
383
        $name = $user->name;
384
385
        $user->delete();
386
        \Log::info(sprintf('Slettet brukeren %s (ID %d)', $name, $user_id));
387
388
        return redirect()->action('UsersController@getIndex')
0 ignored issues
show
Bug Best Practice introduced by
The expression return redirect()->actio...har ikke drept noen).') returns the type Illuminate\Http\RedirectResponse which is incompatible with the documented return type Illuminate\Http\Response.
Loading history...
389
            ->with('status', "Brukeren $name ble slettet (men slapp av, du har ikke drept noen).");
390
    }
391
}
392