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

GreaterThanAnother   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 20
Duplicated Lines 0 %

Importance

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

2 Methods

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