respect-validation/library/Rules/Key.php
Henrique Moody a3c197f600
Handle names via the Named rule
Because of how the validation engine works now [1], there's no reason to
keep adding names to each rule. Instead, create a single rule that
handles naming rules with a few other accessories. This change is not
necessarily simple, but it shrinks the `Rule` interface, and it's more
aligned with how the library works right now.

Personally, I think this API is much more straightforward than the
`setName()` method, as it's way more explicit about which rule we're
naming. Because of this change, the behaviour changed slightly, but it's
for the best.

Because of this change, I managed to remove a lot of code, but
unfortunately, it's quite a big-bang commit. It would be too complicated
to make it atomic since names are an intrinsic part of the library.

[1]: 238f2d506a
2024-12-26 23:10:19 +01:00

55 lines
1.3 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\Result;
use Respect\Validation\Rule;
use Respect\Validation\Rules\Core\KeyRelated;
use Respect\Validation\Rules\Core\Nameable;
use Respect\Validation\Rules\Core\Wrapper;
#[Attribute(Attribute::TARGET_PROPERTY | Attribute::IS_REPEATABLE)]
final class Key extends Wrapper implements KeyRelated
{
public function __construct(
private readonly int|string $key,
Rule $rule,
) {
parent::__construct($rule);
}
public function getKey(): int|string
{
return $this->key;
}
public function evaluate(mixed $input): Result
{
$keyExistsResult = (new KeyExists($this->key))->evaluate($input);
if (!$keyExistsResult->isValid) {
return $keyExistsResult->withName($this->getName());
}
return $this->rule
->evaluate($input[$this->key])
->withName($this->getName())
->withUnchangeableId((string) $this->key);
}
private function getName(): string
{
if ($this->rule instanceof Nameable) {
return $this->rule->getName() ?? ((string) $this->key);
}
return (string) $this->key;
}
}