Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
0.00% |
0 / 32 |
|
0.00% |
0 / 4 |
CRAP | |
0.00% |
0 / 1 |
SubscriptionObserver | |
0.00% |
0 / 32 |
|
0.00% |
0 / 4 |
156 | |
0.00% |
0 / 1 |
created | |
0.00% |
0 / 3 |
|
0.00% |
0 / 1 |
6 | |||
updated | |
0.00% |
0 / 3 |
|
0.00% |
0 / 1 |
6 | |||
canSync | |
0.00% |
0 / 4 |
|
0.00% |
0 / 1 |
12 | |||
checkUserPersonas | |
0.00% |
0 / 22 |
|
0.00% |
0 / 1 |
30 |
1 | <?php |
2 | |
3 | namespace App\Observers; |
4 | |
5 | use App\Http\Models\Auth\User; |
6 | use App\Http\Models\Subscription; |
7 | use App\Http\Models\UserPersona; |
8 | use App\Jobs\ProcessSubscriptionAsyncJob; |
9 | use App\Traits\SubscriptionTrait; |
10 | |
11 | class SubscriptionObserver |
12 | { |
13 | use SubscriptionTrait; |
14 | |
15 | public function created(Subscription $subscription): void |
16 | { |
17 | if ($this->canSync($subscription->user_id)) { |
18 | ProcessSubscriptionAsyncJob::dispatch($subscription); |
19 | } |
20 | |
21 | $this->checkUserPersonas($subscription); |
22 | } |
23 | |
24 | public function updated(Subscription $subscription): void |
25 | { |
26 | if ($this->canSync($subscription->user_id)) { |
27 | ProcessSubscriptionAsyncJob::dispatch($subscription); |
28 | } |
29 | |
30 | $this->checkUserPersonas($subscription); |
31 | } |
32 | |
33 | private function canSync(string $userId) |
34 | { |
35 | $user = User::find($userId); |
36 | |
37 | if (!$user) { |
38 | return false; |
39 | } |
40 | |
41 | return $user->status !== 'Deactivated' && empty($user->deleted_at); |
42 | } |
43 | |
44 | private function checkUserPersonas(Subscription $subscription) |
45 | { |
46 | $user = User::find($subscription->user_id); |
47 | |
48 | if (!$user) { |
49 | return; |
50 | } |
51 | |
52 | $personaCount = UserPersona::withoutGlobalScopes()->where('user_id', $user->_id)->count(); |
53 | $plan = $this->getCurrentPlan($user); |
54 | |
55 | if ($plan->user_persona_available >= $personaCount) { |
56 | UserPersona::withoutGlobalScopes()->where('user_id', $user->_id) |
57 | ->update(['disabled' => false]); |
58 | return; |
59 | } |
60 | |
61 | $defaultUserPersona = UserPersona::withoutGlobalScopes()->where('user_id', $user->_id) |
62 | ->where('is_default', true) |
63 | ->first(); |
64 | |
65 | $validUserPersonas = UserPersona::withoutGlobalScopes()->where('user_id', $user->_id) |
66 | ->orderBy('created_at', 'asc') |
67 | ->limit($plan->user_persona_available) |
68 | ->get(); |
69 | |
70 | if ($defaultUserPersona && !$validUserPersonas->contains($defaultUserPersona)) { |
71 | $validUserPersonas->pop(); |
72 | $validUserPersonas->push($defaultUserPersona); |
73 | } |
74 | |
75 | UserPersona::withoutGlobalScopes()->where('user_id', $user->_id) |
76 | ->whereNotIn('_id', $validUserPersonas->pluck('_id')) |
77 | ->update(['disabled' => true]); |
78 | } |
79 | } |