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

77 lines
2.5 KiB
PHP

<?php
namespace com\fwdekker\deathnotifier\validator;
use com\fwdekker\deathnotifier\Response;
/**
* Validates arrays of inputs such as `$_POST` or `$_SESSION` using `Rule`s.
*/
class Validator
{
/**
* Validates whether values in `inputs` match the rules specified in `rule_sets`.
*
* @param array<string, string> $inputs the array of inputs in which to check the values
* @param array<string, Rule[]> $rule_sets maps keys in `inputs` to an array of `Rule`s to be checked
* @return Response|null `null` if all rules are satisfied, or an unsatisfied `Response` otherwise
*/
static function validate_inputs(array $inputs, array $rule_sets): ?Response
{
foreach ($rule_sets as $key => $rules) {
foreach ($rules as $rule) {
$is_valid = $rule->check($inputs, $key);
if ($is_valid !== null)
return $is_valid;
}
}
return null;
}
/**
* Validates that the user is logged in.
*
* @param array<string, string> $session the session to check
* @return Response|null `null` if the user is logged in, or an unsatisfied `Response` otherwise
*/
static function validate_logged_in(array $session): ?Response
{
if (!isset($session["uuid"]))
return Response::unsatisfied("You must be logged in to perform this action.");
return null;
}
/**
* Validates that the user is logged out.
*
* @param array<string, string> $session the session to check
* @return Response|null `null` if the user is logged out, or an unsatisfied `Response` otherwise
*/
static function validate_logged_out(array $session): ?Response
{
if (isset($session["uuid"]))
return Response::unsatisfied("You must be logged out to perform this action.");
return null;
}
/**
* Validates that the array contains the correct token.
*
* @param array<string, string> $token_array the array with key `token`
* @param string $token the expected token
* @return Response|null `null` if the token is correct, or an unsatisfied `Response` otherwise
*/
static function validate_token(array $token_array, string $token): ?Response
{
if (!isset($token_array["token"]) || $token_array["token"] !== $token)
return Response::unsatisfied("Invalid request token. Please refresh the page and try again.");
return null;
}
}