Passed
Branch main (c6b4b7)
by Breno
02:14
created

DateTimeFormat::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 4
rs 10
1
<?php
2
declare(strict_types=1);
3
4
namespace BrenoRoosevelt\Validation\Rules;
5
6
use Attribute;
7
use DateTime;
8
use Throwable;
9
10
#[Attribute(Attribute::TARGET_PROPERTY)]
11
class DateTimeFormat extends AbstractValidation
12
{
13
    const MESSAGE = 'Formato de data e/ou hora inválido, use %s';
14
15
    public function __construct(private string $format, ?string $message = null)
16
    {
17
        $this->message = $message ?? sprintf(self::MESSAGE, $this->format);
18
        parent::__construct($message);
19
    }
20
21
    protected function isValid($input, array $context = []): bool
22
    {
23
        try {
24
            $stringInput = (string) $input;
25
            $d = DateTime::createFromFormat($this->format, $stringInput);
26
            return $d && $d->format($this->format) === $stringInput;
27
        } catch (Throwable) {
28
            return false;
29
        }
30
    }
31
}
32