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

DateTimeFormat   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 19
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 11
c 1
b 0
f 0
dl 0
loc 19
rs 10
wmc 4

2 Methods

Rating   Name   Duplication   Size   Complexity  
A isValid() 0 8 3
A __construct() 0 4 1
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