death-notifier/src/main/php/com/fwdekker/deathnotifier/validator/LengthRule.php

68 lines
2.3 KiB
PHP

<?php
namespace com\fwdekker\deathnotifier\validator;
use com\fwdekker\deathnotifier\Response;
/**
* Requires the input to be of a specific length.
*/
class LengthRule extends Rule
{
/**
* @var int|null The minimum length (inclusive), or `null` if there is no minimum length.
*/
private readonly ?int $min_length;
/**
* @var int|null The maximum length (inclusive), or `null` if there is no maximum length.
*/
private readonly ?int $max_length;
/**
* Instantiates a new rule.
*
* @param int|null $min_length the minimum length (inclusive), or `null` if there is no minimum length
* @param int|null $max_length the maximum length (inclusive), or `null` if there is no maximum length
* @param string|null $override_message the message to return if the rule does not apply to some input. If `null`,
* the rule implementation can choose an appropriate message
*/
public function __construct(?int $min_length = null, ?int $max_length = null, ?string $override_message = null)
{
parent::__construct($override_message);
$this->min_length = $min_length;
$this->max_length = $max_length;
}
/**
* Checks whether the input is of the specified length.
*
* @param array<string, mixed> $inputs the list of inputs in which the value at `key` should be checked
* @param string $key the key in `inputs` of the input to check
* @return Response|null `null` if the input is of the specified length, or an unsatisfied `Response` otherwise
*/
public function check(array $inputs, string $key): ?Response
{
if (!isset($inputs[$key]))
return Response::unsatisfied(
$this->override_message ?? "Missing input '$key'.",
$key
);
else if ($this->min_length !== null && strlen($inputs[$key]) < $this->min_length)
return Response::unsatisfied(
$this->override_message ?? "Use at least $this->min_length character(s).",
$key
);
else if ($this->max_length !== null && strlen($inputs[$key]) > $this->max_length)
return Response::unsatisfied(
$this->override_message ?? "Use at most $this->max_length character(s).",
$key
);
else
return null;
}
}