Files
chat/backend/app/model/Role.php
T
2026-07-22 10:18:59 +08:00

59 lines
1.4 KiB
PHP

<?php
namespace app\model;
use app\service\PermissionCatalog;
use think\Model;
class Role extends Model
{
protected $name = 'roles';
protected $autoWriteTimestamp = true;
protected $createTime = 'created_at';
protected $updateTime = 'updated_at';
public static function defaultPermissions(): array
{
return PermissionCatalog::emptyPermissions();
}
public function getPermissionsAttr($value): array
{
return PermissionCatalog::normalize(self::toPermArray($value));
}
public function setPermissionsAttr($value): string
{
return json_encode(
PermissionCatalog::normalize(self::toPermArray($value)),
JSON_UNESCAPED_UNICODE
);
}
/**
* ThinkPHP 8 会把 JSON 列转成 \think\model\type\Json,需调用 value() 取出数组。
*/
private static function toPermArray(mixed $value): array
{
if ($value === null || $value === '') {
return [];
}
if (is_array($value)) {
return $value;
}
if (is_object($value) && method_exists($value, 'value')) {
$data = $value->value();
return is_array($data) ? $data : [];
}
if (is_string($value)) {
$decoded = json_decode($value, true);
return (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) ? $decoded : [];
}
return [];
}
}