Passed
Push — main ( 9fd9c1...757bec )
by Breno
01:56
created

LessThan::datetime()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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