respect-validation/library/Rules/Subset.php
Henrique Moody 97b243daa1
Allow building rules using prefixes
Although helpful, the changes in the Min, Max, and Length rules made
using those rules more verbose. This commit will simplify their use by
allowing users to use them as prefixes.

Because I was creating prefixes for those rules, I made other cool
prefixes. Doing that is scary because it will generate more code to
support, and I would have liked to avoid that. However, that's a
valuable addition, and it's worth the risk.

I might reconsider that in the future, but for now, that looks like a
good idea.

Signed-off-by: Henrique Moody <henriquemoody@gmail.com>
2024-03-24 16:58:24 +01:00

41 lines
940 B
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\Message\Template;
use Respect\Validation\Result;
use Respect\Validation\Rules\Core\Standard;
use function array_diff;
use function is_array;
#[Template(
'{{name}} must be subset of {{superset}}',
'{{name}} must not be subset of {{superset}}',
)]
final class Subset extends Standard
{
/** @param mixed[] $superset */
public function __construct(
private readonly array $superset
) {
}
public function evaluate(mixed $input): Result
{
$parameters = ['superset' => $this->superset];
if (!is_array($input)) {
return Result::failed($input, $this, $parameters);
}
return new Result(array_diff($input, $this->superset) === [], $input, $this, $parameters);
}
}