1 | <?php |
||
2 | |||
3 | namespace ThinKit\Models\Expiration; |
||
4 | |||
5 | use Carbon\Carbon; |
||
6 | |||
7 | use Illuminate\Database\Eloquent\Builder; |
||
8 | |||
9 | trait HasExpiration |
||
10 | { |
||
11 | 9 | public function initializeHasExpiration() |
|
12 | { |
||
13 | 9 | if (!array_key_exists($this->expirationKeyName(), $this->casts)) { |
|
14 | 9 | $this->casts[$this->expirationKeyName()] = 'datetime'; |
|
0 ignored issues
–
show
Bug
Best Practice
introduced
by
![]() |
|||
15 | } |
||
16 | } |
||
17 | |||
18 | 9 | public function expirationKeyName(): string |
|
19 | { |
||
20 | 9 | return property_exists($this, 'expirationKeyName') ? $this->expirationKeyName : 'expire_at'; |
|
21 | } |
||
22 | |||
23 | 3 | public function expiresAt(): ?\DateTimeInterface |
|
24 | { |
||
25 | 3 | return $this->{$this->expirationKeyName()}; |
|
26 | } |
||
27 | |||
28 | 3 | public function expired(): bool |
|
29 | { |
||
30 | 3 | return $this->willBeExpiredAt(Carbon::now()); |
|
31 | } |
||
32 | |||
33 | 3 | public function willBeExpiredAt(\DateTimeInterface $dateTime): bool |
|
34 | { |
||
35 | 3 | $expiresAt = $this->expiresAt(); |
|
36 | 3 | if (is_null($expiresAt)) { |
|
37 | 1 | return false; |
|
38 | } |
||
39 | |||
40 | 2 | return Carbon::instance($dateTime)->greaterThan($expiresAt); |
|
41 | } |
||
42 | |||
43 | 1 | public function scopeExpired(Builder $query): void |
|
44 | { |
||
45 | 1 | $this->scopeWillBeExpiredAt($query, Carbon::now()); |
|
46 | } |
||
47 | |||
48 | 6 | public function scopeWillBeExpiredAt(Builder $query, \DateTimeInterface $dateTime): void |
|
49 | { |
||
50 | 6 | $query->where(function (Builder $query) use ($dateTime) { |
|
51 | 6 | $query->whereNotNull($this->expirationKeyName()); |
|
52 | 6 | $query->where($this->expirationKeyName(), '<', $dateTime); |
|
53 | 6 | }); |
|
54 | } |
||
55 | } |
||
56 |