Completed
Push — master ( 2c4859...5ed06f )
by Adolfo
14s queued 11s
created

Subscription::scopeUnfinished()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace Sagitarius29\LaravelSubscriptions\Entities;
4
5
use Carbon\Carbon;
6
use Illuminate\Database\Eloquent\Builder;
7
use Illuminate\Database\Eloquent\Model;
8
use Illuminate\Database\Eloquent\Relations\BelongsTo;
9
use Sagitarius29\LaravelSubscriptions\Contracts\PlanContract;
10
use Sagitarius29\LaravelSubscriptions\Contracts\SubscriptionContact;
11
use Sagitarius29\LaravelSubscriptions\Exceptions\SubscriptionErrorException;
12
13
class Subscription extends Model implements SubscriptionContact
14
{
15
    protected $table = 'subscriptions';
16
17
    protected $fillable = [
18
        'plan_id', 'start_at', 'end_at',
19
    ];
20
21
    protected $dates = [
22
        'start_at', 'end_at',
23
    ];
24
25
    public static function make(PlanContract $plan, Carbon $start_at, Carbon $end_at = null): Model
26
    {
27
        if (! $plan instanceof Model) {
28
            throw new SubscriptionErrorException('$plan must be '.Model::class);
29
        }
30
31
        return new self([
32
            'plan_id' => $plan->id,
33
            'start_at' => $start_at,
34
            'end_at' => $end_at,
35
        ]);
36
    }
37
38
    public function scopeCurrent(Builder $q)
39
    {
40
        $today = now();
41
42
        return $q->where('start_at', '<=', $today)
43
            ->where(function ($query) use ($today) {
44
                $query->where('end_at', '>=', $today)->orWhereNull('end_at');
45
            });
46
    }
47
48
    public function scopeUnfinished(Builder $q)
49
    {
50
        $today = now();
51
52
        return $q->where(function ($query) use ($today) {
53
            $query->where('end_at', '>=', $today)->orWhereNull('end_at');
54
        });
55
    }
56
57
    public function getDaysLeft(): ?int
58
    {
59
        if ($this->isPerpetual()) {
60
            return null;
61
        }
62
63
        return now()->diffInDays($this->end_at);
64
    }
65
66
    public function isPerpetual(): bool
67
    {
68
        return $this->end_at == null;
69
    }
70
71
    public function getElapsedDays(): int
72
    {
73
        return now()->diffInDays($this->start_at);
74
    }
75
76
    public function getExpirationDate(): ?Carbon
77
    {
78
        return $this->end_at;
79
    }
80
81
    public function getStartDate(): Carbon
82
    {
83
        return $this->start_at;
84
    }
85
86
    public function subscriber()
87
    {
88
        return $this->morphTo();
89
    }
90
91
    public function plan(): BelongsTo
92
    {
93
        return $this->belongsTo(config('subscriptions.entities.plan'));
94
    }
95
}
96