Completed
Pull Request — master (#5)
by Brent
102:02
created

DateBetween::excludeBoundaries()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace Spatie\ValidationRules\Rules;
4
5
use Carbon\Carbon;
6
use Spatie\ValidationRules\Exceptions\InvalidDate;
7
use Spatie\ValidationRules\IsDateRule;
8
use Illuminate\Contracts\Validation\Rule;
9
10
class DateBetween implements Rule
11
{
12
    use IsDateRule;
13
14
    /** @var \Carbon\Carbon */
15
    protected $start;
16
17
    /** @var \Carbon\Carbon */
18
    protected $end;
19
20
    /** @var bool */
21
    protected $orEquals = true;
22
23
    /** @var string|null */
24
    protected $message = null;
25
26
    public function __construct(Carbon $start, Carbon $end, string $format = 'Y-m-d')
27
    {
28
        $this->start = $start->copy();
29
30
        $this->end = $end->copy();
31
32
        $this->format = $format;
33
    }
34
35
    public function includeBoundaries(): DateBetween
36
    {
37
        $this->orEquals = true;
38
39
        return $this;
40
    }
41
42
    public function excludeBoundaries(): DateBetween
43
    {
44
        $this->orEquals = false;
45
46
        return $this;
47
    }
48
49
    public function withoutTime(): DateBetween
50
    {
51
        $this->start->startOfDay();
52
53
        $this->end->endOfDay();
54
55
        return $this;
56
    }
57
58
    public function passes($attribute, $value): bool
59
    {
60
        try {
61
            $date = $this->createDate($value);
62
63
            return $date->between($this->start, $this->end, $this->orEquals);
64
        } catch (InvalidDate $exception) {
65
            $this->message = $exception->getMessage();
66
67
            return false;
68
        }
69
    }
70
71
    public function message(): string
72
    {
73
        return $this->message ?? __('validationRules.date_between');
74
    }
75
}
76