respect-validation/library/Rules/KeyOptional.php
Henrique Moody 82cb05b197
Handle siblings when creating messages
The way we display messages could have been better, and it took me a
while to realise that to make it better, I would need to handle the
siblings of a result before deciding whether we should render it.

Another issue was that rules like Key and Property had to create a
"dumb" parent just so we would display the messages correctly, and in
some cases, that wasn't even enough.

This commit introduces quite a few changes to how the library works,
making the messages much more straightforward.
2024-12-13 02:34:27 +01:00

45 lines
1.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\Result;
use Respect\Validation\Rule;
use Respect\Validation\Rules\Core\Binder;
use Respect\Validation\Rules\Core\KeyRelated;
use Respect\Validation\Rules\Core\Wrapper;
final class KeyOptional extends Wrapper implements KeyRelated
{
public function __construct(
private readonly int|string $key,
Rule $rule,
) {
$rule->setName($rule->getName() ?? (string) $key);
parent::__construct($rule);
}
public function getKey(): int|string
{
return $this->key;
}
public function evaluate(mixed $input): Result
{
$keyExistsResult = (new Binder($this, new KeyExists($this->key)))->evaluate($input);
if (!$keyExistsResult->isValid) {
return $keyExistsResult->withInvertedMode();
}
return $this->rule
->evaluate($input[$this->key])
->withUnchangeableId((string) $this->key)
->withNameIfMissing($this->rule->getName() ?? (string) $this->key);
}
}