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

DateTimeInPast   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 32
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 15
c 2
b 0
f 0
dl 0
loc 32
rs 10
wmc 7

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A setNow() 0 3 1
A isValid() 0 11 3
A getNow() 0 3 2
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 DateTimeInPast extends AbstractValidation
13
{
14
    private ?DateTimeInterface $now = null;
15
16
    public function __construct(?string $message = 'The date/time should be in the past')
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
    public function getNow(): DateTimeInterface
28
    {
29
        return $this->now instanceof DateTimeInterface ? $this->now : new DateTimeImmutable();
30
    }
31
32
    protected function isValid($input, array $context = []): bool
33
    {
34
        try {
35
            $datetime =
36
                $input instanceof DateTimeInterface ?
37
                    $input :
38
                    new DateTimeImmutable($input);
39
40
            return $datetime < $this->getNow();
41
        } catch (Throwable) {
42
            return false;
43
        }
44
    }
45
}
46