chartboard/app/Models/SettingsModel.php
2026-03-30 09:51:33 +05:30

84 lines
2.3 KiB
PHP

<?php
namespace App\Models;
use CodeIgniter\Model;
class SettingsModel extends Model
{
protected $table = 'settings';
protected $primaryKey = 'id';
protected $useAutoIncrement = true;
protected $returnType = 'array';
protected $useSoftDeletes = false;
protected $protectFields = true;
protected $allowedFields = [
'workspace_id',
'key',
'value',
'type',
];
protected $useTimestamps = true;
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
public function getValue(?int $workspaceId, string $key, ?string $default = null): ?string
{
$b = $this->builder()->where('key', $key);
if ($workspaceId === null) {
$b->where('workspace_id IS NULL', null, false);
} else {
$b->where('workspace_id', $workspaceId);
}
$row = $b->get()->getRowArray();
return $row ? (string) $row['value'] : $default;
}
public function getBoolean(?int $workspaceId, string $key, bool $default = false): bool
{
$v = $this->getValue($workspaceId, $key, null);
if ($v === null) {
return $default;
}
return in_array(strtolower($v), ['1', 'true', 'yes', 'on'], true);
}
public function getInt(?int $workspaceId, string $key, int $default = 0): int
{
$v = $this->getValue($workspaceId, $key, null);
if ($v === null || ! is_numeric($v)) {
return $default;
}
return (int) $v;
}
public function setValue(?int $workspaceId, string $key, string $value, string $type = 'string'): bool
{
$b = $this->builder()->where('key', $key);
if ($workspaceId === null) {
$b->where('workspace_id IS NULL', null, false);
} else {
$b->where('workspace_id', $workspaceId);
}
$row = $b->get()->getRowArray();
if ($row) {
return $this->update((int) $row['id'], [
'value' => $value,
'type' => $type,
]);
}
return (bool) $this->insert([
'workspace_id' => $workspaceId,
'key' => $key,
'value' => $value,
'type' => $type,
]);
}
}