You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
71 lines
2.0 KiB
71 lines
2.0 KiB
<?php
|
|
|
|
namespace App\Controller\Route;
|
|
|
|
use App\Http\HttpResponse;
|
|
use App\Session\SessionHandle;
|
|
use Exception;
|
|
|
|
/**
|
|
* A Front controller action
|
|
*/
|
|
class Action {
|
|
/**
|
|
* @var callable(mixed[]): HttpResponse $action action to call
|
|
*/
|
|
private $action;
|
|
|
|
private bool $isAuthRequired;
|
|
|
|
/**
|
|
* @param callable(mixed[]): HttpResponse $action
|
|
*/
|
|
private function __construct(callable $action, bool $isAuthRequired) {
|
|
$this->action = $action;
|
|
$this->isAuthRequired = $isAuthRequired;
|
|
}
|
|
|
|
public function isAuthRequired(): bool {
|
|
return $this->isAuthRequired;
|
|
}
|
|
|
|
/**
|
|
* @param mixed[] $params
|
|
* @param SessionHandle $session
|
|
* @return HttpResponse
|
|
* @throws Exception <p>
|
|
* thrown if this action is required to be authenticated, but the given session does not contain a logged-in account.
|
|
* </p>
|
|
* <p>
|
|
* Caller is supposed to ensure that the user is logged-in before, if `$this->isAuthRequired()` is true before
|
|
* running this action.
|
|
* </p>
|
|
*/
|
|
public function run(array $params, SessionHandle $session): HttpResponse {
|
|
$params = array_values($params);
|
|
if ($this->isAuthRequired) {
|
|
if ($session->getAccount() == null) {
|
|
throw new Exception("action requires authorization.");
|
|
}
|
|
}
|
|
|
|
$params[] = $session;
|
|
return call_user_func_array($this->action, $params);
|
|
}
|
|
|
|
/**
|
|
* @param callable(mixed[]): HttpResponse $action
|
|
* @return Action an action that does not require to have an authorization.
|
|
*/
|
|
public static function noAuth(callable $action): Action {
|
|
return new Action($action, false);
|
|
}
|
|
|
|
/**
|
|
* @param callable(mixed[]): HttpResponse $action
|
|
* @return Action an action that does require to have an authorization.
|
|
*/
|
|
public static function auth(callable $action): Action {
|
|
return new Action($action, true);
|
|
}
|
|
} |