Passed
Push — master ( c5e5cb...25795c )
by Dan Michael O.
03:38
created

WebhooksController::handleUserUpdate()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 49
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 34
nc 6
nop 2
dl 0
loc 49
rs 8.7537
c 0
b 0
f 0
1
<?php
2
3
namespace App\Http\Controllers;
4
5
use App\User;
6
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...
7
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...
8
use Scriptotek\Alma\Client;
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...
9
10
class WebhooksController extends Controller
11
{
12
    /**
13
     * Alma webhooks router.
14
     *
15
     * @param Client $almaClient
16
     * @param Request $request
17
     * @return Response
18
     */
19
    public function handle(Client $almaClient, Request $request)
20
    {
21
        $secret = config('services.alma.webhook_secret');
0 ignored issues
show
Bug introduced by
The function config 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

21
        $secret = /** @scrutinizer ignore-call */ config('services.alma.webhook_secret');
Loading history...
22
        $eventType = $request->input('action');
23
        $hash = $request->header('X-Exl-Signature');
24
25
        $expectedHash = base64_encode(
26
            hash_hmac('sha256', $request->getContent(), $secret, true)
27
        );
28
29
        if (!hash_equals($hash, $expectedHash)) {
30
            \Log::warning(
31
                "Ignoring Alma '{$eventType}' event due to invalid signature. " .
32
                "Expected '{$expectedHash}', got '{$hash}'."
33
            );
34
35
            return response()->json(['errorMessage' => 'Invalid Signature'], 401);
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

35
            return /** @scrutinizer ignore-call */ response()->json(['errorMessage' => 'Invalid Signature'], 401);
Loading history...
36
        }
37
38
        switch ($eventType) {
39
            case 'USER':
40
                return $this->handleUserUpdate($almaClient, $request);
41
42
            default:
43
                return response('No handler for this webhook event type.', 202);
44
        }
45
    }
46
47
    /**
48
     * Handler for the Alma user webhook.
49
     *
50
     * @param Client $almaClient
51
     * @param Request $request
52
     * @return Response
53
     */
54
    protected function handleUserUpdate(Client $almaClient, Request $request)
55
    {
56
        $data = $request->input('webhook_user');
57
        $primaryId = array_get($data, 'user.primary_id');
0 ignored issues
show
Bug introduced by
The function array_get 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

57
        $primaryId = /** @scrutinizer ignore-call */ array_get($data, 'user.primary_id');
Loading history...
58
59
        if ($data['method'] == 'UPDATE') {
60
            $almaClientUser = \Scriptotek\Alma\Users\User::make($almaClient, $primaryId)
0 ignored issues
show
Bug introduced by
The type Scriptotek\Alma\Users\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...
61
                ->init(json_decode(json_encode($data['user'])));
62
63
            $almaUser = new \App\Alma\User($almaClientUser);
64
65
            $localUser = User::where('alma_primary_id', '=', $primaryId)
66
                ->orWhere('university_id', '=', $almaUser->getUniversityId())
67
                ->first();
68
69
            if (is_null($localUser)) {
70
                \Log::debug('Ignorerer Alma-brukeroppdateringsvarsel for bruker som ikke er i Bibrex.');
71
            } else {
72
                $localUser->mergeFromAlmaResponse($almaUser);
73
                if ($localUser->isDirty()) {
74
                    $localUser->save();
75
                    \Log::info(sprintf(
76
                        'Varsel fra Alma om at brukeren <a href="%s">%s</a> har blitt oppdatert.',
77
                        action('UsersController@getShow', $localUser->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
                        /** @scrutinizer ignore-call */ 
78
                        action('UsersController@getShow', $localUser->id),
Loading history...
78
                        $localUser->name,
79
                        $data['cause'],
80
                        $data['method']
81
                    ));
82
                } else {
83
                    \Log::debug(
84
                        'Varsel fra Alma førte ikke til noen endringer på den tilknyttede Bibrex-brukeren.'
85
                    );
86
                }
87
            }
88
        } elseif ($data['method'] == 'DELETE') {
89
            $localUser = User::where('alma_primary_id', '=', $primaryId)->first();
90
            if (is_null($localUser)) {
91
                \Log::debug('Ignorerer Alma-brukeroppdateringsvarsel for bruker som ikke er i Bibrex.');
92
            } else {
93
                \Log::info(sprintf(
94
                    'Varsel fra Alma om at brukeren <a href="%s">%s</a> har blitt slettet.',
95
                    action('UsersController@getShow', $localUser->id),
96
                    $localUser->name
97
                ));
98
            }
99
        }
100
101
        // Say yo to Alma
102
        return response('Yo!', 200);
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

102
        return /** @scrutinizer ignore-call */ response('Yo!', 200);
Loading history...
103
    }
104
}
105