Completed
Push — master ( e1543f...d374d7 )
by Adolfo
20s queued 10s
created

Subscription::plan()   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
42
        return $q->where('start_at', '<=', $date)
43
            ->where(function ($query) use ($date) {
44
                $query->where('end_at', '>=', $date)->orWhereNull('end_at');
45
            });
46
    }
47
48
    public function getDaysLeft(): ?int
49
    {
50
        if ($this->isPerpetual()) {
51
            return null;
52
        }
53
54
        return now()->diffInDays($this->end_at);
55
    }
56
57
    public function isPerpetual(): bool
58
    {
59
        return $this->end_at == null;
60
    }
61
62
    public function getElapsedDays(): int
63
    {
64
        return now()->diffInDays($this->start_at);
65
    }
66
67
    public function getExpirationDate(): ?Carbon
68
    {
69
        return $this->end_at;
70
    }
71
72
    public function getStartDate(): Carbon
73
    {
74
        return $this->start_at;
75
    }
76
77
    public function subscriber()
78
    {
79
        return $this->morphTo();
80
    }
81
82
    public function plan(): BelongsTo
83
    {
84
        return $this->belongsTo(config('subscriptions.entities.plan'));
85
    }
86
}
87