SendWebhook   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 78
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 3

Importance

Changes 0
Metric Value
wmc 9
lcom 0
cbo 3
dl 0
loc 78
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A sendViaHttp() 0 14 4
A logWebhook() 0 31 4
A sendViaQueue() 0 6 1
1
<?php
2
3
namespace Bencoderus\Webhook\Traits;
4
5
use Bencoderus\Webhook\Exceptions\WebhookException;
6
use Bencoderus\Webhook\Http\Clients\HttpClient;
7
use Bencoderus\Webhook\Jobs\OutgoingWebhookJob;
8
use Bencoderus\Webhook\Models\WebhookLog;
9
use Exception;
10
use Illuminate\Support\Facades\Schema;
11
12
trait SendWebhook
13
{
14
    /**
15
     * Send Webhook synchronously.
16
     *
17
     * @param array $data
18
     *
19
     * @return bool
20
     */
21
    private function sendViaHttp(array $data): bool
22
    {
23
        try {
24
            $response = (new HttpClient())->withHeaders($data['signature'])->post($data['url'], $data['payload']);
25
26
            $this->logWebhook($response, $data);
27
28
            return $response->statusCode() >= 200 && $response->statusCode() <= 205;
29
        } catch (Exception $exception) {
30
            if ($exception instanceof WebhookException) {
31
                return false;
32
            }
33
        }
34
    }
35
36
    /**
37
     * Generate a webhook log.
38
     *
39
     * @param $response
40
     * @param array $data
41
     *
42
     * @return void
43
     */
44
    private function logWebhook($response, array $data)
45
    {
46
        if (! Schema::hasTable('webhook_logs')) {
47
            return;
48
        }
49
50
        if (! config('webhook.log_webhook')) {
51
            return;
52
        }
53
54
        $data['response'] = $response->json();
55
        $data['response_status_code'] = $response->statusCode();
56
57
        if (! $webhook = WebhookLog::where('uuid', $data['webhook_id'])->first()) {
58
            return WebhookLog::create([
59
                'uuid' => $data['webhook_id'],
60
                'url' => $data['url'],
61
                'response_status_code' => $data['response_status_code'],
62
                'response' => $data['response'],
63
                'payload' => $data['payload'],
64
            ]);
65
        }
66
67
        $webhook->update([
68
            'response_status_code' => $data['response_status_code'],
69
            'response' => $data['response'],
70
            'attempts' => $webhook->attempts + 1,
71
        ]);
72
73
        return $webhook;
74
    }
75
76
    /**
77
     * Send using a Queue.
78
     *
79
     * @param array $data
80
     *
81
     * @return bool
82
     */
83
    private function sendViaQueue(array $data): bool
84
    {
85
        OutgoingWebhookJob::dispatch($data);
86
87
        return true;
88
    }
89
}
90