respect-validation/library/Rules/Call.php
Henrique Moody 2fac861aa1
Do not trigger PHP errors in the "Call" rule
This commit make sure that when the callable is executed by the "Call"
rule and PHP triggers an error, the user does not have to deal with it,
and instead the rule will throw "CallException".

Because of the many changes that were made, it didn't make sense to keep
the class "Call" extending the "AbstractRelated" class.

One thing that is a bit problematic with this rule - and with other
rules as well - is that Validation only knows details of a validation
when it fails, because of that we cannot invert the validations that
passed, meaning that the "Not" rule cannot give the proper response to
a validation that passed. This is a know issue that can only be fixed
is we provide a way for Validation do have more granularity control.

Signed-off-by: Henrique Moody <henriquemoody@gmail.com>
2018-08-21 01:22:38 +02:00

98 lines
2.1 KiB
PHP

<?php
/*
* This file is part of Respect/Validation.
*
* (c) Alexandre Gomes Gaigalas <alexandre@gaigalas.net>
*
* For the full copyright and license information, please view the "LICENSE.md"
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Respect\Validation\Rules;
use Respect\Validation\Exceptions\ValidationException;
use Respect\Validation\Validatable;
use function call_user_func;
use function restore_error_handler;
use function set_error_handler;
/**
* Validates the return of a callable for a given input.
*
* @author Alexandre Gomes Gaigalas <alexandre@gaigalas.net>
* @author Emmerson Siqueira <emmersonsiqueira@gmail.com>
* @author Henrique Moody <henriquemoody@gmail.com>
*/
final class Call extends AbstractRule
{
/**
* @var callable
*/
private $callable;
/**
* @var Validatable
*/
private $rule;
/**
* Initializes the rule with the callable to be executed after the input is passed.
*
* @param callable $callable
* @param Validatable $rule
*/
public function __construct(callable $callable, Validatable $rule)
{
$this->callable = $callable;
$this->rule = $rule;
}
/**
* {@inheritdoc}
*/
public function assert($input): void
{
$this->setErrorHandler($input);
$this->rule->assert(call_user_func($this->callable, $input));
restore_error_handler();
}
/**
* {@inheritdoc}
*/
public function check($input): void
{
$this->setErrorHandler($input);
$this->rule->check(call_user_func($this->callable, $input));
restore_error_handler();
}
/**
* {@inheritdoc}
*/
public function validate($input): bool
{
try {
$this->check($input);
} catch (ValidationException $exception) {
return false;
}
return true;
}
private function setErrorHandler($input): void
{
set_error_handler(function () use ($input): void {
throw $this->reportError($input);
});
}
}