netgescon-day0/app/Models/SystemSetting.php

65 lines
1.5 KiB
PHP
Executable File

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Throwable;
class SystemSetting extends Model
{
protected $fillable = [
'key',
'value',
];
public static function getValue(string $key, mixed $default = null): mixed
{
if (! static::settingsTableExists()) {
return $default;
}
try {
$setting = static::query()->where('key', $key)->value('value');
} catch (Throwable) {
return $default;
}
if ($setting === null) {
return $default;
}
$decoded = json_decode($setting, true);
return json_last_error() === JSON_ERROR_NONE ? $decoded : $setting;
}
public static function setValue(string $key, mixed $value): void
{
if (! static::settingsTableExists()) {
return;
}
$storedValue = is_string($value) ? $value : json_encode($value);
static::query()->updateOrCreate(
['key' => $key],
['value' => $storedValue]
);
}
public static function bool(string $key, bool $default = false): bool
{
return filter_var(static::getValue($key, $default), FILTER_VALIDATE_BOOL);
}
protected static function settingsTableExists(): bool
{
try {
$model = new static();
return $model->getConnection()->getSchemaBuilder()->hasTable($model->getTable());
} catch (Throwable) {
return false;
}
}
}