WebhookReceivedController::determineJobClass()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Transmissor\Http\Controllers;
4
5
use Transmissor\Models\User;
6
use Illuminate\Http\Request;
7
use Transmissor\Exceptions\WebhookException;
8
9
class WebhookReceivedController extends Controller
10
{
11
12
    public function __invoke(Request $request, User $user)
13
    {
14
        $signature = $request->header('Transmissor-Signature');
15
16
        if (! $signature) {
17
            throw WebhookException::missingSignature();
18
        }
19
20
        if (! $user->webhook) {
21
            throw WebhookException::signingSecretNotSet();
22
        }
23
24
        $computedSignature = hash_hmac('sha256', $request->getContent(), decrypt($user->webhook));
25
26
        if (! hash_equals($signature, $computedSignature)) {
27
            throw WebhookException::invalidSignature($signature);
28
        }
29
30
        $eventPayload = json_decode($request->getContent());
31
32
        if (! isset($eventPayload->type)) {
33
            throw WebhookException::missingType();
34
        }
35
36
        $jobClass = $this->determineJobClass($eventPayload->type);
37
38
        if (! class_exists($jobClass)) {
39
            throw WebhookException::unrecognizedType($eventPayload->type);
40
        }
41
42
        dispatch(new $jobClass($eventPayload, $user));
43
44
        return response('User will be notified. Thank you Transmissor!');
45
    }
46
47
    protected function determineJobClass(string $type): string
48
    {
49
        return '\\Transmissor\\Jobs\\Webhook\\'.ucfirst($type);
50
    }
51
}
52