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

DateTimeInPast::getNow()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 1
c 1
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 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