Newer
Older
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
<?php
declare(strict_types=1);
/**
* Class SoundbiteModel Model for podcasts_soundbites table in database
*
* @copyright 2020 Ad Aures
* @license https://www.gnu.org/licenses/agpl-3.0.en.html AGPL3
* @link https://castopod.org/
*/
namespace Modules\PremiumPodcasts\Models;
use CodeIgniter\Model;
use Modules\PremiumPodcasts\Entities\Subscription;
class SubscriptionModel extends Model
{
/**
* @var string
*/
protected $table = 'subscriptions';
/**
* @var string
*/
protected $primaryKey = 'id';
/**
* @var string[]
*/
protected $allowedFields = [
'id',
'podcast_id',
'email',
'token',
'status',
'status_message',
'expires_at',
'created_by',
'updated_by',
];
protected $returnType = Subscription::class;
/**
* @var bool
*/
protected $useSoftDeletes = false;
/**
* @var bool
*/
protected $useTimestamps = true;
/**
* @var string[]
*/
protected $afterUpdate = ['clearCache'];
/**
* @var string[]
*/
protected $beforeDelete = ['clearCache'];
public function getSubscriptionById(int $subscriptionId): ?Subscription
{
$cacheName = "subscription#{$subscriptionId}";
if (! ($found = cache($cacheName))) {
$found = $this->find($subscriptionId);
cache()
->save($cacheName, $found, DECADE);
}
return $found;
}
/**
* @return Subscription[]
*/
public function getPodcastSubscriptions(int $podcastId): array
{
$cacheName = "podcast#{$podcastId}_subscriptions";
if (! ($found = cache($cacheName))) {
$found = $this->where('podcast_id', $podcastId)
->findAll();
cache()
->save($cacheName, $found, DECADE);
}
return $found;
}
/**
* @param string $token plain-text token to be encrypted and matched against encrypted tokens in database
*/
public function validateSubscription(int|string $podcastIdOrHandle, string $token): ?Subscription
{
$subscriptionModel = $this;
if (is_int($podcastIdOrHandle)) {
$this->where('id', $podcastIdOrHandle);
} else {
$this->select('subscriptions.*')
->where('handle', $podcastIdOrHandle)
->join('podcasts', 'podcasts.id = subscriptions.podcast_id');
}
return $subscriptionModel
->where([
'token' => hash('sha256', $token),
'status' => 'active',
'expires_at' => null,
])
->orWhere('`expires_at` > UTC_TIMESTAMP()', null, false)
->first();
}
/**
* @param mixed[] $data
*
* @return mixed[]
*/
protected function clearCache(array $data): array
{
$subscription = (new self())->find(is_array($data['id']) ? $data['id'][0] : $data['id']);
cache()
->delete("subscription#{$subscription->id}");
cache()
->delete("podcast#{$subscription->podcast_id}_subscriptions");
return $data;
}
}