104 lines
3.2 KiB
PHP
Executable File
104 lines
3.2 KiB
PHP
Executable File
<?php
|
|
|
|
if (!function_exists('userSetting')) {
|
|
/**
|
|
* Ottiene un'impostazione utente
|
|
*
|
|
* @param string $key
|
|
* @param mixed $default
|
|
* @return mixed
|
|
*/
|
|
function userSetting($key, $default = null)
|
|
{
|
|
if (!auth()->check()) {
|
|
return $default;
|
|
}
|
|
|
|
$user = auth()->user();
|
|
$decodeIfNeeded = function ($val) use ($default) {
|
|
// Mirror model logic: if caller passes array/object default, attempt JSON decode
|
|
if (is_array($default) || is_object($default)) {
|
|
if (is_string($val) && $val !== '') {
|
|
$decoded = json_decode($val, true);
|
|
if (json_last_error() === JSON_ERROR_NONE) {
|
|
return $decoded;
|
|
}
|
|
}
|
|
return is_array($val) ? $val : $default;
|
|
}
|
|
// Best-effort decode when default is null and value looks like JSON
|
|
if ($default === null && is_string($val) && $val !== '') {
|
|
$first = $val[0];
|
|
if ($first === '{' || $first === '[') {
|
|
$decoded = json_decode($val, true);
|
|
if (json_last_error() === JSON_ERROR_NONE) {
|
|
return $decoded;
|
|
}
|
|
}
|
|
}
|
|
return $val;
|
|
};
|
|
|
|
// Se l'utente ha un campo settings
|
|
if (isset($user->settings) && is_array($user->settings)) {
|
|
$val = $user->settings[$key] ?? $default;
|
|
return $decodeIfNeeded($val);
|
|
}
|
|
|
|
// Se l'utente ha una relazione settings
|
|
if (method_exists($user, 'settings')) {
|
|
$setting = $user->settings()->where('key', $key)->first();
|
|
if (!$setting) { return $default; }
|
|
return $decodeIfNeeded($setting->value);
|
|
}
|
|
|
|
return $default;
|
|
}
|
|
}
|
|
|
|
if (!function_exists('setUserSetting')) {
|
|
/**
|
|
* Imposta un'impostazione utente
|
|
*
|
|
* @param string $key
|
|
* @param mixed $value
|
|
* @return bool
|
|
*/
|
|
function setUserSetting($key, $value)
|
|
{
|
|
if (!auth()->check()) {
|
|
return false;
|
|
}
|
|
|
|
$user = auth()->user();
|
|
// Normalize structured values to JSON for storage
|
|
if (is_array($value) || is_object($value)) {
|
|
$stored = json_encode($value, JSON_UNESCAPED_UNICODE);
|
|
} elseif (is_bool($value)) {
|
|
$stored = $value ? 'true' : 'false';
|
|
} elseif (is_null($value)) {
|
|
$stored = null;
|
|
} else {
|
|
$stored = (string) $value;
|
|
}
|
|
|
|
// Se l'utente ha un campo settings
|
|
if (isset($user->settings)) {
|
|
$settings = is_array($user->settings) ? $user->settings : [];
|
|
$settings[$key] = $stored;
|
|
$user->settings = $settings;
|
|
return $user->save();
|
|
}
|
|
|
|
// Se l'utente ha una relazione settings
|
|
if (method_exists($user, 'settings')) {
|
|
return $user->settings()->updateOrCreate(
|
|
['key' => $key],
|
|
['value' => $stored]
|
|
);
|
|
}
|
|
|
|
return false;
|
|
}
|
|
}
|