Passed
Push — main ( 91d287...fcaac4 )
by Breno
02:02
created

DateTimeLessThanOther   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 20
Duplicated Lines 0 %

Importance

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

2 Methods

Rating   Name   Duplication   Size   Complexity  
A isValid() 0 12 4
A __construct() 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 DateTimeLessThanOther extends AbstractValidation
13
{
14
    public function __construct(private string $other, ?string $message = null)
15
    {
16
        parent::__construct($message ?? sprintf('The date/time should be less than %s', $this->other));
17
    }
18
19
    protected function isValid($input, array $context = []): bool
20
    {
21
        try {
22
            $datetime =
23
                $input instanceof DateTimeInterface ?
24
                    $input :
25
                    new DateTimeImmutable($input);
26
27
            return array_key_exists($this->other, $context)
28
                && $datetime < (new DateTimeImmutable($context[$this->other]));
29
        } catch (Throwable) {
30
            return false;
31
        }
32
    }
33
}
34