-
Notifications
You must be signed in to change notification settings - Fork 772
/
Date.php
48 lines (39 loc) · 1.3 KB
/
Date.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<?php
/*
* Copyright (c) Alexandre Gomes Gaigalas <alganet@gmail.com>
* SPDX-License-Identifier: MIT
*/
declare(strict_types=1);
namespace Respect\Validation\Rules;
use Respect\Validation\Exceptions\InvalidRuleConstructorException;
use Respect\Validation\Helpers\CanValidateDateTime;
use Respect\Validation\Message\Template;
use Respect\Validation\Result;
use Respect\Validation\Rules\Core\Standard;
use function date;
use function is_scalar;
use function preg_match;
use function strtotime;
#[Template(
'{{name}} must be a valid date in the format {{sample}}',
'{{name}} must not be a valid date in the format {{sample}}',
)]
final class Date extends Standard
{
use CanValidateDateTime;
public function __construct(
private readonly string $format = 'Y-m-d'
) {
if (!preg_match('/^[djSFmMnYy\W]+$/', $format)) {
throw new InvalidRuleConstructorException('"%s" is not a valid date format', $format);
}
}
public function evaluate(mixed $input): Result
{
$parameters = ['sample' => date($this->format, strtotime('2005-12-30'))];
if (!is_scalar($input)) {
return Result::failed($input, $this, $parameters);
}
return new Result($this->isDateTime($this->format, (string) $input), $input, $this, $parameters);
}
}