Skip to content

Commit

Permalink
Update the validation engine of the "DateTime" rule
Browse files Browse the repository at this point in the history
Signed-off-by: Henrique Moody <[email protected]>
  • Loading branch information
henriquemoody committed Mar 24, 2024
1 parent 97b243d commit 8805c88
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 20 deletions.
29 changes: 10 additions & 19 deletions library/Rules/DateTime.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
use DateTimeInterface;
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;
Expand All @@ -27,7 +29,7 @@
'{{name}} must not be a valid date/time in the format {{sample}}',
self::TEMPLATE_FORMAT,
)]
final class DateTime extends AbstractRule
final class DateTime extends Standard
{
use CanValidateDateTime;

Expand All @@ -38,33 +40,22 @@ public function __construct(
) {
}

public function validate(mixed $input): bool
public function evaluate(mixed $input): Result
{
$template = $this->format !== null ? self::TEMPLATE_FORMAT : self::TEMPLATE_STANDARD;
$parameters = ['sample' => date($this->format ?: 'c', strtotime('2005-12-30 01:02:03'))];
if ($input instanceof DateTimeInterface) {
return $this->format === null;
return new Result($this->format === null, $input, $this, $parameters, $template);
}

if (!is_scalar($input)) {
return false;
return Result::failed($input, $this, $parameters, $template);
}

if ($this->format === null) {
return strtotime((string) $input) !== false;
return new Result(strtotime((string) $input) !== false, $input, $this, $parameters, $template);
}

return $this->isDateTime($this->format, (string) $input);
}

/**
* @return array<string, mixed>
*/
public function getParams(): array
{
return ['sample' => date($this->format ?: 'c', strtotime('2005-12-30 01:02:03'))];
}

protected function getStandardTemplate(mixed $input): string
{
return $this->format !== null ? self::TEMPLATE_FORMAT : self::TEMPLATE_STANDARD;
return new Result($this->isDateTime($this->format, (string) $input), $input, $this, $parameters, $template);
}
}
2 changes: 1 addition & 1 deletion tests/unit/Rules/DateTimeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public function shouldValidateNoMatterTimezone(string $format, string $input, st

$rule = new DateTime($format);

self::assertTrue($rule->validate($input));
self::assertValidInput($rule, $input);

date_default_timezone_set($currentTimezone);
}
Expand Down

0 comments on commit 8805c88

Please sign in to comment.