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

235 lines
8.0 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 = 'default';
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 = [];
protected function __construct()
{
parent::__construct();
$this->allowedFields = ['updated_at', 'created_at'];
$this->validationRules = [];
}
abstract public function getEntity($uid): BaseEntity;
abstract public function getEntitys($where): array;
protected function getFields(array $fields = array(), array $skips = array()): array
{
// echo var_export($fields, true);
// echo "<HR>";
//allowedFields에서 추가했으므로 Controller에는 적용되지 않게하기위함
$skips = ['updated_at', 'created_at', ...$skips];
$tempFields = array();
foreach ($fields as $key => $field) {
in_array($field, $skips) ?: array_push($tempFields, $field);
}
// echo var_export($tempFields, true);
// exit;
return $tempFields;
}
protected function getFieldFilters(array $fields = array(), array $skips = array()): array
{
//allowedFields에서 추가했으므로 Controller에는 적용되지 않게하기위함
$skips = ['updated_at', 'created_at', ...$skips];
$tempFields = array();
foreach ($fields as $field) {
if (!in_array($field, $skips)) {
array_push($tempFields, $field);
}
}
return $tempFields;
}
protected function getFieldRule(string $field, array $rules): array
{
switch ($field) {
case 'user_uid':
$rules[$field] = 'if_exist|regex_match[/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/]';
break;
case 'passwd':
$rules[$field] = 'if_exist|string';
$rules['confirmpassword'] = 'if_exist|string|matches[passwd]';
break;
case 'view_cnt':
$rules[$field] = 'if_exist|numeric';
break;
case 'updated_at':
case 'created_at':
case 'deleted_at':
$rules[$field] = 'if_exist|valid_date';
break;
default:
$rules[$field] = 'if_exist|string';
break;
}
return $rules;
}
final public function getFieldRules(array $fields, array $rules = array()): array
{
foreach ($fields as $field) {
$rules = $this->getFieldRule($field, $rules);
}
return $rules;
}
final public function getPrimaryKey()
{
return $this->primaryKey;
}
final public function getFieldFormOptions($where, $options = array()): array
{
foreach ($this->getEntitys($where) as $entity) {
$options[$entity->getPrimaryKey()] = $entity->getTitle();
}
return $options;
}
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)
);
}
//View관련 (게시판등의 조회수 증가함수)
final public function increaseViewCount($uid, string $field = 'view_cnt', int $cnt = 1)
{
//escape -> false옵션 반드시 있어야함
$this->builder()->set($field, "{$field}+{$cnt}", false);
$this->builder()->where($this->primaryKey, $uid);
$this->builder()->update();
}
//create , modify 직전 작업용 작업
protected function changeFormData(string $field, array $formDatas, $entity)
{
switch ($field) {
case $this->primaryKey:
//primaryKey가 자동입력이 아니면
if (!$this->useAutoIncrement) {
$pk = $this->primaryKey;
$entity->$pk = $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));
}
//primaryKey가 자동입력이면
if ($this->useAutoIncrement) {
$pk = $this->primaryKey;
$entity->$pk = $this->insertID();
}
} else {
throw new \Exception(__FUNCTION__ . " 오류 발생.\n 기존정보와 동일하여 수정되지 않았습니다.");
}
return $entity;
}
protected function create_process($entity, array $formDatas)
{
// echo var_export($this->allowedFields, true);
// exit;
foreach ($this->allowedFields as $field) {
$entity = $this->changeFormData($field, $formDatas, $entity);
}
return $this->save_process($entity);
}
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);
}
//Index관련
protected function setIndexWordFilter(string $word)
{
}
protected function setIndexDateFilterTrit($start, $end)
{
$this->where('created_at >=', $start);
$this->where('created_at <=', $end);
}
protected function setIndexOrderBy($field, $order = 'ASC')
{
$this->orderBy($field, $order);
}
}