Verbs

Subscription Started

1<?php ...
2 
3namespace Thunk\Verbs\Examples\Subscriptions\Events;
4 
5use Thunk\Verbs\Event;
6use Thunk\Verbs\Examples\Subscriptions\Models\Subscription;
7use Thunk\Verbs\Examples\Subscriptions\States\GlobalReportState;
8use Thunk\Verbs\Examples\Subscriptions\States\PlanReportState;
9use Thunk\Verbs\Examples\Subscriptions\States\SubscriptionState;
10use Thunk\Verbs\Support\StateCollection;
11 
12class SubscriptionStarted extends Event
13{
14 public int $user_id;
15 
16 public int $plan_id;
17 
18 public ?int $subscription_id = null;
19 
20 public function states(): StateCollection
21 {
22 $this->subscription_id ??= snowflake_id();
23 
24 return new StateCollection([
25 SubscriptionState::load($this->subscription_id),
26 PlanReportState::load($this->plan_id),
27 GlobalReportState::singleton(),
28 ]);
29 }
30 
31 public function validate(SubscriptionState $state)
32 {
33 return ! $state->is_active;
34 }
35 
36 public function apply(SubscriptionState $state)
37 {
38 $state->is_active = true;
39 $state->plan_id = $this->plan_id;
40 }
41 
42 public function handle()
43 {
44 [$subscription_state] = $this->states();
45 
46 Subscription::create([
47 'id' => $subscription_state->id,
48 'user_id' => $this->user_id,
49 'plan_id' => $this->plan_id,
50 'is_active' => true,
51 ]);
52 }
53}