death-notifier/src/main/php/com/fwdekker/deathnotifier/validation/EqualsRule.php

58 lines
1.9 KiB
PHP

<?php
namespace com\fwdekker\deathnotifier\validation;
use com\fwdekker\deathnotifier\Config;
use com\fwdekker\deathnotifier\IllegalStateError;
/**
* Validates that the input equals a pre-defined string.
*/
class EqualsRule extends Rule
{
/**
* @var string the string that the input should equal
*/
private readonly string $expected;
/**
* @var string the message that is returned if the input is incorrect
*/
private readonly string $message_if_incorrect;
/**
* Constructs a new `EqualsRule`.
*
* @param string $expected the string that the input should equal
* @param string $message_if_incorrect the message that is returned if the input is incorrect
*/
public function __construct(string $expected, string $message_if_incorrect)
{
$this->expected = $expected;
$this->message_if_incorrect = $message_if_incorrect;
}
/**
* Validates that the input equals the CLI password.
*
* @param array<int|string, mixed> $inputs the list of inputs in which the value at {@see $key} should be checked
* @param string $key the key in {@see $inputs} of the input to check
* @return void if the checked input equals the CLI password
* @throws InvalidTypeException if the CLI password is a blank string, if the CLI password is at its default
* value, or if the checked input is not set
* @throws InvalidValueException if the checked input does not equal the CLI password
*/
public function check(array $inputs, string $key): void
{
if (!isset($inputs[$key]))
throw new InvalidTypeException("Required input '$key' not set.");
if (!is_string($inputs[$key]))
throw new InvalidTypeException("Input '$key' should be string, but is " . gettype($inputs[$key]) . ".");
if ($inputs[$key] !== $this->expected)
throw new InvalidValueException($this->message_if_incorrect, $key);
}
}