Cleans up error/notice messages

main
Yasen Pramatarov 2024-11-11 11:33:02 +02:00
parent 96de30f3e0
commit c5e123ea2f
2 changed files with 36 additions and 15 deletions

View File

@ -1,5 +1,16 @@
<?php <?php
/**
* Generate an error or notice message based on the environment.
*
* In a production environment, hides detailed error messages and returns
* a generic message. In other environments, returns the provided message.
*
* @param string $message A user-friendly message to display.
* @param string $error The detailed error message for debugging (optional).
* @param string|null $environment The environment type ('production', 'development', etc.). If null, defaults to the configured environment.
* @return string The appropriate message based on the environment.
*/
function getError($message, $error = '', $environment = null) { function getError($message, $error = '', $environment = null) {
global $config; global $config;
$environment = $config['environment'] ?? 'production'; $environment = $config['environment'] ?? 'production';
@ -11,4 +22,20 @@ function getError($message, $error = '', $environment = null) {
} }
} }
/**
* Render a message if it exists, and optionally unset it after display.
*
* @param string $message The message to display.
* @param string $type The type of message (e.g., 'error', 'notice').
* @param bool $unset Whether to unset the message after display.
*/
function renderMessage(&$message, $type, $unset = false) {
if (isset($message)) {
echo "\t\t<div class=\"{$type}\">" . $message . "</div>\n";
if ($unset) {
$message = null;
}
}
}
?> ?>

View File

@ -1,24 +1,18 @@
<?php <?php
// 'error' for errors // Display and clean up session messages
if (isset($_SESSION['error'])) { foreach (['error', 'notice'] as $type) {
echo "\t\t" . '<div class="error">' . $_SESSION['error'] . '</div>'; if (isset($_SESSION[$type])) {
renderMessage($_SESSION[$type], $type, true);
}
} }
// 'notice' for all non-critical messages // Display standalone messages
if (isset($_SESSION['notice'])) {
echo "\t\t" . '<div class="notice">' . $_SESSION['notice'] . '</div>';
}
// 'error' for errors
if (isset($error)) { if (isset($error)) {
echo "\t\t" . '<div class="error">' . $error . '</div>'; renderMessage($error, 'error', true);
} }
// 'notice' for all non-critical messages if (isset($notice)) {
if (isset($_SESSION['notice'])) { renderMessage($notice, 'notice', true);
echo "\t\t" . '<div class="notice">' . $_SESSION['notice'] . '</div>';
} }
?> ?>