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

HasExpiration::willBeExpiredAt()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 4
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 8
ccs 5
cts 5
cp 1
crap 2
rs 10
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