From 25a1fc0c376b907ad660e032c0392934e81ae037 Mon Sep 17 00:00:00 2001 From: marcoc Date: Tue, 18 Feb 2025 16:06:56 +0100 Subject: [PATCH] feat(preferences): added preferences model and helper to get and set them --- app/Helpers/Preferences.php | 99 +++++++++++++++++++++++++++++++++++++ app/Models/Preference.php | 23 +++++++++ 2 files changed, 122 insertions(+) create mode 100644 app/Helpers/Preferences.php create mode 100644 app/Models/Preference.php diff --git a/app/Helpers/Preferences.php b/app/Helpers/Preferences.php new file mode 100644 index 0000000..d9323af --- /dev/null +++ b/app/Helpers/Preferences.php @@ -0,0 +1,99 @@ +where('subjid', $userId); + } + + if ($pref->count() > 0) { + $pref->valstr = $value; + } else { + if ($isUserValue) { + throw new Exception("Preference {$key} not found for user {$userId}."); + } + throw new Exception("Preference {$key} not found."); + } + + } catch (Exception $e) { + header('HTTP/1.0 503 Service Unavailable'); + Log::info('Database error: ' . $e->getMessage()); + } + } + + private function getValue($key, $isUserValue = false, $forceDefault = false) { + try { + $userId = Auth::id(); + + if ($isUserValue && is_null($userId)) { + throw new Exception("User id can't be null for a user preference {$key}."); + } + + $pref = Preference::where('key', $key); + if ($isUserValue) { + $pref = $pref->where('subjid', $userId); + } + + if ($pref->count() > 0) { + return $pref->first()->valstr; + } else { + if ($isUserValue) { + throw new Exception("Preference {$key} not found for user {$userId}."); + } + throw new Exception("Preference {$key} not found."); + } + + } catch (Exception $e) { + header('HTTP/1.0 503 Service Unavailable'); + Log::info('Database error: ' . $e->getMessage()); + die(); + } + } + + public function getDefaultTimeZone() { + return config('app.timezone'); + } + + public static function setUserTimezone($timezone = null) + { + self::setValue('user_timezone', $timezone, true); + } + + public static function getUserTimezone() + { + $timezone = self::getValue('user_timezone', true); + if (!$timezone) { + return self::getDefaultTimezone(); + } + + return $timezone; + } + + // Always attempts to returns the current user's personal timezone setting + public static function getTimezone() + { + $userId = Auth::id(); + + if (!is_null($userId)) { + return self::getUserTimezone(); + } + + return self::getDefaultTimezone(); + } +} diff --git a/app/Models/Preference.php b/app/Models/Preference.php new file mode 100644 index 0000000..50a5ca6 --- /dev/null +++ b/app/Models/Preference.php @@ -0,0 +1,23 @@ +belongsTo(User::class, 'subjid'); + } +}