feat: complete admin CMS for customizable layout, texts, products, categories and orders
This commit is contained in:
+36
-4
@@ -3,6 +3,7 @@
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Throwable;
|
||||
|
||||
class Setting extends Model
|
||||
{
|
||||
@@ -17,23 +18,50 @@ class Setting extends Model
|
||||
'value',
|
||||
];
|
||||
|
||||
/**
|
||||
* @var array<string, mixed>|null
|
||||
*/
|
||||
protected static ?array $runtimeCache = null;
|
||||
|
||||
public static function flushCache(): void
|
||||
{
|
||||
static::$runtimeCache = null;
|
||||
}
|
||||
|
||||
public static function get(string $key, mixed $default = null): mixed
|
||||
{
|
||||
$setting = static::query()->find($key);
|
||||
if (static::$runtimeCache === null) {
|
||||
try {
|
||||
static::$runtimeCache = static::query()->pluck('value', 'key')->all();
|
||||
} catch (Throwable) {
|
||||
return $default;
|
||||
}
|
||||
}
|
||||
|
||||
if (! $setting || $setting->value === null) {
|
||||
if (! array_key_exists($key, static::$runtimeCache) || static::$runtimeCache[$key] === null) {
|
||||
return $default;
|
||||
}
|
||||
|
||||
$decoded = json_decode($setting->value, true);
|
||||
$val = static::$runtimeCache[$key];
|
||||
|
||||
return (json_last_error() === JSON_ERROR_NONE) ? $decoded : $setting->value;
|
||||
if (is_string($val) && (str_starts_with($val, '{') || str_starts_with($val, '['))) {
|
||||
$decoded = json_decode($val, true);
|
||||
if (json_last_error() === JSON_ERROR_NONE) {
|
||||
return $decoded;
|
||||
}
|
||||
}
|
||||
|
||||
return $val;
|
||||
}
|
||||
|
||||
public static function set(string $key, mixed $value): static
|
||||
{
|
||||
$encoded = is_array($value) || is_object($value) ? json_encode($value) : (string) $value;
|
||||
|
||||
if (static::$runtimeCache !== null) {
|
||||
static::$runtimeCache[$key] = $encoded;
|
||||
}
|
||||
|
||||
return static::query()->updateOrCreate(
|
||||
['key' => $key],
|
||||
['value' => $encoded]
|
||||
@@ -42,6 +70,10 @@ class Setting extends Model
|
||||
|
||||
public static function forget(string $key): bool
|
||||
{
|
||||
if (static::$runtimeCache !== null) {
|
||||
unset(static::$runtimeCache[$key]);
|
||||
}
|
||||
|
||||
return (bool) static::query()->where('key', $key)->delete();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user