respect-validation/library/Rules/UndefOr.php
Henrique Moody 94ddfcd0bd
Create named constructor to create Result
The constructor of `Result` has many arguments, but that's not the
primary reason why I'm making this change. I want to change the
constructor, and it will become more complicated, so having this named
constructor will be useful in the next refactoring.

With this change, I also made the `id` mandatory. That made the
constructor look neater and most to promote almost all properties to the
constructor.

Another change was removing the `fromAdjacent` method, which was quite
confusing. I created the `asAdjacentOf` method, which is a bit clearer.
If anything, it makes all static methods named constructors. It will be
a bit more verbose, but more intuitive.
2025-12-26 22:34:43 +01:00

53 lines
1.4 KiB
PHP

<?php
/*
* Copyright (c) Alexandre Gomes Gaigalas <alganet@gmail.com>
* SPDX-License-Identifier: MIT
*/
declare(strict_types=1);
namespace Respect\Validation\Rules;
use Attribute;
use Respect\Validation\Helpers\CanValidateUndefined;
use Respect\Validation\Message\Template;
use Respect\Validation\Result;
use Respect\Validation\Rules\Core\Wrapper;
use function array_map;
#[Attribute(Attribute::TARGET_PROPERTY | Attribute::IS_REPEATABLE)]
#[Template(
'or must be undefined',
'and must not be undefined',
)]
final class UndefOr extends Wrapper
{
use CanValidateUndefined;
public function evaluate(mixed $input): Result
{
$result = $this->rule->evaluate($input);
if (!$this->isUndefined($input)) {
return $this->enrichResult($result);
}
if (!$result->hasPassed) {
return $this->enrichResult($result->withToggledValidation());
}
return $this->enrichResult($result);
}
private function enrichResult(Result $result): Result
{
if ($result->allowsAdjacent()) {
return $result
->withId($result->id->withPrefix('undefOr'))
->withAdjacent(Result::of($result->hasPassed, $result->input, $this));
}
return $result->withChildren(...array_map(fn(Result $child) => $this->enrichResult($child), $result->children));
}
}