first&last
This commit is contained in:
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class Setting extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
protected $fillable = [
|
||||
'key',
|
||||
'value',
|
||||
'type',
|
||||
];
|
||||
|
||||
public static function getValue(string $key, mixed $default = null): mixed
|
||||
{
|
||||
$setting = static::query()->where('key', $key)->first();
|
||||
|
||||
if (!$setting) {
|
||||
return $default;
|
||||
}
|
||||
|
||||
return $setting->castValue();
|
||||
}
|
||||
|
||||
public static function setValue(string $key, mixed $value, string $type = 'string'): self
|
||||
{
|
||||
return static::query()->updateOrCreate(
|
||||
['key' => $key],
|
||||
['value' => static::serializeValue($value, $type), 'type' => $type]
|
||||
);
|
||||
}
|
||||
|
||||
public function castValue(): mixed
|
||||
{
|
||||
return match ($this->type) {
|
||||
'integer' => (int) $this->value,
|
||||
'boolean' => filter_var($this->value, FILTER_VALIDATE_BOOLEAN),
|
||||
'json' => $this->value ? json_decode($this->value, true, 512, JSON_THROW_ON_ERROR) : [],
|
||||
default => $this->value,
|
||||
};
|
||||
}
|
||||
|
||||
private static function serializeValue(mixed $value, string $type): ?string
|
||||
{
|
||||
if ($value === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return match ($type) {
|
||||
'json' => json_encode($value, JSON_THROW_ON_ERROR),
|
||||
'boolean' => $value ? '1' : '0',
|
||||
default => (string) $value,
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user