for testing and deploying your application
for finding and fixing issues
for empowering human code reviews
<?php
declare(strict_types=1);
namespace Yiisoft\Validator\Rule;
use Yiisoft\Arrays\ArrayHelper;
use Yiisoft\Validator\Exception\UnexpectedRuleException;
use Yiisoft\Validator\Formatter;
use Yiisoft\Validator\FormatterInterface;
use Yiisoft\Validator\Result;
use Yiisoft\Validator\ValidationContext;
/**
* Validates that the value is among a list of values.
*
* The range can be specified via constructor.
* If the {@see InRange::$not} is called, the rule will ensure the value is NOT among the specified range.
*/
final class InRangeHandler implements RuleHandlerInterface
{
private FormatterInterface $formatter;
public function __construct(?FormatterInterface $formatter = null)
$this->formatter = $formatter ?? new Formatter();
}
public function validate(mixed $value, object $rule, ?ValidationContext $context = null): Result
if (!$rule instanceof InRange) {
throw new UnexpectedRuleException(InRange::class, $rule);
$result = new Result();
if ($value === null && $rule->isSkipOnEmpty()) {
return $result;
if ($rule->isNot() === ArrayHelper::isIn($value, $rule->getRange(), $rule->isStrict())) {
$formattedMessage = $this->formatter->format(
$rule->getMessage(),
['attribute' => $context?->getAttribute(), 'value' => $value]
);
$result->addError($formattedMessage);