CashierWebhookHandledEventListener::handle()   A
last analyzed

Complexity

Conditions 5
Paths 5

Size

Total Lines 19
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 11
c 1
b 0
f 0
nc 5
nop 1
dl 0
loc 19
ccs 0
cts 12
cp 0
crap 30
rs 9.6111
1
<?php
2
3
namespace CashierSubscriptionPause\Listeners;
4
5
use CashierSubscriptionPause\Eloquent\WithPauseCollection;
6
use Laravel\Cashier\Cashier;
7
use Laravel\Cashier\Events\WebhookHandled;
8
9
class CashierWebhookHandledEventListener
10
{
11
    /**
12
     * Deactivate default package listener.
13
     *
14
     * @var bool
15
     */
16
    public static bool $deactivateListener = false;
17
18
    /**
19
     * Webhook types.
20
     *
21
     * See https://stripe.com/docs/api/events/types
22
     *
23
     * @var array
24
     */
25
    public static array $listenTypes = [
26
        'customer.subscription.created',
27
        'customer.subscription.updated',
28
    ];
29
30
    /**
31
     * Deactivate listener.
32
     *
33
     * @return static
34
     */
35
    public static function deactivateListener(bool $inactive = true)
36
    {
37
        static::$deactivateListener = $inactive;
38
39
        return new static;
40
    }
41
42
    /**
43
     * Handle received Stripe webhooks.
44
     *
45
     * @param \Laravel\Cashier\Events\WebhookHandled $event
46
     *
47
     * @psalm-suppress UndefinedDocblockClass
48
     *
49
     * @return void
50
     */
51
    public function handle(WebhookHandled $event)
52
    {
53
        if (static::$deactivateListener) {
54
            return;
55
        }
56
57
        $payload = $event->payload;
58
59
        if (in_array($payload['type'], static::$listenTypes)) {
60
            if ($user = Cashier::findBillable($payload['data']['object']['customer'])) {
61
                $data = $payload['data']['object'];
62
63
                /** @var WithPauseCollection $subscription */
64
                $subscription = $user->subscriptions()
65
                                     ->where('stripe_id', $data['id'])
66
                                     ->first();
67
68
                if ($subscription instanceof WithPauseCollection) {
0 ignored issues
show
introduced by
$subscription is always a sub-type of CashierSubscriptionPause...ent\WithPauseCollection.
Loading history...
69
                    $subscription->syncStripePauseCollection();
70
                }
71
            }
72
        }
73
    }
74
}
75