mirror of
https://github.com/Respect/Validation.git
synced 2026-03-16 23:35:45 +01:00
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.
45 lines
1.1 KiB
PHP
45 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\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 Key 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;
|
|
}
|
|
|
|
return $this->rule
|
|
->evaluate($input[$this->key])
|
|
->withUnchangeableId((string) $this->key)
|
|
->withNameIfMissing($this->rule->getName() ?? (string) $this->key);
|
|
}
|
|
}
|