mirror of
https://github.com/Respect/Validation.git
synced 2026-03-15 06:45:44 +01:00
50 lines
1 KiB
PHP
50 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 Attribute;
|
|
use ReflectionObject;
|
|
use Respect\Validation\Message\Template;
|
|
use Respect\Validation\Result;
|
|
use Respect\Validation\Rule;
|
|
|
|
use function is_object;
|
|
|
|
#[Attribute(Attribute::TARGET_PROPERTY | Attribute::IS_REPEATABLE)]
|
|
#[Template(
|
|
'{{name}} must be present',
|
|
'{{name}} must not be present',
|
|
)]
|
|
final readonly class PropertyExists implements Rule
|
|
{
|
|
public function __construct(
|
|
private string $propertyName,
|
|
) {
|
|
}
|
|
|
|
public function evaluate(mixed $input): Result
|
|
{
|
|
return new Result(
|
|
$this->hasProperty($input),
|
|
$input,
|
|
$this,
|
|
path: $this->propertyName,
|
|
);
|
|
}
|
|
|
|
private function hasProperty(mixed $input): bool
|
|
{
|
|
if (!is_object($input)) {
|
|
return false;
|
|
}
|
|
|
|
return (new ReflectionObject($input))->hasProperty($this->propertyName);
|
|
}
|
|
}
|