1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\EmailCampaigns\Models; |
4
|
|
|
|
5
|
|
|
use Illuminate\Database\Eloquent\Model; |
6
|
|
|
use Illuminate\Database\Eloquent\Relations\HasMany; |
7
|
|
|
use Spatie\EmailCampaigns\Enums\SubscriptionStatus; |
8
|
|
|
use Illuminate\Database\Eloquent\Relations\BelongsToMany; |
9
|
|
|
|
10
|
|
|
class EmailList extends Model |
11
|
|
|
{ |
12
|
|
|
public $guarded = []; |
13
|
|
|
|
14
|
|
|
public function subscribers(): BelongsToMany |
15
|
|
|
{ |
16
|
|
|
return $this->allSubscribers()->wherePivot('status', SubscriptionStatus::SUBSCRIBED); |
17
|
|
|
} |
18
|
|
|
|
19
|
|
|
public function allSubscribers(): BelongsToMany |
20
|
|
|
{ |
21
|
|
|
return $this->belongsToMany(Subscriber::class, 'email_list_subscriptions', 'email_list_id', 'email_list_subscriber_id'); |
22
|
|
|
} |
23
|
|
|
|
24
|
|
|
public function subscriptions(): HasMany |
25
|
|
|
{ |
26
|
|
|
return $this->hasMany(Subscription::class)->where('status', SubscriptionStatus::SUBSCRIBED); |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
public function allSubscriptions(): HasMany |
30
|
|
|
{ |
31
|
|
|
return $this->hasMany(Subscription::class); |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
public function campaigns(): HasMany |
35
|
|
|
{ |
36
|
|
|
return $this->hasMany(Campaign::class); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
public function subscribe(string $email): Subscription |
40
|
|
|
{ |
41
|
|
|
/** @var \Spatie\EmailCampaigns\Models\Subscriber $subscriber */ |
42
|
|
|
$subscriber = Subscriber::firstOrCreate([ |
43
|
|
|
'email' => $email, |
44
|
|
|
]); |
45
|
|
|
|
46
|
|
|
return $subscriber->subscribeTo($this); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
public function isSubscribed(string $email): bool |
50
|
|
|
{ |
51
|
|
|
if (! $subscriber = Subscriber::findForEmail($email)) { |
52
|
|
|
return false; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
if (! $subscription = $this->getSubscription($subscriber)) { |
56
|
|
|
return false; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
return $subscription->status === SubscriptionStatus::SUBSCRIBED; |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
public function getSubscription(Subscriber $subscriber): ?Subscription |
63
|
|
|
{ |
64
|
|
|
return Subscription::query() |
65
|
|
|
->where('email_list_id', $this->id) |
66
|
|
|
->where('email_list_subscriber_id', $subscriber->id) |
67
|
|
|
->first(); |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
public function unsubscribe(string $email): bool |
71
|
|
|
{ |
72
|
|
|
if (! $subscriber = Subscriber::findForEmail($email)) { |
73
|
|
|
return false; |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
if (! $subscription = $this->getSubscription($subscriber)) { |
77
|
|
|
return false; |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
$subscription->markAsUnsubscribed(); |
81
|
|
|
|
82
|
|
|
return true; |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
|