trafficmonitor/app/Entities/UserEntity.php

75 lines
2.5 KiB
PHP

<?php
namespace App\Entities;
use App\Entities\CommonEntity;
use App\Models\UserModel as Model;
use CodeIgniter\Entity\Entity; // Entity 클래스를 명시적으로 use 하는 것이 좋습니다.
class UserEntity extends CommonEntity
{
const PK = Model::PK;
const TITLE = Model::TITLE;
const DEFAULT_STATUS = STATUS['AVAILABLE'];
/**
* @var array Entity 속성을 DB에 저장하거나 DB에서 로드할 때의 형 변환 규칙
*/
protected $casts = [
// 'role' 컬럼에 배열을 할당하면 DB에 JSON 문자열로 저장되며,
// DB에서 로드할 때 JSON 문자열이 자동으로 PHP 배열로 변환됩니다.
'role' => 'json-array',
];
public function getID(): string
{
return (string) $this->attributes['id'];
}
public function getPassword(): string
{
return $this->attributes['passwd'];
}
// $formDatas['passwd']에 평문 비밀번호가 들어있으면,
// Model->insert시 Entity 생성자($formDatas)가 setPasswd()를 자동으로 호출합니다.
public function setPasswd(string $password)
{
// 비밀번호를 암호화하여 저장합니다.
$this->attributes['passwd'] = password_hash($password, PASSWORD_BCRYPT);
}
/**
* 사용자의 역할을 배열 형태로 반환합니다.
* $casts에 의해 DB에서 읽어올 때 이미 배열로 변환될 것을 기대합니다.
* @return array
*/
public function getRole(): array
{
$role = $this->attributes['role'] ?? [];
// 1. $casts가 성공적으로 작동했거나, 이미 배열인 경우 바로 반환합니다.
if (is_array($role)) {
return $role;
}
// 2. 캐스팅에 실패했으나 원본이 문자열로 남아있는 경우 (JSON 또는 CSV)
if (is_string($role) && !empty($role)) {
// 2-a. JSON 디코딩을 시도합니다.
$decodedRole = json_decode($role, true);
if (json_last_error() === JSON_ERROR_NONE && is_array($decodedRole)) {
return $decodedRole; // 유효한 JSON 배열인 경우
}
// 2-b. JSON이 아니면 레거시 CSV 형식이라고 가정하고 explode로 변환합니다.
if (defined('DEFAULTS') && isset(DEFAULTS['DELIMITER_ROLE'])) {
return explode(DEFAULTS['DELIMITER_ROLE'], $role);
}
}
// 3. 변환에 실패했거나 데이터가 없는 경우 빈 배열 반환
return [];
}
}