respect-validation/library/Rules/Time.php
Henrique Moody d1f108dc87
Make proper use of exceptions in rules
This commit will ensure that all rules that cannot be created because of
invalid arguments in the constructor will throw the
InvalidRuleConstructorException. It will also make ComponentException
extend LogicException, which makes it easier to determine that the
client has improperly used the library.

I also introduced some tests for two exceptions with logic in their
constructor.

Signed-off-by: Henrique Moody <henriquemoody@gmail.com>
2024-03-25 22:09:02 +01:00

49 lines
1.3 KiB
PHP

<?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 time in the format {{sample}}',
'{{name}} must not be a valid time in the format {{sample}}',
)]
final class Time extends Standard
{
use CanValidateDateTime;
public function __construct(
private readonly string $format = 'H:i:s'
) {
if (!preg_match('/^[gGhHisuvaA\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('23:59:59'))];
if (!is_scalar($input)) {
return Result::failed($input, $this, $parameters);
}
return new Result($this->isDateTime($this->format, (string) $input), $input, $this, $parameters);
}
}