respect-validation/library/Rules/PropertyExists.php
Henrique Moody 8573bc5d45
Do not overwrite "IDs" when updating names
When you have a chain of rules in the Validation and overwrite the name
with "setName()," it's impossible to get the messages from all rules in
the chain as an array because they all have the same name.

These changes will change that behavior by creating a more explicit
distinction between "IDs" and "names." The "IDs" will remain
unchangeable, while we can always overwrite the names. That means that
the array messages will look more similar to the chain, and it will be
possible to overwrite the messages from multiple rules in the same
chain.

Signed-off-by: Henrique Moody <henriquemoody@gmail.com>
2024-03-26 01:12:44 +01:00

47 lines
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 ReflectionObject;
use Respect\Validation\Message\Template;
use Respect\Validation\Result;
use Respect\Validation\Rules\Core\Standard;
use function is_object;
#[Template(
'{{name}} must be present',
'{{name}} must not be present',
)]
final class PropertyExists extends Standard
{
public function __construct(
private readonly string $propertyName
) {
}
public function evaluate(mixed $input): Result
{
if (!is_object($input)) {
return Result::failed($input, $this)->withNameIfMissing($this->propertyName)->withId($this->propertyName);
}
$reflection = new ReflectionObject($input);
return new Result(
$reflection->hasProperty($this->propertyName),
$input,
$this,
name: $this->propertyName,
id: $this->propertyName
);
}
}