Passed
Push — main ( 11848c...4790f2 )
by Breno
02:08
created

DateTimeCompare::isValid()   A

Complexity

Conditions 3
Paths 6

Size

Total Lines 12
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 9
c 1
b 0
f 0
nc 6
nop 2
dl 0
loc 12
rs 9.9666
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 BrenoRoosevelt\Validation\Comparator;
9
use BrenoRoosevelt\Validation\Translation\Translator;
10
use DateTimeImmutable;
11
use DateTimeInterface;
12
use Throwable;
13
14
#[Attribute(Attribute::TARGET_PROPERTY)]
15
class DateTimeCompare extends AbstractRule
16
{
17
    const MESSAGE = 'The date/time should be %s `%s`';
18
19
    use Comparator;
20
21
    public function __construct(
22
        private string $operator,
23
        private string $datetime,
24
        ?string $message = null,
25
        ?int $stopOnFailure = null,
26
        ?int $priority = null
27
    ) {
28
        parent::__construct($message, $stopOnFailure, $priority);
29
    }
30
31
    public function isValid($input, array $context = []): bool
32
    {
33
        try {
34
            $other = new DateTimeImmutable($this->datetime);
35
            $datetime =
36
                $input instanceof DateTimeInterface ?
37
                    $input :
38
                    new DateTimeImmutable($input);
39
40
            return $this->compare($datetime, $this->operator, $other);
41
        } catch (Throwable) {
42
            return false;
43
        }
44
    }
45
46
    public function translatedMessage(): ?string
47
    {
48
        $translatedOperator = Translator::translate($this->operator);
49
        return Translator::translate(self::MESSAGE, $translatedOperator, $this->datetime);
50
    }
51
}
52