Passed
Push — main ( e492c9...632610 )
by Yaroslav
02:58
created

HasExpiration   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 14
c 1
b 0
f 0
dl 0
loc 44
ccs 20
cts 20
cp 1
rs 10
wmc 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
A initializeHasExpiration() 0 4 2
A expiresAt() 0 3 1
A scopeExpired() 0 3 1
A expired() 0 3 1
A expirationKeyName() 0 3 2
A scopeWillBeExpiredAt() 0 5 1
A willBeExpiredAt() 0 8 2
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
The property casts does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
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