Completed
Push — develop ( f351ab...661889 )
by Adolfo
01:14
created

Subscription::getElapsedDays()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace Sagitarius29\LaravelSubscriptions\Entities;
4
5
use Carbon\Carbon;
6
use Illuminate\Database\Eloquent\Model;
7
use Illuminate\Database\Eloquent\Builder;
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
        $date = now();
41
        return $q->where('start_at', '<=', $date)
42
            ->where(function ($query) use ($date) {
43
                $query->where('end_at', '>=', $date)->orWhereNull('end_at');
44
            });
45
    }
46
47
    public function getDaysLeft(): ?int
48
    {
49
        if ($this->isPerpetual()) {
50
            return null;
51
        }
52
53
        return now()->diffInDays($this->end_at);
54
    }
55
56
    public function isPerpetual(): bool
57
    {
58
        return $this->end_at == null;
59
    }
60
61
    public function getElapsedDays(): int
62
    {
63
        return now()->diffInDays($this->start_at);
64
    }
65
66
    public function getExpirationDate(): ?Carbon
67
    {
68
        return $this->end_at;
69
    }
70
71
    public function getStartDate(): Carbon
72
    {
73
        return $this->start_at;
74
    }
75
76
    public function subscriber()
77
    {
78
        return $this->morphTo();
79
    }
80
81
    public function plan(): BelongsTo
82
    {
83
        return $this->belongsTo(config('subscriptions.entities.plan'));
84
    }
85
}
86