respect-validation/library/Rules/Call.php
Henrique Moody e4f2c8154a
Use PHP attributes to define templates
Creating a specific exception for each rule adds a painful overhead. If
you want to make a custom message for your rule, you will need to create
an exception and then register that exception namespace to be able to
use it—all that is just for customizing the message of your rule.

Having different namespaces also implies that you need to fetch the
exception of the rule from another directory to change it. As Uncle Bob
said, "Classes that change together belong together. Classes that are
not reused together should not be grouped."

This commit will drastically change this library, moving all the
templates from the exceptions to the rules. Consequently, the Factory
becomes much simpler, and the library gets a bit smaller, too.

Signed-off-by: Henrique Moody <henriquemoody@gmail.com>
2024-01-29 23:43:57 +01:00

94 lines
2.2 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\Attributes\Template;
use Respect\Validation\Exceptions\ValidationException;
use Respect\Validation\Validatable;
use Throwable;
use function call_user_func;
use function restore_error_handler;
use function set_error_handler;
#[Template(
'{{input}} must be valid when executed with {{callable}}',
'{{input}} must not be valid when executed with {{callable}}',
)]
final class Call extends AbstractRule
{
/**
* @var callable
*/
private $callable;
public function __construct(
callable $callable,
private readonly Validatable $rule
) {
$this->callable = $callable;
}
public function assert(mixed $input): void
{
$this->setErrorHandler($input);
try {
$this->rule->assert(call_user_func($this->callable, $input));
} catch (ValidationException $exception) {
throw $exception;
} catch (Throwable $throwable) {
throw $this->reportError($input);
} finally {
restore_error_handler();
}
}
public function check(mixed $input): void
{
$this->setErrorHandler($input);
try {
$this->rule->check(call_user_func($this->callable, $input));
} catch (ValidationException $exception) {
throw $exception;
} catch (Throwable $throwable) {
throw $this->reportError($input);
} finally {
restore_error_handler();
}
}
public function validate(mixed $input): bool
{
try {
$this->check($input);
} catch (ValidationException $exception) {
return false;
}
return true;
}
/**
* @return array<string, callable>
*/
public function getParams(): array
{
return ['callable' => $this->callable];
}
private function setErrorHandler(mixed $input): void
{
set_error_handler(function () use ($input): void {
throw $this->reportError($input);
});
}
}