Passed
Push — main ( c66d90...1ecce0 )
by Breno
01:44
created

DateTimeInFuture   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 27
Duplicated Lines 0 %

Importance

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

3 Methods

Rating   Name   Duplication   Size   Complexity  
A isValid() 0 11 3
A __construct() 0 4 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;
15
16
    public function __construct(?string $message = 'The date/time should be in the future')
17
    {
18
        $this->setNow(new DateTimeImmutable());
19
        parent::__construct($message);
20
    }
21
22
    public function setNow(DateTimeInterface $now): void
23
    {
24
        $this->now = $now;
25
    }
26
27
    protected function isValid($input, array $context = []): bool
28
    {
29
        try {
30
            $datetime =
31
                $input instanceof DateTimeInterface ?
32
                    $input :
33
                    new DateTimeImmutable($input);
34
35
            return $datetime < $this->now;
36
        } catch (Throwable) {
37
            return false;
38
        }
39
    }
40
}
41