servermgrv2/app/Models/BaseModel.php
최준흠git config git config --helpgit config --global user.name 최준흠 b3659ee820 servermgrv2 init...
2023-07-22 23:19:44 +09:00

179 lines
6.2 KiB
PHP

<?php
namespace App\Models;
use CodeIgniter\Model;
use App\Libraries\Log\Log;
use App\Entities\BaseEntity;
abstract class BaseModel extends Model
{
protected $DBGroup = 'default';
// protected $table = 'user';
protected $primaryKey = 'uid';
protected $useAutoIncrement = true;
protected $insertID = 0;
protected $returnType = 'array'; //object,array,entity명::class
protected $useSoftDeletes = false;
protected $protectFields = true;
protected $allowedFields = [];
// Dates
protected $useTimestamps = true;
protected $dateFormat = 'datetime';
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
protected $deletedField = 'deleted_at';
protected $validationRules = [];
protected $validationMessages = [];
protected $skipValidation = false;
protected $cleanValidationRules = true;
// Callbacks
protected $allowCallbacks = true;
protected $beforeInsert = [];
protected $afterInsert = [];
protected $beforeUpdate = [];
protected $afterUpdate = [];
protected $beforeFind = [];
protected $afterFind = [];
protected $beforeDelete = [];
protected $afterDelete = [];
abstract public function getEntityByField($field, $value): ?BaseEntity;
abstract public function getEntity($uid): ?BaseEntity;
abstract public function getFieldFormOptions(): array;
final public function getUUID()
{
$randomBytes = bin2hex(random_bytes(16));
return sprintf(
"%s-%s-%s-%s-%s",
substr($randomBytes, 0, 8),
substr($randomBytes, 8, 4),
substr($randomBytes, 12, 4),
substr($randomBytes, 16, 4),
substr($randomBytes, 20)
);
}
//계층형구조구현
final protected function create_hierarchy($entity)
{
//생성시는 grpno가 primarykey와 같음
//escape -> false옵션 반드시 있어야함
$this->builder()->set('grpno', $entity->getPrimaryKey(), false);
$this->builder()->where($this->primaryKey, $entity->getPrimaryKey());
$this->builder()->update();
return $entity;
}
final protected function reply_hierarchy($entity, $parent_entity)
{
//부모의 그룹과 grpno가 같고, 부모의 grporder보다 1 큰것을 grporder+1을 해서 update
//escape -> false옵션 반드시 있어야함
$this->builder()->set('grporder', 'grporder+1', false);
$this->builder()->where([
'grpno' => $parent_entity->grpno,
'grporder >' => $parent_entity->grporder
]);
$this->builder()->update();
//reply용 설정
$entity->grpno = $parent_entity->grpno;
$entity->grporder = $parent_entity->grporder + 1;
$entity->grpdepth = $parent_entity->grpdepth + 1;
return $entity;
}
protected function changeFormData($field, array $formDatas, $entity)
{
switch ($field) {
case $this->primaryKey:
if (!$this->useAutoIncrement) {
$entity->$field = $this->getUUID();
}
break;
case 'user_uid':
if (array_key_exists($field, $formDatas) && $formDatas[$field]) {
$entity->$field = $formDatas[$field];
} elseif (session()->get(SESSION_NAMES['ISLOGIN'])) {
$auth = session()->get(SESSION_NAMES['AUTH']);
$entity->$field = $auth[AUTH_FIELDS['ID']];
}
break;
case 'passwd':
if (array_key_exists($field, $formDatas) && $formDatas[$field]) {
$entity->$field = password_hash($formDatas[$field], PASSWORD_DEFAULT);
}
break;
case 'content':
if (array_key_exists($field, $formDatas) && $formDatas[$field]) {
$entity->$field = htmlentities($formDatas[$field]);
}
break;
default:
if (array_key_exists($field, $formDatas) && $formDatas[$field]) {
$entity->$field = $formDatas[$field];
}
break;
}
return $entity;
}
private function save_process($entity)
{
if ($entity->hasChanged()) {
if (!$this->save($entity)) {
Log::add("error", __FUNCTION__ . "에서 호출:" . $this->getLastQuery());
Log::add("error", implode("\n", $this->errors()));
throw new \Exception(__FUNCTION__ . " 오류 발생.\n" . var_export($this->errors(), true));
}
} else {
throw new \Exception(__FUNCTION__ . " 오류 발생.\n 기존정보와 동일하여 수정되지 않았습니다.");
}
return $entity;
}
final protected function create_process($entity, array $formDatas)
{
foreach ($this->allowedFields as $field) {
$entity = $this->changeFormData($field, $formDatas, $entity);
}
return $this->save_process($entity);
}
final protected function modify_process($entity, array $formDatas)
{
foreach ($this->allowedFields as $field) {
if ($field != $this->primaryKey) {
$entity = $this->changeFormData($field, $formDatas, $entity);
}
}
$entity->updated_at = time();
return $this->save_process($entity);
}
//View관련 (게시판등의 조회수 증가함수)
final public function increaseViewCount($uid, $field = 'view_cnt', int $cnt = 1)
{
//escape -> false옵션 반드시 있어야함
$this->builder()->set($field, "{$field}+{$cnt}", false);
$this->builder()->where($this->primaryKey, $uid);
$this->builder()->update();
// echo $this->getLastQuery();
// exit;
}
//Index관련
public function setIndexWordFilter(string $word)
{
}
public function setIndexDateFilterTrit($start, $end)
{
$this->where('created_at >=', $start);
$this->where('created_at <=', $end);
}
public function setIndexOrderBy($field, $order = 'ASC')
{
$this->orderBy($field, $order);
}
}