76 lines
1.8 KiB
PHP
76 lines
1.8 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Support\Facades\Schema;
|
|
|
|
class Cnt extends Model
|
|
{
|
|
use HasFactory;
|
|
|
|
private static ?bool $valueJsonColumnExists = null;
|
|
|
|
protected $table = 'const';
|
|
|
|
protected $fillable = [
|
|
'key',
|
|
'title_fa',
|
|
'value',
|
|
'value_json',
|
|
];
|
|
|
|
protected $casts = [
|
|
'value_json' => 'array',
|
|
];
|
|
|
|
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);
|
|
}
|
|
}
|