Passed
Push — main ( 9c5f48...91d287 )
by Breno
01:50
created

DateTimeInFuture::getNow()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 1
c 0
b 0
f 0
nc 2
nop 0
dl 0
loc 3
rs 10
1
<?php
2
declare(strict_types=1);
3
4
namespace BrenoRoosevelt\Validation\Rules;
5
6
use Attribute;
7
use DateTimeImmutable;
8
use DateTimeInterface;
9
use Throwable;
10
11
#[Attribute(Attribute::TARGET_PROPERTY)]
12
class DateTimeInFuture extends AbstractValidation
13
{
14
    private ?DateTimeInterface $now = null;
15
16
    public function __construct(?string $message = 'The date/time should be in the future')
17
    {
18
        parent::__construct($message);
19
    }
20
21
    public function setNow(DateTimeInterface $now): void
22
    {
23
        $this->now = $now;
24
    }
25
26
    public function getNow(): DateTimeInterface
27
    {
28
        return $this->now instanceof DateTimeInterface ? $this->now : new DateTimeImmutable();
29
    }
30
31
    protected function isValid($input, array $context = []): bool
32
    {
33
        try {
34
            $datetime =
35
                $input instanceof DateTimeInterface ?
36
                    $input :
37
                    new DateTimeImmutable($input);
38
39
            return $datetime > $this->getNow();
40
        } catch (Throwable) {
41
            return false;
42
        }
43
    }
44
}
45