-
-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathHasPlanSubscriptions.php
More file actions
executable file
·95 lines (79 loc) · 2.69 KB
/
Copy pathHasPlanSubscriptions.php
File metadata and controls
executable file
·95 lines (79 loc) · 2.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
<?php
declare(strict_types=1);
namespace Laravelcm\Subscriptions\Traits;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Laravelcm\Subscriptions\Models\Plan;
use Laravelcm\Subscriptions\Models\Subscription;
use Laravelcm\Subscriptions\Services\Period;
trait HasPlanSubscriptions
{
protected static function bootHasSubscriptions(): void
{
static::deleted(function ($plan): void {
$plan->subscriptions()->delete();
});
}
/**
* The subscriber may have many plan subscriptions.
*/
public function planSubscriptions(): MorphMany
{
return $this->morphMany(
related: config('laravel-subscriptions.models.subscription'),
name: 'subscriber',
type: 'subscriber_type',
id: 'subscriber_id'
);
}
public function activePlanSubscriptions(): Collection
{
return $this->planSubscriptions->reject->inactive();
}
public function planSubscription(string $subscriptionSlug): ?Subscription
{
return $this->planSubscriptions()->where('slug', 'like', '%' . $subscriptionSlug . '%')->first();
}
public function subscribedPlans(): Collection
{
$planIds = $this->planSubscriptions->reject
->inactive()
->pluck('plan_id')
->unique();
$model = config('laravel-subscriptions.models.plan');
return $model::whereIn('id', $planIds)->get();
}
public function subscribedTo(int $planId): bool
{
$subscription = $this->planSubscriptions()
->where('plan_id', $planId)
->first();
return $subscription && $subscription->active();
}
public function newPlanSubscription(string $subscription, Plan $plan, ?Carbon $startDate = null): Subscription
{
$trial = new Period(
interval: $plan->trial_interval,
count: $plan->trial_period,
start: $startDate ?? Carbon::now()
);
$period = new Period(
interval: $plan->invoice_interval,
count: $plan->invoice_period,
start: $trial->getEndDate()
);
/** @var Subscription $subscription */
$subscription = $this->planSubscriptions()->create([
'name' => $subscription,
'plan_id' => $plan->getKey(),
'trial_ends_at' => $trial->getEndDate(),
'starts_at' => $period->getStartDate(),
'ends_at' => $period->getEndDate(),
]);
if ($plan->isFree()) {
$subscription->update(['ends_at' => null, 'trial_ends_at' => null]);
}
return $subscription;
}
}