Passed
Push — master ( 12989d...3ff895 )
by Dan Michael O.
01:53
created

UsersController::searchAlma()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 9
c 1
b 0
f 0
nc 2
nop 2
dl 0
loc 15
rs 9.9666
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;
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...
11
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...
12
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...
13
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...
14
use LimitIterator;
15
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...
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)
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', [
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

46
        return /** @scrutinizer ignore-call */ response()->view('users.index', [
Loading history...
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)
58
    {
59
        $users = [];
60
        foreach (User::with('identifiers')->get() as $user) {
61
            $users[] = [
62
                'id' => $user->alma_primary_id ?? $user->id,
63
                // 'primaryId' => $user->alma_primary_id,
64
                'group' => $user->alma_user_group,
65
                'name' => $user->lastname . ', ' . $user->firstname,
66
                'identifiers' => $user->identifiers,
67
                'type' => 'local',
68
            ];
69
        }
70
71
        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

71
        return /** @scrutinizer ignore-call */ response()->json($users);
Loading history...
72
    }
73
74
    /**
75
     * Display a listing of the resource.
76
     *
77
     * @param AlmaClient $alma
78
     * @param  Request $request
79
     * @return Response
80
     */
81
    public function searchAlma(AlmaClient $alma, Request $request)
82
    {
83
        if (is_null($alma->key)) {
84
            \Log::warning('Cannot search Alma users since no Alma API key is configured.');
85
            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

85
            return /** @scrutinizer ignore-call */ response()->json([]);
Loading history...
86
        }
87
        $query = 'ALL~' . $request->input('query');
88
        $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

88
        $users = /** @scrutinizer ignore-call */ collect($alma->users->search($query, ['limit' => 5]))->map(function ($result) {
Loading history...
89
            return [
90
                'id' => $result->primary_id,
91
                'name' => "{$result->last_name}, {$result->first_name}",
92
            ];
93
        });
94
95
        return response()->json($users);
96
    }
97
98
    /**
99
     * Display the specified resource.
100
     *
101
     * @param User $user
102
     * @return Response
103
     */
104
    public function getShow(User $user)
105
    {
106
        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

106
        return /** @scrutinizer ignore-call */ response()->view('users.show', [
Loading history...
107
            'user' => $user,
108
        ]);
109
    }
110
111
    /**
112
     * Display form for connecting local user to external user.
113
     *
114
     * @param User $user
115
     * @return Response
116
     */
117
    public function connectForm(AlmaUsers $almaUsers, User $user)
118
    {
119
        if (!$almaUsers->hasKey()) {
120
            return back()->with('error', 'Ingen API-nøkkel konfigurert, Bibrex kan ikke snakke med Alma.');
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

120
            return /** @scrutinizer ignore-call */ back()->with('error', 'Ingen API-nøkkel konfigurert, Bibrex kan ikke snakke med Alma.');
Loading history...
121
        }
122
123
        $ident = $user->identifiers()->first();
124
        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

124
        return /** @scrutinizer ignore-call */ response()->view('users.connect', [
Loading history...
125
            'user' => $user,
126
            'user_identifier' => is_null($ident) ? null : $ident->value,
127
        ]);
128
    }
129
130
    /**
131
     * Connect local user to external user.
132
     *
133
     * @param AlmaUsers $almaUsers
134
     * @param Request $request
135
     * @param User $user
136
     * @return Response
137
     */
138
    public function connect(AlmaUsers $almaUsers, Request $request, User $user)
139
    {
140
        if (!$almaUsers->hasKey()) {
141
            return back()->with('error', 'Ingen API-nøkkel konfigurert, Bibrex kan ikke snakke med Alma.');
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

141
            return /** @scrutinizer ignore-call */ back()->with('error', 'Ingen API-nøkkel konfigurert, Bibrex kan ikke snakke med Alma.');
Loading history...
142
        }
143
144
        $identifier = $request->identifier;
145
        if (empty($identifier)) {
146
            return back()->with('error', 'Du må registrere låne-ID.');
147
        }
148
149
        $other = User::fromIdentifier($identifier);
150
        if (!is_null($other) && $other->id != $user->id) {
151
            return back()->with('error', 'Låne-ID-en er allerede koblet til en annen Bibrex-bruker ' .
152
                '(' . $other->name . '). Du kan slå dem sammen fra brukeroversikten.');
153
        }
154
155
        $almaUser = $almaUsers->findById($identifier);
156
157
        if (!$almaUser) {
158
            return back()->with('error', 'Fant ikke noen bruker med identifikator ' . $identifier . ' i Alma 😭 ');
159
        }
160
161
        try {
162
            $almaUsers->updateLocalUserFromAlmaUser($user, $almaUser);
163
        } catch (\RuntimeException $ex) {
164
            return back()->with('error', $ex->getMessage());
165
        }
166
        $user->save();
167
168
        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

168
        return /** @scrutinizer ignore-call */ redirect()->action('UsersController@getShow', $user->id)
Loading history...
169
            ->with('status', 'Bibrex-brukeren ble koblet med Alma-brukeren!');
170
    }
171
172
    /**
173
     * Import user data from Alma.
174
     *
175
     * @param AlmaUsers $almaUsers
176
     * @param User $user
177
     * @return Response
178
     */
179
    public function sync(AlmaUsers $almaUsers, User $user)
180
    {
181
        if (!$almaUsers->hasKey()) {
182
            return back()->with('error', 'Ingen API-nøkkel konfigurert, Bibrex kan ikke snakke med Alma.');
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

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

229
        return /** @scrutinizer ignore-call */ response()->view('users.edit', array(
Loading history...
230
            'user' => $user
231
        ));
232
    }
233
234
    /**
235
     * Update the specified resource in storage.
236
     *
237
     * @param User $user
238
     * @param UserUpsertRequest $request
239
     * @return Response
240
     */
241
    public function upsert(User $user, UserUpsertRequest $request)
242
    {
243
        $isNewUser = !$user->exists;
244
245
        $user->lastname = $request->lastname;
246
        $user->firstname = $request->firstname;
247
        $user->phone = $request->phone;
248
        $user->email = $request->email;
249
        $user->note = $request->note;
250
        $user->lang = $request->lang;
251
        $user->last_loan_at = Carbon::now();
252
        if (!$user->save()) {
253
            throw new \RuntimeException('Ukjent feil under lagring av bruker!');
254
        }
255
256
        $user->setIdentifiers($request->identifiers);
257
258
        if ($isNewUser) {
259
            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

259
            return /** @scrutinizer ignore-call */ redirect()->action('LoansController@getIndex')
Loading history...
260
                ->with('status', 'Brukeren ble opprettet.')
261
                ->with('user', [
262
                    'type' => 'local',
263
                    'id' => $user->id,
264
                    'name' => $user->lastname . ', ' . $user->firstname,
265
                ]);
266
        }
267
268
        return redirect()->action('UsersController@getShow', $user->id)
269
            ->with('status', 'Brukeren ble lagret.');
270
    }
271
272
    /**
273
     * Display form to merge two users.
274
     *
275
     * @param User $user1
276
     * @param User $user2
277
     * @return Response
278
     */
279
    public function getMerge(User $user1, User $user2)
280
    {
281
        $merged = $user1->getMergeData($user2);
282
283
        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

283
        return /** @scrutinizer ignore-call */ response()->view('users.merge', array(
Loading history...
284
            'user1' => $user1,
285
            'user2' => $user2,
286
            'merged' => $merged
287
        ));
288
    }
289
290
    /**
291
     * Merge $user2 into $user1
292
     *
293
     * @param Request $request
294
     * @param User $user1
295
     * @param User $user2
296
     * @return Response
297
     */
298
    public function postMerge(Request $request, User $user1, User $user2)
299
    {
300
        $mergedAttributes = array();
301
        foreach (User::$editableAttributes as $attr) {
302
            $mergedAttributes[$attr] = $request->input($attr);
303
        }
304
305
        $mergedAttributes['identifiers'] = [];
306
        foreach ($request->all() as $key => $val) {
307
            if (preg_match('/identifier_type_([0-9]+)/', $key, $matches)) {
308
                $identifierId = $matches[1];
309
310
                if (empty($request->{"identifier_value_{$identifierId}"})) {
311
                    continue;
312
                }
313
314
                $mergedAttributes['identifiers'][] = [
315
                    'type' => $request->{"identifier_type_{$identifierId}"},
316
                    'value' => $request->{"identifier_value_{$identifierId}"},
317
                ];
318
            }
319
        }
320
321
        $errors = $user1->merge($user2, $mergedAttributes);
322
323
        if (!is_null($errors)) {
324
            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

324
            return /** @scrutinizer ignore-call */ redirect()->action('UsersController@getMerge', array($user1->id, $user2->id))
Loading history...
325
                ->withErrors($errors);
326
        }
327
328
        return redirect()->action('UsersController@getShow', $user1->id)
329
            ->with('status', 'Brukerne ble flettet.');
330
    }
331
332
    /**
333
     * Show the form for creating the specified resource.
334
     *
335
     * @param Request $request
336
     * @return Response
337
     */
338
    public function createForm(Request $request)
339
    {
340
        $user = User::make();
341
342
        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

342
        return /** @scrutinizer ignore-call */ response()->view('users.create', [
Loading history...
343
            'user' => $user,
344
        ]);
345
    }
346
347
    /**
348
     * Show the form for deleting the specified resource.
349
     *
350
     * @param User $user
351
     * @param Request $request
352
     * @return Response
353
     */
354
    public function deleteForm(User $user, Request $request)
355
    {
356
        if ($user->loans()->count()) {
357
            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

357
            return /** @scrutinizer ignore-call */ redirect()->action('UsersController@getShow', $user->id)
Loading history...
358
                ->with('error', 'Kan ikke slette en bruker med aktive lån.');
359
        }
360
361
        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

361
        return /** @scrutinizer ignore-call */ response()->view('users.delete', [
Loading history...
362
            'user' => $user,
363
        ]);
364
    }
365
366
    /**
367
     * Delte the specified resource from storage.
368
     *
369
     * @param User $user
370
     * @param Request $request
371
     * @return Response
372
     */
373
    public function delete(User $user, Request $request)
374
    {
375
        if ($user->loans()->count()) {
376
            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

376
            return /** @scrutinizer ignore-call */ redirect()->action('UsersController@getShow', $user->id)
Loading history...
377
                ->with('error', 'Kan ikke slette en bruker med aktive lån.');
378
        }
379
380
        $user_id = $user->id;
381
        $name = $user->name;
382
383
        $user->delete();
384
        \Log::info(sprintf('Slettet brukeren %s (ID %d)', $name, $user_id));
385
386
        return redirect()->action('UsersController@getIndex')
387
            ->with('status', "Brukeren $name ble slettet (men slapp av, du har ikke drept noen).");
388
    }
389
}
390