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

DateTimeFormat::translatedMessage()   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
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
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\Translation\Translator;
9
use DateTime;
10
use Throwable;
11
12
#[Attribute(Attribute::TARGET_PROPERTY)]
13
class DateTimeFormat extends AbstractRule
14
{
15
    const MESSAGE = 'Invalid date/time format, use %s';
16
17
    public function __construct(
18
        private string $format,
19
        ?string $message = null,
20
        ?int $stopOnFailure = null,
21
        ?int $priority = null
22
    ) {
23
        parent::__construct($message, $stopOnFailure, $priority);
24
    }
25
26
    public function isValid($input, array $context = []): bool
27
    {
28
        try {
29
            $stringInput = (string) $input;
30
            $d = DateTime::createFromFormat($this->format, $stringInput);
31
            return $d && $d->format($this->format) === $stringInput;
32
        } catch (Throwable) {
33
            return false;
34
        }
35
    }
36
37
    public function translatedMessage(): ?string
38
    {
39
        return Translator::translate(self::MESSAGE, $this->format);
40
    }
41
}
42