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

DateTimeCompareWith::isValid()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 13
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 10
c 1
b 0
f 0
nc 8
nop 2
dl 0
loc 13
rs 9.9332
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 DateTimeCompareWith 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 $other,
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 = fn() => new DateTimeImmutable($context[$this->other]);
35
            $datetime =
36
                $input instanceof DateTimeInterface ?
37
                    $input :
38
                    new DateTimeImmutable($input);
39
40
            return array_key_exists($this->other, $context)
41
                && $this->compare($datetime, $this->operator, $other);
42
        } catch (Throwable) {
43
            return false;
44
        }
45
    }
46
47
    public function translatedMessage(): ?string
48
    {
49
        $translatedOperator = Translator::translate($this->operator);
50
        return Translator::translate(self::MESSAGE, $translatedOperator, $this->other);
51
    }
52
}
53