Files
boursecu_server/app/Models/Cnt.php
T

76 lines
1.8 KiB
PHP
Raw Normal View History

2026-01-24 14:03:11 +00:00
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
2026-06-30 21:44:39 +03:30
use Illuminate\Support\Facades\Schema;
2026-01-24 14:03:11 +00:00
class Cnt extends Model
{
use HasFactory;
2026-06-30 21:44:39 +03:30
private static ?bool $valueJsonColumnExists = null;
2026-01-24 14:03:11 +00:00
protected $table = 'const';
2026-06-30 21:44:39 +03:30
2026-01-24 14:03:11 +00:00
protected $fillable = [
'key',
'title_fa',
'value',
2026-06-30 21:44:39 +03:30
'value_json',
2026-01-24 14:03:11 +00:00
];
2026-06-30 21:44:39 +03:30
2026-01-24 14:03:11 +00:00
protected $casts = [
2026-06-30 21:44:39 +03:30
'value_json' => 'array',
2026-01-24 14:03:11 +00:00
];
2026-06-30 21:44:39 +03:30
public static function hasValueJsonColumn(): bool
{
if (static::$valueJsonColumnExists !== null) {
return static::$valueJsonColumnExists;
}
try {
static::$valueJsonColumnExists = Schema::hasColumn((new static)->getTable(), 'value_json');
} catch (\Throwable) {
static::$valueJsonColumnExists = false;
}
return static::$valueJsonColumnExists;
}
public function jsonPayload(): array
{
if (static::hasValueJsonColumn() && is_array($this->value_json)) {
return $this->value_json;
}
$raw = $this->value ?? '';
if ($raw === '' || $raw === null) {
return [];
}
$decoded = json_decode((string) $raw, true);
return is_array($decoded) ? $decoded : [];
}
public static function saveJsonPayload(string $key, array $payload, ?string $titleFa = null): self
{
$data = [];
if ($titleFa !== null) {
$data['title_fa'] = $titleFa;
}
if (static::hasValueJsonColumn()) {
$data['value_json'] = $payload;
} else {
$data['value'] = json_encode($payload, JSON_UNESCAPED_UNICODE);
}
return static::updateOrCreate(['key' => $key], $data);
}
2026-01-24 14:03:11 +00:00
}