dbmsv4/app/Entities/UserEntity.php
2025-11-18 16:54:55 +09:00

87 lines
3.2 KiB
PHP

<?php
namespace App\Entities;
use App\Entities\CommonEntity;
use App\Models\UserModel as Model;
class UserEntity extends CommonEntity
{
const PK = Model::PK;
const TITLE = Model::TITLE;
/**
* @var array DB 컬럼 타입이 VARCHAR(255)이고 CSV 형식으로 통일하기 위해 json-array 캐스팅을 제거합니다.
*/
protected $casts = [
// 'role' => 'json-array', // 🚫 CSV 형식 저장을 위해 제거
];
public function getID(): string
{
return (string) $this->attributes['id'];
}
public function getPassword(): string
{
return $this->attributes['passwd'];
}
/**
* 사용자의 역할을 배열 형태로 반환합니다.
* DB의 JSON 또는 CSV 형식 데이터를 모두 배열로 복구할 수 있는 로직을 포함합니다.
* @return array
*/
public function getRole(): array
{
$role = $this->attributes['role'] ?? null;
// 1. 이미 배열인 경우 (방어적 코딩)
if (is_array($role)) {
return array_filter($role);
}
// 2. 문자열 데이터인 경우 처리
if (is_string($role) && !empty($role)) {
// 2-a. JSON 디코딩 시도 (기존 DB의 JSON 형식 처리)
$decodedRole = json_decode($role, true);
if (json_last_error() === JSON_ERROR_NONE && is_array($decodedRole)) {
return $decodedRole;
}
// 2-b. JSON이 아니면 CSV로 가정하고 변환
$parts = explode(',', $role);
// 각 요소의 불필요한 공백과 따옴표 제거
$cleanedRoles = array_map(fn($item) => trim($item, " \t\n\r\0\x0B\""), $parts);
return array_filter($cleanedRoles);
}
// 3. 변환에 실패했거나 데이터가 없는 경우 빈 배열 반환
return [];
}
// --- Setter Methods ---
public function setPasswd(string $password)
{
// 비밀번호를 암호화하여 저장합니다.
$this->attributes['passwd'] = password_hash($password, PASSWORD_BCRYPT);
}
/**
* Role 데이터가 Entity에 설정될 때 호출되어, 입력된 CSV/JSON 문자열을 정리 후
* DB에 적합한 CSV 문자열로 최종 저장합니다.
* @param mixed $role 입력 데이터 (문자열 또는 배열)
*/
public function setRole(mixed $role)
{
$roleArray = [];
if (is_string($role)) {
// 1. 양쪽의 불필요한 따옴표와 공백을 제거하여 깨끗한 문자열 확보
$cleanRoleString = trim($role, " \t\n\r\0\x0B\"");
if (!empty($cleanRoleString)) {
$role = explode(DEFAULTS["DELIMITER_ROLE"], $cleanRoleString);
}
}
if (is_array($role)) {
//배열에도 불필요한 따옴표와 공백을 제거
$cleanedRoles = array_map(fn($item) => trim($item, " \t\n\r\0\x0B\""), $role);
$roleArray = array_filter($cleanedRoles);
}
// 💡 핵심: 최종적으로 DB에 삽입될 단일 CSV 문자열로 변환하여 저장합니다.
$this->attributes['role'] = implode(DEFAULTS["DELIMITER_ROLE"], $roleArray);
}
}