Passed
Push — main ( c4e78f...e492c9 )
by Yaroslav
14:10
created

HasExpiration   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Test Coverage

Coverage 95%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 14
c 1
b 0
f 0
dl 0
loc 44
ccs 19
cts 20
cp 0.95
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 willBeExpiredAt() 0 8 2
A expirationKeyName() 0 3 2
A scopeWillBeExpiredAt() 0 5 1
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 5
    public function initializeHasExpiration()
12
    {
13 5
        if (!array_key_exists($this->expirationKeyName(), $this->casts)) {
14 5
            $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 5
    public function expirationKeyName(): string
19
    {
20 5
        return property_exists($this, 'expirationKeyName') ? $this->expirationKeyName : 'expire_at';
21
    }
22
23 2
    public function expiresAt(): ?\DateTimeInterface
24
    {
25 2
        return $this->{$this->expirationKeyName()};
26
    }
27
28 2
    public function expired(): bool
29
    {
30 2
        return $this->willBeExpiredAt(Carbon::now());
31
    }
32
33 2
    public function willBeExpiredAt(\DateTimeInterface $dateTime): bool
34
    {
35 2
        $expiresAt = $this->expiresAt();
36 2
        if (is_null($expiresAt)) {
37
            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 3
    public function scopeWillBeExpiredAt(Builder $query, \DateTimeInterface $dateTime): void
49
    {
50 3
        $query->where(function (Builder $query) use ($dateTime) {
51 3
            $query->whereNotNull($this->expirationKeyName());
52 3
            $query->where($this->expirationKeyName(), '<', $dateTime);
53 3
        });
54
    }
55
}
56