respect-validation/library/Rules/ContainsAny.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

55 lines
1.4 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\Exceptions\InvalidRuleConstructorException;
use Respect\Validation\Message\Template;
use Respect\Validation\Rules\Core\Envelope;
use function array_map;
use function count;
#[Template(
'{{name}} must contain at least one of the values {{needles}}',
'{{name}} must not contain any of the values {{needles}}',
)]
final class ContainsAny extends Envelope
{
/** @param non-empty-array<mixed> $needles */
public function __construct(array $needles, bool $identical = false)
{
// @phpstan-ignore-next-line
if (empty($needles)) {
throw new InvalidRuleConstructorException('At least one value must be provided');
}
$rules = $this->getRules($needles, $identical);
parent::__construct(
count($rules) === 1 ? $rules[0] : new AnyOf(...$rules),
['needles' => $needles]
);
}
/**
* @param mixed[] $needles
*
* @return Contains[]
*/
private function getRules(array $needles, bool $identical): array
{
return array_map(
static function ($needle) use ($identical): Contains {
return new Contains($needle, $identical);
},
$needles
);
}
}