Passed
Push — main ( 9fd9c1...757bec )
by Breno
01:56
created

Format   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 19
Duplicated Lines 0 %

Importance

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

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A isValid() 0 8 3
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 DateTime;
9
use Throwable;
10
11
#[Attribute(Attribute::TARGET_PROPERTY)]
12
class Format extends AbstractRule
13
{
14
    const MESSAGE = 'Invalid date/time format, use %s';
15
16
    public function __construct(private string $format, ?string $message = null)
17
    {
18
        $this->message = $message ?? sprintf(self::MESSAGE, $this->format);
19
        parent::__construct($message);
20
    }
21
22
    public function isValid($input, array $context = []): bool
23
    {
24
        try {
25
            $stringInput = (string) $input;
26
            $d = DateTime::createFromFormat($this->format, $stringInput);
27
            return $d && $d->format($this->format) === $stringInput;
28
        } catch (Throwable) {
29
            return false;
30
        }
31
    }
32
}
33