70 lines
2.6 KiB
PHP
70 lines
2.6 KiB
PHP
<?php
|
|
|
|
namespace com\fwdekker\deathnotifier\user;
|
|
|
|
use com\fwdekker\deathnotifier\Action;
|
|
use com\fwdekker\deathnotifier\validator\IsBooleanRule;
|
|
use com\fwdekker\deathnotifier\validator\IsValidCsrfTokenRule;
|
|
use com\fwdekker\deathnotifier\UnexpectedException;
|
|
use com\fwdekker\deathnotifier\validator\InvalidInputException;
|
|
use com\fwdekker\deathnotifier\validator\RuleSet;
|
|
use com\fwdekker\deathnotifier\validator\SessionRuleSet;
|
|
|
|
|
|
/**
|
|
* Sets whether email notifications are sent.
|
|
*/
|
|
class ToggleNotificationsAction extends Action
|
|
{
|
|
/**
|
|
* @var UserList the list containing the user to toggle notifications for
|
|
*/
|
|
private readonly UserList $user_list;
|
|
|
|
|
|
/**
|
|
* Constructs a new `ToggleNotificationsAction`.
|
|
*
|
|
* @param UserList $user_list the list containing the user to toggle notifications for
|
|
*/
|
|
public function __construct(UserList $user_list)
|
|
{
|
|
$this->user_list = $user_list;
|
|
}
|
|
|
|
|
|
/**
|
|
* Sets whether email notifications are sent.
|
|
*
|
|
* Requires that the user is logged in and that a valid CSRF token is present.
|
|
*
|
|
* @param array<int|string, mixed> $inputs `"token": string`: a valid CSRF token, `"enable_notifications": bool`:
|
|
* `true` if and only if notifications should be enabled
|
|
* @return null
|
|
* @throws InvalidInputException if the user is not logged in, if no valid CSRF token is present, if the toggle
|
|
* value is not a boolean, or if the user's email address it not verified
|
|
* @throws UnexpectedException if the current user has been deleted
|
|
* @noinspection PhpDocRedundantThrowsInspection can be thrown through {@see TrackingList::transaction()}
|
|
*/
|
|
public function handle(array $inputs): mixed
|
|
{
|
|
(new SessionRuleSet(validate_logged_in: true))->check($_SESSION);
|
|
(new RuleSet([
|
|
"token" => [new IsValidCsrfTokenRule()],
|
|
"enable_notifications" => [new IsBooleanRule()],
|
|
]))->check($inputs);
|
|
|
|
$this->user_list->transaction(function () use ($inputs) {
|
|
$user_data = $this->user_list->get_user_by_uuid($_SESSION["uuid"]);
|
|
if ($user_data === null)
|
|
throw new UnexpectedException("Failed to retrieve user data. Refresh the page and try again.");
|
|
if ($inputs["enable_notifications"] && $user_data["email_verification_token"] !== null)
|
|
throw new InvalidInputException("Please verify your email address before toggling notifications.");
|
|
|
|
$this->user_list->set_notifications_enabled($_SESSION["uuid"], $inputs["enable_notifications"]);
|
|
});
|
|
|
|
return null;
|
|
}
|
|
}
|