respect-validation/library/Rules/When.php
Henrique Moody 9322cd6375
Do not create results with siblings in the When rule
When creating a result with a sibling in the When rule, the result
generates an unhelpful message. In most of the use cases of the When
rule, the initial rule ("when") is only helpful in determining which
will be the "real" rule to use.

Those changes will change the When rule not to generate results with
siblings.

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

46 lines
1.1 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\Helpers\CanBindEvaluateRule;
use Respect\Validation\Result;
use Respect\Validation\Rules\Core\Standard;
use Respect\Validation\Validatable;
final class When extends Standard
{
use CanBindEvaluateRule;
private readonly Validatable $else;
public function __construct(
private readonly Validatable $when,
private readonly Validatable $then,
?Validatable $else = null
) {
if ($else === null) {
$else = new AlwaysInvalid();
$else->setTemplate(AlwaysInvalid::TEMPLATE_SIMPLE);
}
$this->else = $else;
}
public function evaluate(mixed $input): Result
{
$whenResult = $this->bindEvaluate($this->when, $this, $input);
if ($whenResult->isValid) {
return $this->bindEvaluate($this->then, $this, $input);
}
return $this->bindEvaluate($this->else, $this, $input);
}
}