81 lines
2.8 KiB
PHP
81 lines
2.8 KiB
PHP
<?php
|
|
|
|
namespace com\fwdekker\deathnotifier;
|
|
|
|
use com\fwdekker\deathnotifier\validator\IsEqualToRule;
|
|
use com\fwdekker\deathnotifier\validator\IsNotSetRule;
|
|
use com\fwdekker\deathnotifier\validator\IsSetRule;
|
|
use InvalidArgumentException;
|
|
|
|
|
|
abstract class Action
|
|
{
|
|
private readonly bool $require_logged_in;
|
|
private readonly bool $require_logged_out;
|
|
private readonly bool $require_valid_csrf_token;
|
|
private readonly array $rule_lists;
|
|
|
|
public readonly ActionMethod $method;
|
|
public readonly string $action;
|
|
|
|
|
|
public function __construct(ActionMethod $method,
|
|
string $action,
|
|
bool $require_logged_in = false,
|
|
bool $require_logged_out = false,
|
|
bool $require_valid_csrf_token = false,
|
|
array $rule_lists = [])
|
|
{
|
|
if ($require_logged_in && $require_logged_out)
|
|
throw new InvalidArgumentException("Cannot require that user is both logged in and logged out.");
|
|
|
|
$this->method = $method;
|
|
$this->action = $action;
|
|
|
|
$this->require_logged_in = $require_logged_in;
|
|
$this->require_logged_out = $require_logged_out;
|
|
$this->require_valid_csrf_token = $require_valid_csrf_token;
|
|
$this->rule_lists = $rule_lists;
|
|
}
|
|
|
|
|
|
final function can_handle(ActionMethod $method, string $action): bool
|
|
{
|
|
return $method === $this->method && $action === $this->action;
|
|
}
|
|
|
|
/**
|
|
* Validates inputs, throwing an exception if any input is invalid.
|
|
*
|
|
* @return void if the input is valid
|
|
* @throws ValidationException if the input is invalid
|
|
*/
|
|
function validate_inputs(): void
|
|
{
|
|
$inputs = $this->method->get_inputs();
|
|
|
|
if ($this->require_logged_in)
|
|
(new IsSetRule("You must be logged in to perform this action."))->check($_SESSION, "uuid");
|
|
if ($this->require_logged_out)
|
|
(new IsNotSetRule("You must be logged out to perform this action."))->check($_SESSION, "uuid");
|
|
if ($this->require_valid_csrf_token)
|
|
(new IsEqualToRule(
|
|
$_SESSION["token"],
|
|
"Invalid request token. Please refresh the page and try again."
|
|
))->check($inputs, "token");
|
|
|
|
foreach ($this->rule_lists as $key => $rule_list)
|
|
foreach ($rule_list as $rule)
|
|
$rule->check($inputs, $key);
|
|
}
|
|
|
|
/**
|
|
* Performs the action.
|
|
*
|
|
* @return mixed the data requested by the action; may be `null`
|
|
* @throws ActionException if the action could not be performed
|
|
* @throws ValidationException if the inputs are invalid upon further inspection
|
|
*/
|
|
abstract function handle(): mixed;
|
|
}
|