Make FlashLevels an enum.

This commit is contained in:
Buster Neece 2023-02-23 23:10:58 -06:00
parent 0da43ea431
commit ede5e88a49
No known key found for this signature in database
GPG Key ID: F1D2E64A0005E80E
19 changed files with 77 additions and 95 deletions

View File

@ -7,7 +7,6 @@ namespace App\Controller\Admin\Debug;
use App\Console\Application; use App\Console\Application;
use App\Http\Response; use App\Http\Response;
use App\Http\ServerRequest; use App\Http\ServerRequest;
use App\Session\Flash;
use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ResponseInterface;
final class ClearCacheAction final class ClearCacheAction
@ -26,7 +25,7 @@ final class ClearCacheAction
); );
// Flash an update to ensure the session is recreated. // Flash an update to ensure the session is recreated.
$request->getFlash()->addMessage($resultOutput, Flash::SUCCESS); $request->getFlash()->success($resultOutput);
return $response->withRedirect($request->getRouter()->fromHere('admin:debug:index')); return $response->withRedirect($request->getRouter()->fromHere('admin:debug:index'));
} }

View File

@ -8,7 +8,6 @@ use App\Http\Response;
use App\Http\ServerRequest; use App\Http\ServerRequest;
use App\MessageQueue\QueueManagerInterface; use App\MessageQueue\QueueManagerInterface;
use App\MessageQueue\QueueNames; use App\MessageQueue\QueueNames;
use App\Session\Flash;
use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ResponseInterface;
final class ClearQueueAction final class ClearQueueAction
@ -32,10 +31,7 @@ final class ClearQueueAction
} }
// Flash an update to ensure the session is recreated. // Flash an update to ensure the session is recreated.
$request->getFlash()->addMessage( $request->getFlash()->success(__('Message queue cleared.'));
__('Message queue cleared.'),
Flash::SUCCESS
);
return $response->withRedirect($request->getRouter()->fromHere('admin:debug:index')); return $response->withRedirect($request->getRouter()->fromHere('admin:debug:index'));
} }

View File

@ -10,7 +10,6 @@ use App\Http\Response;
use App\Http\ServerRequest; use App\Http\ServerRequest;
use App\RateLimit; use App\RateLimit;
use App\Service\Mail; use App\Service\Mail;
use App\Session\Flash;
use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ResponseInterface;
final class ForgotPasswordAction final class ForgotPasswordAction
@ -38,7 +37,7 @@ final class ForgotPasswordAction
try { try {
$this->rateLimit->checkRequestRateLimit($request, 'forgot', 30, 3); $this->rateLimit->checkRequestRateLimit($request, 'forgot', 30, 3);
} catch (RateLimitExceededException) { } catch (RateLimitExceededException) {
$flash->addMessage( $flash->error(
sprintf( sprintf(
'<b>%s</b><br>%s', '<b>%s</b><br>%s',
__('Too many forgot password attempts'), __('Too many forgot password attempts'),
@ -47,7 +46,6 @@ final class ForgotPasswordAction
. '30 seconds and try again.' . '30 seconds and try again.'
) )
), ),
Flash::ERROR
); );
return $response->withRedirect($request->getUri()->getPath()); return $response->withRedirect($request->getUri()->getPath());
@ -75,7 +73,7 @@ final class ForgotPasswordAction
$this->mail->send($email); $this->mail->send($email);
} }
$flash->addMessage( $flash->success(
sprintf( sprintf(
'<b>%s</b><br>%s', '<b>%s</b><br>%s',
__('Account recovery e-mail sent.'), __('Account recovery e-mail sent.'),
@ -84,7 +82,6 @@ final class ForgotPasswordAction
. 'for a password reset message.' . 'for a password reset message.'
) )
), ),
Flash::SUCCESS
); );
return $response->withRedirect($request->getRouter()->named('account:login')); return $response->withRedirect($request->getRouter()->named('account:login'));

View File

@ -9,7 +9,6 @@ use App\Exception\RateLimitExceededException;
use App\Http\Response; use App\Http\Response;
use App\Http\ServerRequest; use App\Http\ServerRequest;
use App\RateLimit; use App\RateLimit;
use App\Session\Flash;
use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\EntityManagerInterface;
use Mezzio\Session\SessionCookiePersistenceInterface; use Mezzio\Session\SessionCookiePersistenceInterface;
use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ResponseInterface;
@ -55,13 +54,12 @@ final class LoginAction
try { try {
$this->rateLimit->checkRequestRateLimit($request, 'login', 30, 5); $this->rateLimit->checkRequestRateLimit($request, 'login', 30, 5);
} catch (RateLimitExceededException) { } catch (RateLimitExceededException) {
$flash->addMessage( $flash->error(
sprintf( sprintf(
'<b>%s</b><br>%s', '<b>%s</b><br>%s',
__('Too many login attempts'), __('Too many login attempts'),
__('You have attempted to log in too many times. Please wait 30 seconds and try again.') __('You have attempted to log in too many times. Please wait 30 seconds and try again.')
), ),
Flash::ERROR
); );
return $response->withRedirect($request->getUri()->getPath()); return $response->withRedirect($request->getUri()->getPath());
@ -93,20 +91,18 @@ final class LoginAction
// Redirect to complete setup if it's not completed yet. // Redirect to complete setup if it's not completed yet.
if (!$settings->isSetupComplete()) { if (!$settings->isSetupComplete()) {
$flash->addMessage( $flash->success(
sprintf( sprintf(
'<b>%s</b><br>%s', '<b>%s</b><br>%s',
__('Logged in successfully.'), __('Logged in successfully.'),
__('Complete the setup process to get started.') __('Complete the setup process to get started.')
), ),
Flash::SUCCESS
); );
return $response->withRedirect($request->getRouter()->named('setup:index')); return $response->withRedirect($request->getRouter()->named('setup:index'));
} }
$flash->addMessage( $flash->success(
'<b>' . __('Logged in successfully.') . '</b><br>' . $user->getEmail(), '<b>' . __('Logged in successfully.') . '</b><br>' . $user->getEmail(),
Flash::SUCCESS
); );
$referrer = $session->get('login_referrer'); $referrer = $session->get('login_referrer');
@ -115,9 +111,8 @@ final class LoginAction
); );
} }
$flash->addMessage( $flash->error(
'<b>' . __('Login unsuccessful') . '</b><br>' . __('Your credentials could not be verified.'), '<b>' . __('Login unsuccessful') . '</b><br>' . __('Your credentials could not be verified.'),
Flash::ERROR
); );
return $response->withRedirect((string)$request->getUri()); return $response->withRedirect((string)$request->getUri());

View File

@ -8,7 +8,6 @@ use App\Entity;
use App\Exception\NotFoundException; use App\Exception\NotFoundException;
use App\Http\Response; use App\Http\Response;
use App\Http\ServerRequest; use App\Http\ServerRequest;
use App\Session\Flash;
use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ResponseInterface;
final class MasqueradeAction final class MasqueradeAction
@ -37,9 +36,8 @@ final class MasqueradeAction
$auth = $request->getAuth(); $auth = $request->getAuth();
$auth->masqueradeAsUser($user); $auth->masqueradeAsUser($user);
$request->getFlash()->addMessage( $request->getFlash()->success(
'<b>' . __('Logged in successfully.') . '</b><br>' . $user->getEmail(), '<b>' . __('Logged in successfully.') . '</b><br>' . $user->getEmail(),
Flash::SUCCESS
); );
return $response->withRedirect($request->getRouter()->named('dashboard')); return $response->withRedirect($request->getRouter()->named('dashboard'));

View File

@ -7,7 +7,6 @@ namespace App\Controller\Frontend\Account;
use App\Entity; use App\Entity;
use App\Http\Response; use App\Http\Response;
use App\Http\ServerRequest; use App\Http\ServerRequest;
use App\Session\Flash;
use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\EntityManagerInterface;
use InvalidArgumentException; use InvalidArgumentException;
use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ResponseInterface;
@ -30,12 +29,11 @@ final class RecoverAction
$flash = $request->getFlash(); $flash = $request->getFlash();
if (!$user instanceof Entity\User) { if (!$user instanceof Entity\User) {
$flash->addMessage( $flash->error(
sprintf( sprintf(
'<b>%s</b>', '<b>%s</b>',
__('Invalid token specified.'), __('Invalid token specified.'),
), ),
Flash::ERROR
); );
return $response->withRedirect($request->getRouter()->named('account:login')); return $response->withRedirect($request->getRouter()->named('account:login'));
@ -64,13 +62,12 @@ final class RecoverAction
$this->loginTokenRepo->revokeForUser($user); $this->loginTokenRepo->revokeForUser($user);
$flash->addMessage( $flash->success(
sprintf( sprintf(
'<b>%s</b><br>%s', '<b>%s</b><br>%s',
__('Logged in using account recovery token'), __('Logged in using account recovery token'),
__('Your password has been updated.') __('Your password has been updated.')
), ),
Flash::SUCCESS
); );
return $response->withRedirect($request->getRouter()->named('dashboard')); return $response->withRedirect($request->getRouter()->named('dashboard'));

View File

@ -7,7 +7,6 @@ namespace App\Controller\Frontend\Account;
use App\Entity\User; use App\Entity\User;
use App\Http\Response; use App\Http\Response;
use App\Http\ServerRequest; use App\Http\ServerRequest;
use App\Session\Flash;
use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ResponseInterface;
final class TwoFactorAction final class TwoFactorAction
@ -26,9 +25,8 @@ final class TwoFactorAction
/** @var User $user */ /** @var User $user */
$user = $auth->getUser(); $user = $auth->getUser();
$flash->addMessage( $flash->success(
'<b>' . __('Logged in successfully.') . '</b><br>' . $user->getEmail(), '<b>' . __('Logged in successfully.') . '</b><br>' . $user->getEmail(),
Flash::SUCCESS
); );
$referrer = $request->getSession()->get('login_referrer'); $referrer = $request->getSession()->get('login_referrer');
@ -39,9 +37,8 @@ final class TwoFactorAction
return $response->withRedirect($request->getRouter()->named('dashboard')); return $response->withRedirect($request->getRouter()->named('dashboard'));
} }
$flash->addMessage( $flash->error(
'<b>' . __('Login unsuccessful') . '</b><br>' . __('Your credentials could not be verified.'), '<b>' . __('Login unsuccessful') . '</b><br>' . __('Your credentials could not be verified.'),
Flash::ERROR
); );
return $response->withRedirect((string)$request->getUri()); return $response->withRedirect((string)$request->getUri());

View File

@ -11,7 +11,6 @@ use App\Exception\PodcastNotFoundException;
use App\Exception\StationNotFoundException; use App\Exception\StationNotFoundException;
use App\Http\Response; use App\Http\Response;
use App\Http\ServerRequest; use App\Http\ServerRequest;
use App\Session\Flash;
use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ResponseInterface;
final class PodcastEpisodeAction final class PodcastEpisodeAction
@ -53,7 +52,7 @@ final class PodcastEpisodeAction
); );
if (!($episode instanceof PodcastEpisode) || !$episode->isPublished()) { if (!($episode instanceof PodcastEpisode) || !$episode->isPublished()) {
$request->getFlash()->addMessage(__('Episode not found.'), Flash::ERROR); $request->getFlash()->error(__('Episode not found.'));
return $response->withRedirect($podcastEpisodesLink); return $response->withRedirect($podcastEpisodesLink);
} }

View File

@ -11,7 +11,6 @@ use App\Exception\PodcastNotFoundException;
use App\Exception\StationNotFoundException; use App\Exception\StationNotFoundException;
use App\Http\Response; use App\Http\Response;
use App\Http\ServerRequest; use App\Http\ServerRequest;
use App\Session\Flash;
use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ResponseInterface;
final class PodcastEpisodesAction final class PodcastEpisodesAction
@ -65,7 +64,7 @@ final class PodcastEpisodesAction
); );
if (count($publishedEpisodes) === 0) { if (count($publishedEpisodes) === 0) {
$request->getFlash()->addMessage(__('No episodes found.'), Flash::ERROR); $request->getFlash()->error(__('No episodes found.'));
return $response->withRedirect($podcastsLink); return $response->withRedirect($podcastsLink);
} }

View File

@ -10,7 +10,6 @@ use App\Exception\NotLoggedInException;
use App\Exception\ValidationException; use App\Exception\ValidationException;
use App\Http\Response; use App\Http\Response;
use App\Http\ServerRequest; use App\Http\ServerRequest;
use App\Session\Flash;
use App\Version; use App\Version;
use App\VueComponent\StationFormComponent; use App\VueComponent\StationFormComponent;
use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\EntityManagerInterface;
@ -188,7 +187,7 @@ final class SetupController
ServerRequest $request, ServerRequest $request,
Response $response Response $response
): ResponseInterface { ): ResponseInterface {
$request->getFlash()->addMessage('<b>' . __('Setup has already been completed!') . '</b>', Flash::ERROR); $request->getFlash()->error('<b>' . __('Setup has already been completed!') . '</b>');
return $response->withRedirect($request->getRouter()->named('dashboard')); return $response->withRedirect($request->getRouter()->named('dashboard'));
} }

View File

@ -175,7 +175,7 @@ final class ErrorHandler extends \Slim\Handlers\ErrorHandler
$session = $sessionPersistence->initializeSessionFromRequest($this->request); $session = $sessionPersistence->initializeSessionFromRequest($this->request);
$flash = new Flash($session); $flash = new Flash($session);
$flash->addMessage(__('You must be logged in to access this page.'), Flash::ERROR); $flash->error(__('You must be logged in to access this page.'));
// Set referrer for login redirection. // Set referrer for login redirection.
$session->set('login_referrer', $this->request->getUri()->getPath()); $session->set('login_referrer', $this->request->getUri()->getPath());
@ -204,9 +204,8 @@ final class ErrorHandler extends \Slim\Handlers\ErrorHandler
$session = $sessionPersistence->initializeSessionFromRequest($this->request); $session = $sessionPersistence->initializeSessionFromRequest($this->request);
$flash = new Flash($session); $flash = new Flash($session);
$flash->addMessage( $flash->error(
__('You do not have permission to access this portion of the site.'), __('You do not have permission to access this portion of the site.'),
Flash::ERROR
); );
$response = $sessionPersistence->persistSession($session, $response); $response = $sessionPersistence->persistSession($session, $response);

View File

@ -8,7 +8,7 @@ use App\Entity\Api\Notification;
use App\Entity\Repository\SettingsRepository; use App\Entity\Repository\SettingsRepository;
use App\Enums\GlobalPermissions; use App\Enums\GlobalPermissions;
use App\Event\GetNotifications; use App\Event\GetNotifications;
use App\Session\Flash; use App\Session\FlashLevels;
final class BaseUrlCheck final class BaseUrlCheck
{ {
@ -57,7 +57,7 @@ final class BaseUrlCheck
(string)$baseUriWithRequest (string)$baseUriWithRequest
); );
$notification->body = implode(' ', $notificationBodyParts); $notification->body = implode(' ', $notificationBodyParts);
$notification->type = Flash::WARNING; $notification->type = FlashLevels::Warning->value;
$notification->actionLabel = __('System Settings'); $notification->actionLabel = __('System Settings');
$notification->actionUrl = $router->named('admin:settings:index'); $notification->actionUrl = $router->named('admin:settings:index');

View File

@ -8,7 +8,7 @@ use App\Entity\Api\Notification;
use App\Enums\GlobalPermissions; use App\Enums\GlobalPermissions;
use App\Environment; use App\Environment;
use App\Event\GetNotifications; use App\Event\GetNotifications;
use App\Session\Flash; use App\Session\FlashLevels;
final class ProfilerAdvisorCheck final class ProfilerAdvisorCheck
{ {
@ -39,7 +39,7 @@ final class ProfilerAdvisorCheck
'You can track the execution time and memory usage of any AzuraCast page or application ' . 'You can track the execution time and memory usage of any AzuraCast page or application ' .
'from the profiler page.', 'from the profiler page.',
); );
$notification->type = Flash::INFO; $notification->type = FlashLevels::Info->value;
$notification->actionLabel = __('Profiler Control Panel'); $notification->actionLabel = __('Profiler Control Panel');
$notification->actionUrl = '/?' . http_build_query( $notification->actionUrl = '/?' . http_build_query(
@ -58,7 +58,7 @@ final class ProfilerAdvisorCheck
'This can have an adverse impact on system performance. ' . 'This can have an adverse impact on system performance. ' .
'You should disable this when possible.' 'You should disable this when possible.'
); );
$notification->type = Flash::WARNING; $notification->type = FlashLevels::Warning->value;
$event->addNotification($notification); $event->addNotification($notification);
} }

View File

@ -8,7 +8,7 @@ use App\Entity;
use App\Enums\GlobalPermissions; use App\Enums\GlobalPermissions;
use App\Environment; use App\Environment;
use App\Event\GetNotifications; use App\Event\GetNotifications;
use App\Session\Flash; use App\Session\FlashLevels;
use Carbon\CarbonImmutable; use Carbon\CarbonImmutable;
final class RecentBackupCheck final class RecentBackupCheck
@ -48,7 +48,7 @@ final class RecentBackupCheck
$notification = new Entity\Api\Notification(); $notification = new Entity\Api\Notification();
$notification->title = __('Installation Not Recently Backed Up'); $notification->title = __('Installation Not Recently Backed Up');
$notification->body = __('This installation has not been backed up in the last two weeks.'); $notification->body = __('This installation has not been backed up in the last two weeks.');
$notification->type = Flash::INFO; $notification->type = FlashLevels::Info->value;
$router = $request->getRouter(); $router = $request->getRouter();
$notification->actionLabel = __('Backups'); $notification->actionLabel = __('Backups');

View File

@ -8,7 +8,7 @@ use App\Entity\Api\Notification;
use App\Enums\GlobalPermissions; use App\Enums\GlobalPermissions;
use App\Event\GetNotifications; use App\Event\GetNotifications;
use App\Service\ServiceControl; use App\Service\ServiceControl;
use App\Session\Flash; use App\Session\FlashLevels;
final class ServiceCheck final class ServiceCheck
{ {
@ -35,7 +35,7 @@ final class ServiceCheck
$notification->body = __( $notification->body = __(
'One of the essential services on this installation is not currently running. Visit the system administration and check the system logs to find the cause of this issue.' 'One of the essential services on this installation is not currently running. Visit the system administration and check the system logs to find the cause of this issue.'
); );
$notification->type = Flash::ERROR; $notification->type = FlashLevels::Error->value;
$router = $request->getRouter(); $router = $request->getRouter();

View File

@ -7,7 +7,7 @@ namespace App\Notification\Check;
use App\Entity; use App\Entity;
use App\Enums\GlobalPermissions; use App\Enums\GlobalPermissions;
use App\Event\GetNotifications; use App\Event\GetNotifications;
use App\Session\Flash; use App\Session\FlashLevels;
final class SyncTaskCheck final class SyncTaskCheck
{ {
@ -39,7 +39,7 @@ final class SyncTaskCheck
$notification->body = __( $notification->body = __(
'Routine synchronization is currently disabled. Make sure to re-enable it to resume routine maintenance tasks.' 'Routine synchronization is currently disabled. Make sure to re-enable it to resume routine maintenance tasks.'
); );
$notification->type = Flash::ERROR; $notification->type = FlashLevels::Error->value;
// phpcs:enable // phpcs:enable
$event->addNotification($notification); $event->addNotification($notification);
@ -54,7 +54,7 @@ final class SyncTaskCheck
$notification->body = __( $notification->body = __(
'The routine synchronization task has not run recently. This may indicate an error with your installation.' 'The routine synchronization task has not run recently. This may indicate an error with your installation.'
); );
$notification->type = Flash::ERROR; $notification->type = FlashLevels::Error->value;
$router = $request->getRouter(); $router = $request->getRouter();

View File

@ -8,7 +8,7 @@ use App\Entity;
use App\Enums\GlobalPermissions; use App\Enums\GlobalPermissions;
use App\Enums\ReleaseChannel; use App\Enums\ReleaseChannel;
use App\Event\GetNotifications; use App\Event\GetNotifications;
use App\Session\Flash; use App\Session\FlashLevels;
use App\Version; use App\Version;
final class UpdateCheck final class UpdateCheck
@ -61,7 +61,7 @@ final class UpdateCheck
$notification = new Entity\Api\Notification(); $notification = new Entity\Api\Notification();
$notification->title = __('New AzuraCast Release Version Available'); $notification->title = __('New AzuraCast Release Version Available');
$notification->body = implode(' ', $notificationParts); $notification->body = implode(' ', $notificationParts);
$notification->type = Flash::INFO; $notification->type = FlashLevels::Info->value;
$notification->actionLabel = $actionLabel; $notification->actionLabel = $actionLabel;
$notification->actionUrl = $actionUrl; $notification->actionUrl = $actionUrl;
@ -86,7 +86,7 @@ final class UpdateCheck
$notification = new Entity\Api\Notification(); $notification = new Entity\Api\Notification();
$notification->title = __('New AzuraCast Updates Available'); $notification->title = __('New AzuraCast Updates Available');
$notification->body = implode(' ', $notificationParts); $notification->body = implode(' ', $notificationParts);
$notification->type = Flash::INFO; $notification->type = FlashLevels::Info->value;
$notification->actionLabel = $actionLabel; $notification->actionLabel = $actionLabel;
$notification->actionUrl = $actionUrl; $notification->actionUrl = $actionUrl;

View File

@ -13,11 +13,6 @@ final class Flash
{ {
public const SESSION_KEY = 'flash'; public const SESSION_KEY = 'flash';
public const SUCCESS = 'success';
public const WARNING = 'warning';
public const ERROR = 'danger';
public const INFO = 'info';
private ?array $messages = null; private ?array $messages = null;
public function __construct( public function __construct(
@ -25,43 +20,42 @@ final class Flash
) { ) {
} }
/** public function success(
* Alias of addMessage. string $message,
* bool $saveInSession = true
* @param string $message ): void {
* @param string $level $this->addMessage($message, FlashLevels::Success, $saveInSession);
* @param bool $saveInSession
*/
public function alert(string $message, string $level = self::INFO, bool $saveInSession = true): void
{
$this->addMessage($message, $level, $saveInSession);
} }
/** public function warning(
* Add a message to the flash message queue. string $message,
* bool $saveInSession = true
* @param string $message ): void {
* @param string $level $this->addMessage($message, FlashLevels::Warning, $saveInSession);
* @param bool $saveInSession }
*/
public function addMessage(string $message, string $level = self::INFO, bool $saveInSession = true): void
{
$colorChart = [
'green' => self::SUCCESS,
'success' => self::SUCCESS,
'yellow' => self::WARNING,
'warning' => self::WARNING,
'red' => self::ERROR,
'error' => self::ERROR,
'danger' => self::ERROR,
'info' => self::INFO,
'blue' => self::INFO,
'default' => '',
];
public function error(
string $message,
bool $saveInSession = true
): void {
$this->addMessage($message, FlashLevels::Error, $saveInSession);
}
public function info(
string $message,
bool $saveInSession = true
): void {
$this->addMessage($message, FlashLevels::Info, $saveInSession);
}
public function addMessage(
string $message,
FlashLevels $level = FlashLevels::Info,
bool $saveInSession = true
): void {
$messageRow = [ $messageRow = [
'text' => $message, 'text' => $message,
'color' => $colorChart[$level] ?? $level, 'color' => $level->value,
]; ];
$this->getMessages(); $this->getMessages();

View File

@ -0,0 +1,13 @@
<?php
declare(strict_types=1);
namespace App\Session;
enum FlashLevels: string
{
case Success = 'success';
case Warning = 'warning';
case Error = 'danger';
case Info = 'info';
}