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

DateTimeInFuture   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 31
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 14
c 1
b 0
f 0
dl 0
loc 31
rs 10
wmc 7

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getNow() 0 3 2
A isValid() 0 11 3
A __construct() 0 3 1
A setNow() 0 3 1
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