dbms init...1

This commit is contained in:
최준흠 2025-04-29 16:56:58 +09:00
parent 8ec1a0ad77
commit 6b74bdc1e2
35 changed files with 776 additions and 825 deletions

View File

@ -314,4 +314,4 @@ define('LAYOUTS', [
]); ]);
//List의 Page당 갯수 //List의 Page당 갯수
define('DEFAULT_LIST_PERPAGE', $_ENV['LIST_PERPAGE'] ?? $_SERVER['LIST_PERPAGE'] ?? 20); define('DEFAULT_LIST_PERPAGE', $_ENV['LIST_PERPAGE'] ?? $_SERVER['LIST_PERPAGE'] ?? 20);

View File

@ -40,19 +40,4 @@ $routes->group('admin', ['namespace' => 'App\Controllers\Admin', 'filter' => 'au
$routes->get('/', 'MyLogController::index'); $routes->get('/', 'MyLogController::index');
$routes->get('view/(:num)', 'MyLogController::view/$1'); $routes->get('view/(:num)', 'MyLogController::view/$1');
}); });
$routes->group('cloudflare', ['namespace' => 'App\Controllers\Admin\Cloudflare', 'filter' => 'authFilter:cloudflare'], function ($routes) {
$routes->group('auth', ['namespace' => 'App\Controllers\Admin\Cloudflare'], function ($routes) {
$routes->get('/', 'AuthController::index');
$routes->get('create', 'AuthController::create_form');
$routes->post('create', 'AuthController::create');
$routes->get('modify/(:num)', 'AuthController::modify_form/$1');
$routes->post('modify/(:num)', 'AuthController::modify/$1');
$routes->get('view/(:num)', 'AuthController::view/$1');
$routes->get('delete/(:num)', 'AuthController::delete/$1');
$routes->get('toggle/(:num)/(:any)', 'AuthController::toggle/$1/$2');
// $routes->post('batchjob', 'AuthController::batchjob');
// $routes->post('batchjob_delete', 'AuthController::batchjob_delete');
$routes->get('download/(:alpha)', 'AccountController::download/$1');
});
});
}); });

View File

@ -7,83 +7,13 @@ use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface; use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use CodeIgniter\HTTP\RedirectResponse;
use App\Services\MyLogService;
abstract class AdminController extends CommonController abstract class AdminController extends CommonController
{ {
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger) public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{ {
parent::initController($request, $response, $logger); parent::initController($request, $response, $logger);
$this->layout = "admin"; $this->layout = "admin";
$this->uri_path = "admin/"; $this->uri_path = "admin" . DIRECTORY_SEPARATOR;
$this->view_path = "admin/"; $this->view_path = $this->uri_path;
}
//생성
protected function create_process_result($message): RedirectResponse|string
{
MyLogService::save($this->getService(), __FUNCTION__, $this->myauth, $message, DEFAULTS['STATUS']);
return parent::create_process_result($message);
}
protected function create_process_failed($message): RedirectResponse|string
{
MyLogService::save($this->getService(), __FUNCTION__, $this->myauth, $message);
return parent::create_process_failed($message);
}
//수정
protected function modify_process_result($message): RedirectResponse|string
{
MyLogService::save($this->getService(), __FUNCTION__, $this->myauth, $message, DEFAULTS['STATUS']);
return parent::modify_process_result($message);
}
protected function modify_process_failed($message): RedirectResponse|string
{
MyLogService::save($this->getService(), __FUNCTION__, $this->myauth, $message);
return parent::modify_process_failed($message);
}
//단일필드작업
protected function toggle_process_result($message): RedirectResponse|string
{
MyLogService::save($this->getService(), __FUNCTION__, $this->myauth, $message, DEFAULTS['STATUS']);
return parent::toggle_process_result($message);
}
protected function toggle_process_failed($message): RedirectResponse|string
{
MyLogService::save($this->getService(), __FUNCTION__, $this->myauth, $message);
return parent::toggle_process_failed($message);
}
//일괄처리작업
protected function batchjob_process_result($message): RedirectResponse|string
{
MyLogService::save($this->getService(), __FUNCTION__, $this->myauth, $message, DEFAULTS['STATUS']);
return parent::batchjob_process_result($message);
}
protected function batchjob_process_failed($message): RedirectResponse|string
{
MyLogService::save($this->getService(), __FUNCTION__, $this->myauth, $message);
return parent::batchjob_process_failed($message);
}
//삭제 delete,batchjob_delete 공통사용
protected function delete_process_result($message): RedirectResponse|string
{
MyLogService::save($this->getService(), __FUNCTION__, $this->myauth, $message, DEFAULTS['STATUS']);
return parent::delete_process_result($message);
}
protected function delete_process_failed($message): RedirectResponse|string
{
MyLogService::save($this->getService(), __FUNCTION__, $this->myauth, $message);
return parent::delete_process_failed($message);
}
//일괄삭제
protected function batchjob_delete_process_result($message): RedirectResponse|string
{
MyLogService::save($this->getService(), __FUNCTION__, $this->myauth, $message, DEFAULTS['STATUS']);
return parent::batchjob_delete_process_result($message);
}
protected function batchjob_delete_process_failed($message): RedirectResponse|string
{
MyLogService::save($this->getService(), __FUNCTION__, $this->myauth, $message);
return parent::batchjob_delete_process_failed($message);
} }
} }

View File

@ -6,27 +6,40 @@ use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface; use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use App\Helpers\CommonHelper; use App\Helpers\CommonHelper as Helper;
use App\Services\UserService; use App\Services\UserService as Service;
class Home extends AdminController class Home extends AdminController
{ {
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger) public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{ {
parent::initController($request, $response, $logger); parent::initController($request, $response, $logger);
$this->layout = "admin";
$this->uri_path = "admin/";
$this->view_path = "admin/";
$this->title = "관리자페이지 메인"; $this->title = "관리자페이지 메인";
$this->helper = new CommonHelper(); $this->helper = new Helper($this->request);
} }
protected function getService(): UserService protected function getServiceClass(): Service
{ {
if ($this->service === null) { if ($this->service === null) {
$this->service = new UserService(); $this->service = new Service($this->request);
} }
return $this->service; return $this->service;
} }
//Index,FieldForm관련
public function getFields(): array
{
return [];
}
public function getFilterFields(): array
{
return [];
}
public function getBatchJobFields(): array
{
return [];
}
//Index,FieldForm관련
public function index(): string public function index(): string
{ {
helper(['form']); helper(['form']);

View File

@ -2,44 +2,58 @@
namespace App\Controllers\Admin; namespace App\Controllers\Admin;
use App\Helpers\MyLogHelper;
use App\Services\MyLogService;
use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface; use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use App\Models\UserModel; use App\Helpers\MyLogHelper as Helper;
use App\Services\MyLogService as Service;
use App\Services\UserService;
class MyLogController extends AdminController class MyLogController extends AdminController
{ {
private $_userModel = null; private $_userService = null;
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger) public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{ {
parent::initController($request, $response, $logger); parent::initController($request, $response, $logger);
$this->uri_path .= strtolower($this->getService()->getClassName()) . DIRECTORY_SEPARATOR;
$this->view_path = $this->uri_path;
$this->title = lang("MyLog.title"); $this->title = lang("MyLog.title");
$this->helper = new MyLogHelper(); $this->helper = new Helper($this->request);
} }
protected function getService(): MyLogService protected function getServiceClass(): Service
{ {
if ($this->service === null) { if ($this->service === null) {
$this->service = new MyLogService(); $this->service = new Service($this->request);
$this->class_name = "MyLog";
$this->class_path = $this->class_name;
} }
return $this->service; return $this->service;
} }
public function getUserModel(): UserModel public function getUserService(): UserService
{ {
if ($this->_userModel === null) { if ($this->_userService === null) {
$this->_userModel = new UserModel(); $this->_userService = new UserService($this->request);
} }
return $this->_userModel; return $this->_userService;
}
//Index,FieldForm관련
public function getFields(): array
{
return ['class_name', 'method_name', $this->getService()->getModel()::TITLE, 'user_uid', 'status'];
}
public function getFilterFields(): array
{
return ['user_uid', 'status'];
}
public function getBatchJobFields(): array
{
return [];
} }
protected function getFormFieldOption(string $field, array $options = []): array protected function getFormFieldOption(string $field, array $options = []): array
{ {
switch ($field) { switch ($field) {
case 'user_uid': case 'user_uid':
// $this->getUserModel()->where('status', DEFAULTS['STATUS']); // $this->getUserModel()->where('status', DEFAULTS['STATUS']);
$options[$field] = $this->getUserModel()->getFormFieldOption($field); $options[$field] = $this->getUserService()->getFormFieldOption($field);
// echo $this->getUserModel()->getLastQuery(); // echo $this->getUserModel()->getLastQuery();
// dd($options); // dd($options);
break; break;
@ -49,6 +63,9 @@ class MyLogController extends AdminController
} }
return $options; return $options;
} }
//Index,FieldForm관련
//View관련 //View관련
protected function view_init(string $action, $fields = []): void protected function view_init(string $action, $fields = []): void
{ {

View File

@ -2,31 +2,44 @@
namespace App\Controllers\Admin; namespace App\Controllers\Admin;
use App\Helpers\UserHelper; use App\Helpers\UserHelper as Helper;
use App\Services\UserService; use App\Services\UserService as Service;
use CodeIgniter\HTTP\RedirectResponse;
use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface; use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Validation\Validation; use CodeIgniter\Validation\Validation;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
class UserController extends AdminController class UserController extends AdminController
{ {
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger) public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{ {
parent::initController($request, $response, $logger); parent::initController($request, $response, $logger);
$this->uri_path .= strtolower($this->getService()->getClassName()) . DIRECTORY_SEPARATOR;
$this->title = lang("{$this->getService()->getClassPath()}.title"); $this->title = lang("{$this->getService()->getClassPath()}.title");
$this->helper = new UserHelper(); $this->helper = new Helper($this->getService());
} }
protected function getService(): UserService protected function getServiceClass(): Service
{ {
if ($this->service === null) { if ($this->service === null) {
$this->service = new UserService(); $this->service = new Service($this->request);
$this->class_name = $this->service->getClassName();
$this->class_path = $this->service->getClassPath();
} }
return $this->service; return $this->service;
} }
//Index,FieldForm관련
public function getFields(): array
{
return ['id', $this->getService()->getModel()::TITLE, 'email', 'mobile', 'role', 'status'];
}
public function getFilterFields(): array
{
return ['role', 'status'];
}
public function getBatchJobFields(): array
{
return ['status'];
}
protected function setValidation(string $action, string $field, Validation $validation): Validation protected function setValidation(string $action, string $field, Validation $validation): Validation
{ {
switch ($field) { switch ($field) {
@ -40,20 +53,24 @@ class UserController extends AdminController
} }
return $validation; return $validation;
} }
//Index,FieldForm관련
//생성 //생성
protected function create_init(string $action, $fields = []): void protected function create_process(): mixed
{ {
$fields = [ $fields = [
'fields' => ['id', 'passwd', 'confirmpassword', $this->getService()->getModel()::TITLE, 'email', 'mobile', 'role'], 'fields' => ['id', 'passwd', 'confirmpassword', $this->getService()->getModel()::TITLE, 'email', 'mobile', 'role'],
]; ];
parent::create_init($action, fields: $fields); $this->init('create', $fields);
return parent::create_process();
} }
//수정 //수정
protected function modify_init(string $action, $fields = []): void protected function modify_process($uid): mixed
{ {
$fields = [ $fields = [
'fields' => ['id', 'passwd', 'confirmpassword', $this->getService()->getModel()::TITLE, 'email', 'mobile', 'role', 'status'], 'fields' => ['id', 'passwd', 'confirmpassword', $this->getService()->getModel()::TITLE, 'email', 'mobile', 'role', 'status'],
]; ];
parent::modify_init($action, $fields); $this->init('modify', $fields);
return parent::modify_process($uid);
} }
} }

View File

@ -3,21 +3,26 @@
namespace App\Controllers; namespace App\Controllers;
use App\Controllers\BaseController; use App\Controllers\BaseController;
use CodeIgniter\HTTP\DownloadResponse;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RedirectResponse;
use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface; use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
use CodeIgniter\HTTP\RedirectResponse;
use CodeIgniter\HTTP\DownloadResponse;
use CodeIgniter\Validation\Validation; use CodeIgniter\Validation\Validation;
use PhpOffice\PhpSpreadsheet\IOFactory; use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Reader\Html; use PhpOffice\PhpSpreadsheet\Reader\Html;
use PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf; use PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf;
use Psr\Log\LoggerInterface;
abstract class CommonController extends BaseController abstract class CommonController extends BaseController
{ {
private $_service = null;
private $_viewDatas = []; private $_viewDatas = [];
abstract protected function getService(): mixed; abstract protected function getServiceClass(): mixed;
abstract public function getFields(): array;
abstract public function getFilterFields(): array;
abstract public function getBatchJobFields(): array;
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger) public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{ {
parent::initController($request, $response, $logger); parent::initController($request, $response, $logger);
@ -34,11 +39,39 @@ abstract class CommonController extends BaseController
{ {
$this->_viewDatas[$name] = $value; $this->_viewDatas[$name] = $value;
} }
final public function getService(): mixed
{
if ($this->_service === null) {
$serviceClass = $this->getServiceClass();
$this->_service = new $serviceClass($this->request);
// $this->_service->setDebug(true);
}
return $this->_service;
}
final public function getViewDatas(): array final public function getViewDatas(): array
{ {
return $this->_viewDatas; return $this->_viewDatas;
} }
//Index,FieldForm관련
protected function getFieldRule(string $action, string $field): string
{
if (is_array($field)) {
throw new \Exception(__FUNCTION__ . "=> field가 array 입니다.\n" . var_export($field, true));
}
switch ($field) {
default:
$rule = $this->getService()->getFieldRule($action, $field);
break;
}
return $rule;
}
final protected function getFieldRules(string $action, array $fields, $rules = []): array
{
foreach ($fields as $field) {
$rules[$field] = $this->getFieldRule($action, $field);
}
return $rules;
}
protected function setValidation(string $action, string $field, Validation $validation): Validation protected function setValidation(string $action, string $field, Validation $validation): Validation
{ {
switch ($field) { switch ($field) {
@ -56,7 +89,6 @@ abstract class CommonController extends BaseController
} }
return $validation; return $validation;
} }
//Field별 Form Option용
protected function getFormFieldOption(string $field, array $options): array protected function getFormFieldOption(string $field, array $options): array
{ {
switch ($field) { switch ($field) {
@ -79,47 +111,20 @@ abstract class CommonController extends BaseController
// dd($options); // dd($options);
return $options; return $options;
} }
//Index,FieldForm관련
//Field관련 //Field관련
protected function init(string $action, array $fields = []): void protected function init(string $action, array $fields = []): void
{ {
$this->action = $action; $this->action = $action;
$this->fields = array_key_exists('fields', $fields) && is_array($fields['fields']) && count($fields['fields']) ? $fields['fields'] : $this->getService()->getFields(); $this->fields = array_key_exists('fields', $fields) && is_array($fields['fields']) && count($fields['fields']) ? $fields['fields'] : $this->getFields();
$this->field_rules = array_key_exists('field_rules', $fields) && is_array($fields['field_rules']) && count($fields['field_rules']) ? $fields['field_rules'] : $this->getService()->getFieldRules($this->action, $this->fields); $this->field_rules = array_key_exists('field_rules', $fields) && is_array($fields['field_rules']) && count($fields['field_rules']) ? $fields['field_rules'] : $this->getFieldRules($this->action, $this->fields);
$this->filter_fields = array_key_exists('filter_fields', $fields) && is_array($fields['filter_fields']) && count($fields['filter_fields']) ? $fields['filter_fields'] : $this->getService()->getFilterFields(); $this->filter_fields = array_key_exists('filter_fields', $fields) && is_array($fields['filter_fields']) && count($fields['filter_fields']) ? $fields['filter_fields'] : $this->getFilterFields();
$this->field_options = array_key_exists('field_options', $fields) && is_array($fields['field_optionss']) && count($fields['field_options']) ? $fields['field_options'] : $this->getFormFieldOptions($this->filter_fields); $this->field_options = array_key_exists('field_options', $fields) && is_array($fields['field_optionss']) && count($fields['field_options']) ? $fields['field_options'] : $this->getFormFieldOptions($this->filter_fields);
$this->batchjob_fields = array_key_exists('batchjob_fields', $fields) && is_array($fields['batchjob_fields']) && count($fields['batchjob_fields']) ? $fields['filter_fields'] : $this->getService()->getBatchJobFields(); $this->batchjob_fields = array_key_exists('batchjob_fields', $fields) && is_array($fields['batchjob_fields']) && count($fields['batchjob_fields']) ? $fields['filter_fields'] : $this->getBatchJobFields();
} }
// 생성 //데이터 검증
protected function create_init(string $action, $fields = []): void final protected function doValidate(string $action, array $fields): array
{
$this->init($action, $fields);
}
protected function create_form_process(): void {}
final public function create_form(): RedirectResponse|string
{
$this->create_init('create');
return $this->create_form_procedure();
}
protected function create_form_process_result(): string
{
return view(
$this->view_path . "create",
data: ['viewDatas' => $this->getViewDatas()]
);
}
final protected function create_form_procedure(): RedirectResponse|string
{
try {
helper(['form']);
$this->create_form_process();
$this->forms = ['attributes' => ['method' => "post",], 'hiddens' => []];
return $this->create_form_process_result();
} catch (\Exception $e) {
return redirect()->back()->with('error', $e->getMessage());
}
}
protected function create_validate(string $action, array $fields): array
{ {
//변경할 값 확인 : Upload된 파일 검증시 $this->request->getPOST()보다 먼처 체크필요 //변경할 값 확인 : Upload된 파일 검증시 $this->request->getPOST()보다 먼처 체크필요
$validation = $this->getValidation($action, $fields); $validation = $this->getValidation($action, $fields);
@ -131,170 +136,124 @@ abstract class CommonController extends BaseController
} }
return $validation->getValidated(); return $validation->getValidated();
} }
protected function create_process(): void
{
$this->formDatas = $this->create_validate($this->action, $this->fields);
$this->entity = $this->getService()->create($this->formDatas);
}
protected function create_process_result($message): RedirectResponse|string
{
$url = strtolower(base_url() . $this->uri_path . $this->getService()->getClassName()) . "/view/" . $this->entity->getPK();
return redirect()->to($url)->with('error', $message);
}
protected function create_process_failed($message): RedirectResponse|string
{
return redirect()->back()->withInput()->with('error', $message);
}
final protected function create_procedure(): RedirectResponse|string
{
//Transaction Start
$this->getService()->getModel()->transStart();
try {
helper(['form']);
$this->create_process();
$this->getService()->getModel()->transCommit();
return $this->create_process_result(MESSAGES["SUCCESS"]);
} catch (\Exception $e) {
//Transaction Rollback
$this->getService()->getModel()->transRollback();
return $this->create_process_result($e->getMessage());
}
}
final public function create(): RedirectResponse|string
{
$this->create_init(__FUNCTION__);
return $this->create_procedure();
}
//수정관련 // 생성
protected function modify_init(string $action, $fields = []): void protected function create_form_process(): void {}
{ public function create_form(): RedirectResponse|string
$this->init($action, $fields);
}
final public function modify_form(mixed $uid): RedirectResponse|string
{
$this->modify_init('modify');
return $this->modify_form_procedure($uid);
}
protected function modify_form_process(mixed $uid): void
{
$this->entity = $this->getService()->getModel()->getEntityByPK($uid);
if ($this->entity === null) {
throw new \Exception("해당 정보를 찾을수 없습니다.");
}
}
protected function modify_form_process_result(): string
{
return view(
$this->view_path . "modify",
data: ['viewDatas' => $this->getViewDatas()]
);
}
final protected function modify_form_procedure(mixed $uid): RedirectResponse|string
{ {
try { try {
$this->init('create');
helper(['form']); helper(['form']);
$this->modify_form_process($uid); $this->create_form_process();
$this->forms = ['attributes' => ['method' => "post",], 'hiddens' => []]; $this->forms = ['attributes' => ['method' => "post",], 'hiddens' => []];
return $this->modify_form_process_result(); return view($this->view_path . "create", data: ['viewDatas' => $this->getViewDatas()]);
} catch (\Exception $e) { } catch (\Exception $e) {
return redirect()->back()->with('error', $e->getMessage()); return redirect()->back()->with('error', $e->getMessage());
} }
} }
final protected function modify_validate(string $action, array $fields): array protected function create_process(): mixed
{ {
//변경할 값 확인 : Upload된 파일 검증시 $this->request->getVar()보다 먼처 체크필요 $this->formDatas = $this->doValidate($this->action, $this->fields);
$validation = $this->getValidation($action, $fields); return $this->getService()->create($this->formDatas);
if (!$validation->withRequest($this->request)->run()) {
throw new \Exception("{$this->getService()->getClassName()} 작업 데이터 검증 오류발생\n" . implode(
"\n",
$validation->getErrors()
));
}
return $validation->getValidated();
} }
//modify,toggle,batchjob 공통사용 public function create(): RedirectResponse|string
protected function modify_process(mixed $uid): void
{
$this->formDatas = $this->modify_validate($this->action, $this->fields);
//자신정보정의
$this->entity = $this->getService()->getModel()->getEntityByPK($uid);
if ($this->entity === null) {
throw new \Exception(__FUNCTION__ . " => {$uid} 정보를 찾을수 없습니다.");
}
$this->entity = $this->getService()->modify($this->entity, $this->formDatas);
}
protected function modify_process_result($message): RedirectResponse|string
{
$url = strtolower(base_url() . $this->uri_path . $this->getService()->getClassName()) . "/view/" . $this->entity->getPK();
return redirect()->to($url)->with('error', $message);
}
protected function modify_process_failed($message): RedirectResponse|string
{
return redirect()->back()->withInput()->with('error', $message);
}
final protected function modify_procedure(mixed $uid): RedirectResponse|string
{ {
//Transaction Start //Transaction Start
$this->getService()->getModel()->transStart(); $this->getService()->getModel()->transStart();
try { try {
$this->init(__FUNCTION__);
helper(['form']); helper(['form']);
$this->modify_process($uid); $this->entity = $this->create_process();
$this->getService()->getModel()->transCommit(); $this->getService()->getModel()->transCommit();
return $this->modify_process_result(MESSAGES["SUCCESS"]); //평소에는 index로 전환됨
$url = $this->myauth->popPreviousUrl();
if ($this->redirect) { //redirect가 선언되어 있으면
$url = strtolower(base_url() . $this->uri_path . $this->getService()->getClassName()) . "/" . $this->redirect . "/" . $this->entity->getPK();
}
return redirect()->to($url)->with('error', MESSAGES["SUCCESS"]);
} catch (\Exception $e) { } catch (\Exception $e) {
//Transaction Rollback //Transaction Rollback
$this->getService()->getModel()->transRollback(); $this->getService()->getModel()->transRollback();
return $this->modify_process_result($e->getMessage()); return redirect()->back()->withInput()->with('error', $e->getMessage());
} }
} }
final public function modify(int $uid): RedirectResponse|string
//수정관련
protected function modify_form_process(mixed $uid): mixed
{ {
$this->modify_init(__FUNCTION__); $this->getService()->getModel()->where($this->getService()->getModel()::PK, $uid);
return $this->modify_procedure($uid); $entity = $this->getService()->getEntity();
if ($entity === null) {
throw new \Exception("해당 정보를 찾을수 없습니다.");
}
return $entity;
}
public function modify_form(mixed $uid): RedirectResponse|string
{
try {
$this->init('modify');
helper(['form']);
$this->entity = $this->modify_form_process($uid);
$this->forms = ['attributes' => ['method' => "post",], 'hiddens' => []];
return view($this->view_path . "modify", data: ['viewDatas' => $this->getViewDatas()]);
} catch (\Exception $e) {
return redirect()->back()->with('error', $e->getMessage());
}
} }
//modify,toggle,batchjob 공통사용
protected function modify_process(mixed $uid): mixed
{
$this->formDatas = $this->doValidate($this->action, $this->fields);
//자신정보정의
$this->getService()->getModel()->where($this->getService()->getModel()::PK, $uid);
$entity = $this->getService()->getEntity();
if (!$entity) {
throw new \Exception(__FUNCTION__ . " => {$uid} 정보를 찾을수 없습니다.");
}
return $this->getService()->modify($entity, $this->formDatas);
}
public function modify(int $uid): RedirectResponse|string
{
//Transaction Start
$this->getService()->getModel()->transStart();
try {
$this->init(__FUNCTION__);
helper(['form']);
$this->entity = $this->modify_process($uid);
$this->getService()->getModel()->transCommit();
//평소에는 index로 전환됨
$url = $this->myauth->popPreviousUrl();
if ($this->redirect) { //redirect가 선언되어 있으면
$url = strtolower(base_url() . $this->uri_path . $this->getService()->getClassName()) . "/" . $this->redirect . "/" . $this->entity->getPK();
}
return redirect()->to($url)->with('error', MESSAGES["SUCCESS"]);
} catch (\Exception $e) {
//Transaction Rollback
$this->getService()->getModel()->transRollback();
return redirect()->back()->withInput()->with('error', $e->getMessage());
}
}
//단일필드작업 //단일필드작업
protected function toggle_process_result($message): RedirectResponse|string final public function toggle(mixed $uid, string $field): RedirectResponse
{
return redirect()->to($this->myauth->popPreviousUrl())->with('error', $message);
}
protected function toggle_process_failed($message): RedirectResponse|string
{
return redirect()->back()->with('error', $message);
}
final protected function toggle_procedure(mixed $uid, string $field): RedirectResponse
{ {
//Transaction Start //Transaction Start
$this->getService()->getModel()->transStart(); $this->getService()->getModel()->transStart();
try { try {
$this->action = __FUNCTION__; $this->action = __FUNCTION__;
$this->fields = [$field]; $this->fields = [$field];
$this->modify_process($uid); $this->entity = $this->modify_process($uid);
$this->getService()->getModel()->transCommit(); $this->getService()->getModel()->transCommit();
return $this->toggle_process_result(MESSAGES["SUCCESS"]); return redirect()->to($this->myauth->popPreviousUrl())->with('error', MESSAGES["SUCCESS"]);
} catch (\Exception $e) { } catch (\Exception $e) {
//Transaction Rollback
$this->getService()->getModel()->transRollback(); $this->getService()->getModel()->transRollback();
return $this->toggle_process_failed($e->getMessage()); return redirect()->back()->with('error', $e->getMessage());
} }
} }
final public function toggle(mixed $uid, string $field): RedirectResponse|string
{
return $this->toggle_procedure($uid, $field);
}
//일괄처리작업 //일괄처리작업
protected function batchjob_process_result($message): RedirectResponse|string final public function batchjob(): RedirectResponse
{
return redirect()->to($this->myauth->popPreviousUrl())->with('error', $message);
}
protected function batchjob_process_failed($message): RedirectResponse|string
{
return redirect()->back()->with('error', $message);
}
final protected function batchjob_procedure(): RedirectResponse
{ {
$this->init(__FUNCTION__);
//Transaction Start //Transaction Start
$this->getService()->getModel()->transStart(); $this->getService()->getModel()->transStart();
try { try {
@ -311,71 +270,46 @@ abstract class CommonController extends BaseController
if (!$uids) { if (!$uids) {
throw new \Exception("적용할 리스트를 선택하셔야합니다."); throw new \Exception("적용할 리스트를 선택하셔야합니다.");
} }
$entities = [];
foreach (explode(",", $uids) as $uid) { foreach (explode(",", $uids) as $uid) {
$this->modify_process($uid); $entities[$uid] = $this->modify_process($uid);
} }
$this->entities = $entities;
$this->getService()->getModel()->transCommit(); $this->getService()->getModel()->transCommit();
return $this->batchjob_process_result(MESSAGES["SUCCESS"]); return redirect()->to($this->myauth->popPreviousUrl())->with('error', MESSAGES["SUCCESS"]);
} catch (\Exception $e) { } catch (\Exception $e) {
//Transaction Rollback //Transaction Rollback
$this->getService()->getModel()->transRollback(); $this->getService()->getModel()->transRollback();
return $this->batchjob_process_failed($e->getMessage()); return redirect()->back()->with('error', $e->getMessage());
} }
} }
//일괄처리작업
final public function batchjob(): RedirectResponse
{
$this->init(__FUNCTION__);
return $this->batchjob_procedure();
}
//삭제 delete,batchjob_delete 공통사용 //삭제,일괄삭제 공통사용
protected function delete_process_result($message): RedirectResponse|string protected function delete_process(mixed $uid): mixed
{
return redirect()->to($this->myauth->popPreviousUrl())->with('error', $message);
}
protected function delete_process_failed($message): RedirectResponse|string
{
return redirect()->back()->with('error', $message);
}
protected function delete_process(mixed $uid): void
{ {
//자신정보정의 //자신정보정의
$this->entity = $this->getService()->getModel()->getEntityByPK($uid); $entity = $this->getService()->getModel()->getEntityByPK($uid);
if ($this->entity === null) { if ($entity === null) {
throw new \Exception("{$uid} 정보를 찾을수 없습니다."); throw new \Exception("{$uid} 정보를 찾을수 없습니다.");
} }
$this->entity = $this->getService()->delete($this->entity); return $this->getService()->delete($entity);
} }
final protected function delete_procedure(mixed $uid): RedirectResponse|string public function delete(mixed $uid): RedirectResponse|string
{ {
//Transaction Start //Transaction Start
$this->getService()->getModel()->transStart(); $this->getService()->getModel()->transStart();
try { try {
$this->delete_process($uid); $this->entity = $this->delete_process($uid);
$this->getService()->getModel()->transCommit(); $this->getService()->getModel()->transCommit();
return $this->delete_process_result(MESSAGES["SUCCESS"]); return redirect()->to($this->myauth->popPreviousUrl())->with('error', MESSAGES["SUCCESS"]);
} catch (\Exception $e) { } catch (\Exception $e) {
//Transaction Rollback //Transaction Rollback
$this->getService()->getModel()->transRollback(); $this->getService()->getModel()->transRollback();
return $this->delete_process_failed($e->getMessage()); return redirect()->back()->with('error', $e->getMessage());
} }
} }
final public function delete(mixed $uid): RedirectResponse|string
{
return $this->delete_procedure($uid);
}
//일괄삭제 //일괄삭제
protected function batchjob_delete_process_result($message): RedirectResponse|string final public function batchjob_delete(): RedirectResponse|string
{
return redirect()->to($this->myauth->popPreviousUrl())->with('error', $message);
}
protected function batchjob_delete_process_failed($message): RedirectResponse|string
{
return redirect()->back()->with('error', $message);
}
final protected function batchjob_delete_procedure(): RedirectResponse|string
{ {
//Transaction Start //Transaction Start
$this->getService()->getModel()->transStart(); $this->getService()->getModel()->transStart();
@ -385,81 +319,82 @@ abstract class CommonController extends BaseController
if (!$uids) { if (!$uids) {
throw new \Exception("적용할 리스트를 선택하셔야합니다."); throw new \Exception("적용할 리스트를 선택하셔야합니다.");
} }
$entities = [];
foreach (explode(",", $uids) as $uid) { foreach (explode(",", $uids) as $uid) {
$this->delete_process($uid); $entities[$uid] = $this->delete_process($uid);
} }
$this->entities = $entities;
$this->getService()->getModel()->transCommit(); $this->getService()->getModel()->transCommit();
return $this->batchjob_delete_process_result(MESSAGES["SUCCESS"]); return redirect()->to($this->myauth->popPreviousUrl())->with('error', MESSAGES["SUCCESS"]);
} catch (\Exception $e) { } catch (\Exception $e) {
//Transaction Rollback //Transaction Rollback
$this->getService()->getModel()->transRollback(); $this->getService()->getModel()->transRollback();
return $this->batchjob_delete_process_failed($e->getMessage()); return redirect()->back()->with('error', $e->getMessage());
} }
} }
final public function batchjob_delete(): RedirectResponse|string
{
return $this->batchjob_delete_procedure();
}
//View //View
protected function view_init(string $action, $fields = []): void protected function view_process($uid): mixed
{
$this->init($action, $fields);
}
protected function view_process(mixed $uid): void
{ {
//자신정보정의 //자신정보정의
$this->entity = $this->getService()->getModel()->getEntityByPK($uid); $this->getService()->getModel()->where($this->getService()->getModel()::PK, $uid);
if ($this->entity === null) { $entity = $this->getService()->getEntity();
throw new \Exception("해당 정보를 찾을수 없습니다."); if (!$entity) {
throw new \Exception("해당 사용자정보를 찾을수 없습니다.");
} }
return $entity;
} }
protected function view_process_result(): string public function view(string $uid): RedirectResponse|string
{
helper(['form']);
$this->forms = ['attributes' => ['method' => "post",], 'hiddens' => []];
return view(
$this->view_path . "view",
data: ['viewDatas' => $this->getViewDatas()]
);
}
protected function view_process_failed($message): RedirectResponse|string
{
return redirect()->back()->with('error', $message);
}
final protected function view_procedure(mixed $uid): RedirectResponse|string
{ {
try { try {
$this->view_process($uid); $this->init(__FUNCTION__);
return $this->view_process_result(); $this->entity = $this->view_process($uid);
helper(['form']);
$this->forms = ['attributes' => ['method' => "post",], 'hiddens' => []];
return view($this->view_path . "view", data: ['viewDatas' => $this->getViewDatas()]);
} catch (\Exception $e) { } catch (\Exception $e) {
return $this->view_process_failed($e->getMessage()); return redirect()->back()->with('error', $e->getMessage());
} }
} }
final public function view(string $uid): RedirectResponse|string
{
$this->view_init(__FUNCTION__);
return $this->view_procedure($uid);
}
// 리스트 //리스트
protected function index_init(string $action, $fields = []): void //List 조건절 처리
protected function setConditionForList(array $filter_fields): void
{ {
$this->init($action, $fields); //조건절 처리
foreach ($filter_fields as $field) {
$this->$field = $this->request->getVar($field) ?? DEFAULTS['EMPTY'];
if ($this->$field !== DEFAULTS['EMPTY']) {
$this->getService()->getModel()->setList_FieldFilter($field, $this->$field);
}
}
//검색어 처리
$this->word = $this->request->getVar('word') ?? DEFAULTS['EMPTY'];
if ($this->word !== DEFAULTS['EMPTY']) {
$this->getService()->getModel()->setList_WordFilter($this->word);
}
//검색일 처리
$this->start = $this->request->getVar('start') ?? DEFAULTS['EMPTY'];
$this->end = $this->request->getVar('end') ?: DEFAULTS['EMPTY'];
$this->getService()->getModel()->setList_DateFilter($this->start, $this->end);
} }
//PageNation 처리 //PageNation 처리
private function index_pagination_process($pager_group = 'default', int $segment = 0, $template = 'bootstrap_full'): string protected function getPageOptionsByPaginationForList(): array
{ {
//Page, Per_page필요부분 $page_options = ["" => "줄수선택"];
$this->page = (int) $this->request->getVar('page') ?: 1;
$this->per_page = (int) $this->request->getVar('per_page') ?: intval(env("mvc.default.list.per_page") ?? 10);
//줄수 처리용
$page_options = array("" => "줄수선택");
for ($i = $this->per_page; $i <= $this->total_count; $i += $this->per_page) { for ($i = $this->per_page; $i <= $this->total_count; $i += $this->per_page) {
$page_options[$i] = $i; $page_options[$i] = $i;
} }
$page_options[$this->total_count] = $this->total_count; $page_options[$this->total_count] = $this->total_count;
$this->page_options = $page_options; return $page_options;
}
protected function getPaginationForList($pager_group = 'default', int $segment = 0, $template = 'bootstrap_full')
{
//Page, Per_page필요부분
$this->page = (int) $this->request->getVar('page') ?: 1;
$this->per_page = (int) $this->request->getVar('per_page') ?: intval(DEFAULT_LIST_PERPAGE ?? 20);
//줄수 처리용
$this->page_options = $this->getPageOptionsByPaginationForList();
// 1.Views/Pagers/에 bootstrap_full.php,bootstrap_simple.php 생성 // 1.Views/Pagers/에 bootstrap_full.php,bootstrap_simple.php 생성
// 2.app/Config/Pager.php/$templates에 'bootstrap_full => 'Pagers\bootstrap_full', // 2.app/Config/Pager.php/$templates에 'bootstrap_full => 'Pagers\bootstrap_full',
// 'bootstrap_simple' => 'Pagers\bootstrap_simple', 추가 // 'bootstrap_simple' => 'Pagers\bootstrap_simple', 추가
@ -470,8 +405,17 @@ abstract class CommonController extends BaseController
$this->total_page = $pager->getPageCount($pager_group); $this->total_page = $pager->getPageCount($pager_group);
return $pager->links($pager_group, $template); return $pager->links($pager_group, $template);
} }
protected function index_entitys_process_orderBy(): void protected function index_process(): array
{ {
//조건절 처리
$this->setConditionForList($this->filter_fields);
//TotalCount
$this->total_count = intval($this->getService()->getModel()->selectCount('*', 'cnt')->get()->getRow()->cnt);
// echo $this->total_count;
// exit;
//Pagination 처리
$this->pagination = $this->getPaginationForList();
//OrderBy 처리
$this->order_field = $this->request->getVar('order_field') ?: DEFAULTS['EMPTY']; $this->order_field = $this->request->getVar('order_field') ?: DEFAULTS['EMPTY'];
$this->order_value = $this->request->getVar('order_value') ?: DEFAULTS['EMPTY']; $this->order_value = $this->request->getVar('order_value') ?: DEFAULTS['EMPTY'];
if ($this->order_field !== DEFAULTS['EMPTY'] && $this->order_value !== DEFAULTS['EMPTY']) { if ($this->order_field !== DEFAULTS['EMPTY'] && $this->order_value !== DEFAULTS['EMPTY']) {
@ -479,54 +423,23 @@ abstract class CommonController extends BaseController
} else { } else {
$this->getService()->getModel()->orderBy(sprintf("%s.%s %s", $this->getService()->getModel()::TABLE, $this->getService()->getModel()::PK, "DESC")); $this->getService()->getModel()->orderBy(sprintf("%s.%s %s", $this->getService()->getModel()::TABLE, $this->getService()->getModel()::PK, "DESC"));
} }
$this->getService()->getModel()->limit($this->per_page);
$this->getService()->getModel()->offset(($this->page - 1) * $this->per_page);
return $this->getService()->getEntities();
} }
protected function index_entitys_process_limit(): void public function index()
{
$this->getService()->getModel()->limit($this->per_page, $this->page * $this->per_page - $this->per_page);
}
protected function index_entitys_process(): array
{
$this->getService()->setListConditon($this->request, $this->filter_fields);
$this->total = $this->getService()->setTotalCount();
//Sorting 처리
$this->index_entitys_process_orderBy();
//Limit관련
$this->index_entitys_process_limit();
$entitys = $this->getService()->getModel()->select($this->getService()->getModel()::TABLE . '.*')->findAll();
// log_message("debug", $this->getService()->getModel()->getLastQuery());
return $entitys;
}
protected function index_process_result(): string
{
return view(
$this->view_path . "index",
['viewDatas' => $this->getViewDatas()]
);
}
final protected function index_procedure(): string
{ {
try { try {
helper(['form']); $this->init(__FUNCTION__);
//URL처리 $this->entities = $this->index_process();
$this->uri = $this->request->getUri();
//total 처리
$this->total_count = $this->getService()->setListCondition();
//pagenation 처리
$this->pagination = $this->index_pagination_process();
//모델 처리
$this->entitys = $this->index_entitys_process();
// 현재 URL을 스택에 저장 // 현재 URL을 스택에 저장
$this->myauth->pushCurrentUrl($this->request->getUri()->getPath() . ($this->request->getUri()->getQuery() ? "?" . $this->request->getUri()->getQuery() : "")); $this->myauth->pushCurrentUrl($this->request->getUri()->getPath() . ($this->request->getUri()->getQuery() ? "?" . $this->request->getUri()->getQuery() : ""));
return $this->index_process_result(); helper(['form']);
return view($this->view_path . "index", ['viewDatas' => $this->getViewDatas()]);
} catch (\Exception $e) { } catch (\Exception $e) {
return $this->helper->alert($e->getMessage()); return $this->helper->alert($e->getMessage());
} }
} }
public function index(): string
{
$this->index_init(__FUNCTION__);
return $this->index_procedure();
}
//OUPUT Document 관련 //OUPUT Document 관련
private function output_save_process(string $document_type, mixed $loaded_data): array private function output_save_process(string $document_type, mixed $loaded_data): array
@ -560,7 +473,7 @@ abstract class CommonController extends BaseController
return array($full_path, $file_name); return array($full_path, $file_name);
} }
//File Download관련 //File Download관련
final protected function download_procedure(string $output_type, mixed $uid = false): DownloadResponse|RedirectResponse protected function download_process(string $output_type, mixed $uid = false): DownloadResponse|RedirectResponse
{ {
try { try {
helper(['form']); helper(['form']);
@ -570,11 +483,8 @@ abstract class CommonController extends BaseController
case 'excel': case 'excel':
case 'pdf': case 'pdf':
// string buffer에서 읽어오는 경우 // string buffer에서 읽어오는 경우
$this->entitys = $this->index_entitys_process(); $this->entities = $this->index_process();
$html = view( $html = view('templates' . DIRECTORY_SEPARATOR . $this->action, ['viewDatas' => $this->getViewDatas()]);
'templates' . DIRECTORY_SEPARATOR . $this->action,
['viewDatas' => $this->getViewDatas()]
);
//data loading //data loading
$reader = new Html(); $reader = new Html();
$loaded_data = $reader->loadFromString($html); $loaded_data = $reader->loadFromString($html);
@ -602,6 +512,6 @@ abstract class CommonController extends BaseController
final public function download(string $output_type, mixed $uid = false): DownloadResponse|string final public function download(string $output_type, mixed $uid = false): DownloadResponse|string
{ {
$this->init(__FUNCTION__); $this->init(__FUNCTION__);
return $this->download_procedure($output_type, $uid); return $this->download_process($output_type, $uid);
} }
} }

View File

@ -2,39 +2,54 @@
namespace App\Controllers; namespace App\Controllers;
use App\Libraries\MySocket\GoogleSocket\API as GoogleSocket;
use CodeIgniter\HTTP\RedirectResponse; use CodeIgniter\HTTP\RedirectResponse;
use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface; use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use App\Services\UserService;
use App\Helpers\UserHelper; use App\Services\UserService as Service;
use App\Services\Auth\GoogleService; use App\Helpers\UserHelper as Helper;
use App\Services\Auth\LocalService; use App\Services\Auth\LocalService;
use App\Services\Auth\GoogleService;
use App\Libraries\MySocket\GoogleSocket\API as GoogleSocket;
class UserController extends CommonController class UserController extends CommonController
{ {
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger) public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{ {
parent::initController($request, $response, $logger); parent::initController($request, $response, $logger);
$this->uri_path .= strtolower($this->getService()->getClassName()) . DIRECTORY_SEPARATOR;
$this->view_path = $this->uri_path;
$this->title = lang("{$this->getService()->getClassPath()}.title");; $this->title = lang("{$this->getService()->getClassPath()}.title");;
$this->helper = new UserHelper(); $this->helper = new Helper($this->request);
} }
protected function getService(): UserService protected function getServiceClass(): Service
{ {
if ($this->service === null) { if ($this->service === null) {
$this->service = new UserService(); $this->service = new Service($this->request);
$this->class_name = $this->service->getClassName();
$this->class_path = $this->service->getClassPath();
} }
return $this->service; return $this->service;
} }
protected function login_init(string $action, array $fields = []): void //Index,FieldForm관련
public function getFields(): array
{
return ['id', $this->getService()->getModel()::TITLE, 'email', 'mobile', 'role', 'status'];
}
public function getFilterFields(): array
{
return ['role', 'status'];
}
public function getBatchJobFields(): array
{
return ['status'];
}
//Index,FieldForm관련
private function login_init(string $action, array $fields = []): void
{ {
$this->action = $action; $this->action = $action;
$fields = [ $fields = ['fields' => ['id', 'passwd'],];
'fields' => ['id', 'passwd'],
];
$this->init($action, $fields); $this->init($action, $fields);
} }
//로그인화면 //로그인화면
@ -47,10 +62,7 @@ class UserController extends CommonController
$google_socket = new GoogleSocket(); $google_socket = new GoogleSocket();
$this->google_url = $google_socket->createAuthUrl(); $this->google_url = $google_socket->createAuthUrl();
$this->forms = ['attributes' => ['method' => "post",], 'hiddens' => []]; $this->forms = ['attributes' => ['method' => "post",], 'hiddens' => []];
return view( return view($this->view_path . "login", data: ['viewDatas' => $this->getViewDatas()]);
$this->view_path . "login",
data: ['viewDatas' => $this->getViewDatas()]
);
} catch (\Exception $e) { } catch (\Exception $e) {
log_message("error", $e->getMessage()); log_message("error", $e->getMessage());
return redirect()->back()->withInput()->with('error', __FUNCTION__ . " 실패하였습니다.\n" . $e->getMessage()); return redirect()->back()->withInput()->with('error', __FUNCTION__ . " 실패하였습니다.\n" . $e->getMessage());

View File

@ -4,9 +4,9 @@
"settings": { "settings": {
"width": 4000, "width": 4000,
"height": 4000, "height": 4000,
"scrollTop": -1393.7855, "scrollTop": -2096.6106,
"scrollLeft": -1341.8424, "scrollLeft": -1225.4185,
"zoomLevel": 0.28, "zoomLevel": 0.73,
"show": 431, "show": 431,
"database": 4, "database": 4,
"databaseName": "", "databaseName": "",
@ -782,12 +782,10 @@
"columnIds": [ "columnIds": [
"J_xS3cvULouXCTo5gCiTm", "J_xS3cvULouXCTo5gCiTm",
"DGl10GI58QwOHwpTu4Z1Y", "DGl10GI58QwOHwpTu4Z1Y",
"yMcXBh6lgSLWfLhrivvuX",
"KvMMNu-PKESt0_2K4AJcB", "KvMMNu-PKESt0_2K4AJcB",
"kKI4hKELPs9Nh5UtQvSu7", "kKI4hKELPs9Nh5UtQvSu7",
"wkjLZ-Bc9g3Z6Rh_IQ7_q", "wkjLZ-Bc9g3Z6Rh_IQ7_q",
"W5bxFTggHoO9_PPsfy2EB", "W5bxFTggHoO9_PPsfy2EB",
"Wef1cEik-NFTr_alGxLpa",
"qHceMMaFcmVnWPlJ2T4Sg" "qHceMMaFcmVnWPlJ2T4Sg"
], ],
"seqColumnIds": [ "seqColumnIds": [
@ -811,7 +809,7 @@
"color": "" "color": ""
}, },
"meta": { "meta": {
"updateAt": 1745821593690, "updateAt": 1745885705761,
"createAt": 1745819764142 "createAt": 1745819764142
} }
}, },
@ -3778,18 +3776,18 @@
"tableId": "gsa0XtQZQgrJ8ZXy8VQVg", "tableId": "gsa0XtQZQgrJ8ZXy8VQVg",
"name": "status", "name": "status",
"comment": "", "comment": "",
"dataType": "ENUM(use,archived)", "dataType": "ENUM(info,warning,error,megency,critical,debug)",
"default": "use", "default": "info",
"options": 0, "options": 0,
"ui": { "ui": {
"keys": 0, "keys": 0,
"widthName": 60, "widthName": 60,
"widthComment": 60, "widthComment": 60,
"widthDataType": 109, "widthDataType": 262,
"widthDefault": 60 "widthDefault": 60
}, },
"meta": { "meta": {
"updateAt": 1745819764142, "updateAt": 1745885282627,
"createAt": 1745819764142 "createAt": 1745819764142
} }
}, },
@ -4709,7 +4707,7 @@
"DGl10GI58QwOHwpTu4Z1Y" "DGl10GI58QwOHwpTu4Z1Y"
], ],
"x": 1172.834, "x": 1172.834,
"y": 2689.8385, "y": 2665.8385,
"direction": 1 "direction": 1
}, },
"meta": { "meta": {
@ -5312,6 +5310,21 @@
{ {
"options(notNull)": 1745821700049 "options(notNull)": 1745821700049
} }
],
"Wef1cEik-NFTr_alGxLpa": [
"tableColumnEntities",
-1,
1745885692761,
{
"dataType": 1745885282627,
"default": 1745885076389
}
],
"yMcXBh6lgSLWfLhrivvuX": [
"tableColumnEntities",
-1,
1745885705761,
{}
] ]
} }
} }

62
app/Database/users.sql Normal file
View File

@ -0,0 +1,62 @@
/*!999999\- enable the sandbox mode */
-- MariaDB dump 10.19 Distrib 10.5.25-MariaDB, for Win64 (AMD64)
--
-- Host: localhost Database: cfmgr
-- ------------------------------------------------------
-- Server version 10.5.25-MariaDB
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `user`
--
DROP TABLE IF EXISTS `user`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `user` (
`uid` int(5) unsigned NOT NULL AUTO_INCREMENT,
`id` varchar(20) NOT NULL,
`passwd` varchar(255) NOT NULL,
`name` varchar(20) NOT NULL,
`email` varchar(50) NOT NULL,
`mobile` varchar(20) DEFAULT NULL,
`role` varchar(255) NOT NULL DEFAULT 'use',
`status` varchar(10) NOT NULL DEFAULT 'use',
`updated_at` timestamp NULL DEFAULT NULL,
`created_at` timestamp NOT NULL DEFAULT current_timestamp(),
PRIMARY KEY (`uid`),
UNIQUE KEY `id` (`id`),
UNIQUE KEY `email` (`email`)
) ENGINE=InnoDB AUTO_INCREMENT=26 DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `user`
--
LOCK TABLES `user` WRITE;
/*!40000 ALTER TABLE `user` DISABLE KEYS */;
INSERT INTO `user` VALUES (1,'choi.jh','$2y$10$9kUte0xrvEkxtI9CzVaeKeCAxzOR4pKPpsCaQHR1YW7dXsCrTLWeC','최준흠','choi.jh@prime-idc.jp',NULL,'user,vip,manager,cloudflare,firewall,director,master','use','2023-05-31 14:55:51','2023-03-23 06:50:04'),(2,'cho.jh','$2y$10$ot/aUXR/W1n4Q3dZA2dZCOxQrpVb2Bq31Y7xFQS3G6D1gtImmyBjm','조준희','cho.jh@prime-idc.jp',NULL,'manager,cloudflare','use','2023-05-30 14:35:55','2023-03-24 02:20:48'),(4,'kimdy','$2y$10$18uyn94xdprzAnt.oYZ5weAvb8rRLhkz/SdQrjEK7yuGhCr9PlUCC','김동윤','kimdy@prime-idc.jp',NULL,'manager,cloudflare','use','2023-03-24 02:21:50','2023-03-24 02:21:50'),(5,'kimhy','$2y$10$.yEKVqY.F7HoSOZijl4uyeulUtfAQ4EDRiyR2JpgFYBuKw.mZoZvG','김효영','khy@prime-idc.jp',NULL,'manager,cloudflare,director','use','2023-03-24 02:23:18','2023-03-24 02:23:18'),(6,'kim.eh','$2y$10$YmwicI.Br4XNyGamfRADMOu.qlkwKd2fmnNkL7YIkNHGndvqYPnCq','김은혁','kim.eh@prime-idc.jp',NULL,'manager,cloudflare','use','2023-03-24 02:23:52','2023-03-24 02:23:52'),(7,'leeph','$2y$10$lR739WzJsW6rDLgchYs7buek4BYeTlKHTQY60RDqRms9Io7RSY3AC','이풍호','leeph@prime-idc.jp',NULL,'manager,cloudflare','use','2023-05-29 16:32:52','2023-03-24 02:24:21'),(8,'jinmingyu','$2y$10$PI8WA6d/z4hDE6hxJoUhbuMH3vTTWH0Ry2Z6fTLUUpwQGaE/9bEZa','김명옥','jinmingyu@idcjp.jp',NULL,'manager,cloudflare','use','2023-07-21 06:48:39','2023-03-24 02:25:00'),(9,'kangdh','$2y$10$gu9OS2DDQQ5H.Hh61t3BSOUp87l35q.xsduVSxvCcn8IgA4jrATgG','강동헌','kang.dh@idcjp.jp',NULL,'manager,cloudflare','use','2023-06-22 23:59:07','2023-03-24 02:25:48'),(10,'yoohs','$2y$10$TGASk98FuZ6Ux6FDquu1aO3rztA01MCle/Vs1.3iaEMQzakAbCzJy','유혜성','yoo.hs@idcjp.jp',NULL,'manager,cloudflare','use','2023-06-02 02:07:19','2023-03-24 02:26:31'),(11,'kim.yh','$2y$10$8GciQXpKYiR3TDWQfh9JjOQAQ.YWGoOSCL0a0/w4XACO0mUgjjbWy','김영환','kim.yh@idcjp.jp',NULL,'manager,cloudflare,firewall','use','2023-10-16 23:08:51','2023-03-24 02:27:05'),(12,'yunmuj','$2y$10$zkgwGVj2JSOVIsxLe8fePe1gvWWaCemfZMktzBlrN8oLb3CKydkZC','윤무정','yunmuj@idcjp.jp',NULL,'manager,cloudflare','use','2024-06-12 00:21:07','2023-03-24 02:27:59'),(13,'kim.mt','$2y$10$3dfkA0oq4LqiJOmjbBGKe.p0Dhj/MDqjoTdw11BOPF/H2qJqnEuHO','김문태','kim.mt@idcjp.jp',NULL,'manager,cloudflare','use','2023-05-31 14:22:43','2023-03-24 02:28:31'),(14,'shin.ms','$2y$10$.jaDkGtm/gZK3ZDF.fJUGOwMI7Zif5588X5AxSMvvk238RDI7spQ6','신민수','shin.ms@idcjp.jp',NULL,'manager,cloudflare','use','2023-03-24 02:29:00','2023-03-24 02:29:00'),(15,'park.sm','$2y$10$BwMxw0uvw2tAdQ0EZQ2/hu.Q7zYu7mbuBPPRTaa14bwG3VLf0cXfu','박선미','park.sm@idcjp.jp',NULL,'manager,cloudflare','use','2024-03-12 02:14:09','2023-03-24 02:29:34'),(19,'park.hg','$2y$10$x7QQOkOEJHVKOnghbHBqYuI12Vsa9KLV8W4wgebCWy1pZiM93/W.e','박혁규','park.hg@prime-idc.jp',NULL,'manager','unuse','2023-09-04 10:27:32','2023-09-04 09:48:02'),(21,'masakuni','$2y$10$di6Y7CqJGbbf72kDyCrOCOafJgk3vqJCYg6N3EtBUc3J6r24/7SFe','김창국','masakuni@prime-idc.jp',NULL,'cloudflare','unuse','2023-12-18 08:56:29','2023-12-18 08:56:29'),(22,'bjh','$2y$10$LnEQ6kz4igRPZeDYwe7UluRiSaMVGN9Jj1fW3QqUUp6zPeLJW9goS','배장훈','bjh@prime-idc.jp',NULL,'cloudflare','unuse','2024-06-06 23:51:19','2024-02-26 01:26:20'),(23,'cho.sh','$2y$10$jmmNrEsFmb2.Zj3OkBXDHuktrIj.NCP/tO2k9kquFBTBssa/lNG6y','조성호','cho.sh@prime-idc.jp',NULL,'user','unuse','2024-10-02 00:45:19','2024-10-02 00:32:30'),(24,'kobn','$2y$10$pWM/XFfSNeSng32sypbDX.WaR4UlM4EDkYKCQfFkYIOC7Ppg0nc5G','고병남','ko@prime-idc.jp',NULL,'manager,cloudflare','use',NULL,'2024-10-29 06:30:19'),(25,'jeong.sg','$2y$10$OzH6140JztiUEs4s/VHbPOxfxubFooqwqVhGpdFG8OJCGAFXNu546','정상구','jeong.sg@prime-idc.jp',NULL,'manager,cloudflare','use','2025-01-23 00:30:13','2025-01-23 00:29:46');
/*!40000 ALTER TABLE `user` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2025-04-29 9:31:24

View File

@ -8,6 +8,8 @@ abstract class CommonEntity extends Entity
{ {
protected $datamap = []; protected $datamap = [];
protected $dates = ['created_at', 'updated_at', 'deleted_at']; protected $dates = ['created_at', 'updated_at', 'deleted_at'];
//사용법 : $client->created_at->format('Y-m-d')
//비교방법 : if ($client->created_at < new \DateTime('2024-01-01')) {
protected $casts = []; protected $casts = [];
public function __construct(array|null $data = null) public function __construct(array|null $data = null)
@ -18,12 +20,12 @@ abstract class CommonEntity extends Entity
abstract public function __toString(); abstract public function __toString();
final public function getPK(): string final public function getPK(): string
{ {
$field = constant("static::PKField"); $field = constant("static::PK");
return $this->$field; return $this->$field;
} }
final public function getTitle(): string final public function getTitle(): string
{ {
$field = constant("static::TitleField"); $field = constant("static::Title");
return $this->$field; return $this->$field;
} }
final public function getUpdatedAt(): string final public function getUpdatedAt(): string

View File

@ -7,8 +7,8 @@ use App\Models\MyLogModel as Model;
class MyLogEntity extends Entity class MyLogEntity extends Entity
{ {
const PKField = Model::PK; const PK = Model::PK;
const TitleField = Model::TITLE; const Title = Model::TITLE;
public function __toString(): string public function __toString(): string
{ {
return "{$this->getPK()}:{$this->getTitle()}}"; return "{$this->getPK()}:{$this->getTitle()}}";

View File

@ -7,6 +7,8 @@ use App\Models\UserModel as Model;
class UserEntity extends CommonEntity class UserEntity extends CommonEntity
{ {
const PK = Model::PK;
const Title = Model::TITLE;
public function __toString(): string public function __toString(): string
{ {
return "{$this->getPK()}:{$this->getID()}:{$this->getTitle()},{$this->getRole()}}"; return "{$this->getPK()}:{$this->getID()}:{$this->getTitle()},{$this->getRole()}}";

View File

@ -3,30 +3,24 @@
namespace App\Entities; namespace App\Entities;
use App\Entities\CommonEntity; use App\Entities\CommonEntity;
use App\Models\UserSNSModel; use App\Models\UserSNSModel as Model;
class UserSNSEntity extends CommonEntity class UserSNSEntity extends CommonEntity
{ {
const PK = Model::PK;
const Title = Model::TITLE;
public function __toString(): string public function __toString(): string
{ {
return "{$this->getPK()}|{$this->getID()}|{$this->getTitle()}"; return "{$this->getPK()}|{$this->getID()}|{$this->getTitle()}";
} }
public function getPK(): int
{
return $this->attributes[UserSNSModel::PK];
}
public function getTitle(): string
{
return $this->attributes[UserSNSModel::TITLE];
}
public function setTitle(string $title): void public function setTitle(string $title): void
{ {
$this->attributes[UserSNSModel::TITLE] = $title; $this->attributes[Model::TITLE] = $title;
} }
//Common Function //Common Function
public function getParent(): int|null public function getParent(): int|null
{ {
return $this->attributes[UserSNSModel::PARENT]; return $this->attributes[Model::PARENT];
} }
public function getID(): string public function getID(): string
{ {

View File

@ -27,7 +27,9 @@ class AuthFilter implements FilterInterface
public function before(RequestInterface $request, $arguments = null) public function before(RequestInterface $request, $arguments = null)
{ {
$auth = service('myauth'); $auth = service('myauth');
// var_dump($arguments);
// log_message("debug", var_export($arguments, true)); // log_message("debug", var_export($arguments, true));
// exit;
// 로그인 않했으면 // 로그인 않했으면
if (!$auth->isLoggedIn()) { if (!$auth->isLoggedIn()) {
$auth->pushCurrentUrl($request->getUri()->getPath() . ($request->getUri()->getQuery() ? "?" . $request->getUri()->getQuery() : "")); $auth->pushCurrentUrl($request->getUri()->getPath() . ($request->getUri()->getQuery() ? "?" . $request->getUri()->getQuery() : ""));

View File

@ -4,49 +4,18 @@ namespace App\Helpers;
class CommonHelper class CommonHelper
{ {
public function __construct() {} private $_service = null;
public function __construct($service)
final public function getRandomString($length = 10, $characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
{ {
return substr(str_shuffle($characters), 0, $length); $this->_service = $service;
} }
final public function getPasswordString($length = 8) final protected function getService()
{ {
return $this->getRandomString($length, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_-=+;:,.?"); return $this->_service;
} }
// byte값을 알아보기 쉽게 변환 final public function isDomainName(string $domain): bool
final public function getSizeForHuman($bytes)
{
$ext = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
$unitCount = 0;
for (; $bytes > 1024; $unitCount++) {
$bytes /= 1024;
}
return floor($bytes) . $ext[$unitCount];
}
// Proxy등을 통하여 Client_IP가 알수없는경우 실제사용자의 IP를 가져오기 위한것
final public function getClientIP($clientIP = false)
{
if (isset($_SERVER['HTTP_CLIENT_IP'])) {
$clientIP = $_SERVER['HTTP_CLIENT_IP'];
} else if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$clientIP = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else if (isset($_SERVER['HTTP_X_FORWARDED'])) {
$clientIP = $_SERVER['HTTP_X_FORWARDED'];
} else if (isset($_SERVER['HTTP_FORWARDED_FOR'])) {
$clientIP = $_SERVER['HTTP_FORWARDED_FOR'];
} else if (isset($_SERVER['HTTP_FORWARDED'])) {
$clientIP = $_SERVER['HTTP_FORWARDED'];
} else if (isset($_SERVER['REMOTE_ADDR'])) {
$clientIP = $_SERVER['REMOTE_ADDR'];
}
return $clientIP;
}
final public function isDomain(string $domain): bool
{ {
$pattern_validation = '/((http|https)\:\/\/)?[a-zA-Z0-9\.\/\?\:@\-_=#]+\.([a-zA-Z0-9\&\.\/\?\:@\-_=#])*/'; $pattern_validation = '/((http|https)\:\/\/)?[a-zA-Z0-9\.\/\?\:@\-_=#]+\.([a-zA-Z0-9\&\.\/\?\:@\-_=#])*/';
return preg_match($pattern_validation, $domain); return preg_match($pattern_validation, $domain);
@ -70,27 +39,11 @@ class CommonHelper
} }
return $result; return $result;
} }
final public function isHostName(string $host): bool
final public function isHost(string $host): bool
{ {
$pattern_validation = '/[a-zA-Z0-9\.\/\?\:@\*\-_=#]/'; $pattern_validation = '/[a-zA-Z0-9\.\/\?\:@\*\-_=#]/';
return preg_match($pattern_validation, $host); return preg_match($pattern_validation, $host);
} }
// (EX:192.168.1.0 -> 192.168.001.000)
final public function convertIPV4toCIDR($cidr)
{
$temps = explode(".", $cidr);
return sprintf("%03d.%03d.%03d.%03d", $temps[0], $temps[1], $temps[2], $temps[3]);
}
// (EX:192.168.001.0000 -> 192.168.1.0)
final public function convertCIDRtoIPV4($ipv4)
{
$temps = explode(".", $ipv4);
return sprintf("%d.%d.%d.%d", $temps[0], $temps[1], $temps[2], $temps[3]);
}
final public function isMobile() final public function isMobile()
{ {
// Check the server headers to see if they're mobile friendly // Check the server headers to see if they're mobile friendly
@ -140,12 +93,65 @@ class CommonHelper
return "<script type=\"text/javascript\">{$msg}</script>"; return "<script type=\"text/javascript\">{$msg}</script>";
} }
final public function getRandomString($length = 10, $characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
{
return substr(str_shuffle($characters), 0, $length);
}
final public function getPasswordString($length = 8)
{
return $this->getRandomString($length, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_-=+;:,.?");
}
// byte값을 알아보기 쉽게 변환
final public function getSizeForHuman($bytes)
{
$ext = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
$unitCount = 0;
for (; $bytes > 1024; $unitCount++) {
$bytes /= 1024;
}
return floor($bytes) . $ext[$unitCount];
}
// Proxy등을 통하여 Client_IP가 알수없는경우 실제사용자의 IP를 가져오기 위한것
final public function getClientIP($clientIP = false)
{
if (isset($_SERVER['HTTP_CLIENT_IP'])) {
$clientIP = $_SERVER['HTTP_CLIENT_IP'];
} else if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$clientIP = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else if (isset($_SERVER['HTTP_X_FORWARDED'])) {
$clientIP = $_SERVER['HTTP_X_FORWARDED'];
} else if (isset($_SERVER['HTTP_FORWARDED_FOR'])) {
$clientIP = $_SERVER['HTTP_FORWARDED_FOR'];
} else if (isset($_SERVER['HTTP_FORWARDED'])) {
$clientIP = $_SERVER['HTTP_FORWARDED'];
} else if (isset($_SERVER['REMOTE_ADDR'])) {
$clientIP = $_SERVER['REMOTE_ADDR'];
}
return $clientIP;
}
// (EX:192.168.1.0 -> 192.168.001.000)
final public function convertIPV4toCIDR($cidr)
{
$temps = explode(".", $cidr);
return sprintf("%03d.%03d.%03d.%03d", $temps[0], $temps[1], $temps[2], $temps[3]);
}
// (EX:192.168.001.0000 -> 192.168.1.0)
final public function convertCIDRtoIPV4($ipv4)
{
$temps = explode(".", $ipv4);
return sprintf("%d.%d.%d.%d", $temps[0], $temps[1], $temps[2], $temps[3]);
}
public function getFieldLabel(string $field, array $viewDatas, array $extras = []): string public function getFieldLabel(string $field, array $viewDatas, array $extras = []): string
{ {
switch ($field) { switch ($field) {
default: default:
$extras = (strpos($viewDatas['field_rules'][$field], 'required') !== false) ? ["class" => "text-danger", "required" => "", ...$extras] : $extras; $extras = (strpos($viewDatas['field_rules'][$field], 'required') !== false) ? ["class" => "text-danger", "required" => "", ...$extras] : $extras;
$label = form_label(lang("{$viewDatas['class_path']}.label.{$field}"), $field, $extras); $label = form_label(lang("{$this->getService()->getClassPath()}.label.{$field}"), $field, $extras);
break; break;
} }
return $label; return $label;
@ -161,7 +167,7 @@ class CommonHelper
switch ($field) { switch ($field) {
case 'status': case 'status':
$form = form_dropdown($field, [ $form = form_dropdown($field, [
"" => lang($viewDatas['class_path'] . '.label.' . $field) . ' 선택', "" => lang($this->getService()->getClassPath() . '.label.' . $field) . ' 선택',
] + $viewDatas['field_options'][$field], $value, $extras); ] + $viewDatas['field_options'][$field], $value, $extras);
break; break;
case 'updated_at': case 'updated_at':
@ -222,7 +228,7 @@ class CommonHelper
if (isset($viewDatas['order_field']) && $viewDatas['order_field'] == $field) { if (isset($viewDatas['order_field']) && $viewDatas['order_field'] == $field) {
$label .= $viewDatas['order_value'] == 'ASC' ? ICONS["UP"] : ICONS["DOWN"]; $label .= $viewDatas['order_value'] == 'ASC' ? ICONS["UP"] : ICONS["DOWN"];
} }
$query = $viewDatas['uri']->getQuery(['except' => ['order_field', 'order_value']]); $query = $this->getService()->getRequest()->getUri()->getQuery(['except' => ['order_field', 'order_value']]);
$query .= empty($query) ? "" : "&"; $query .= empty($query) ? "" : "&";
$query .= "order_field={$field}&order_value="; $query .= "order_field={$field}&order_value=";
$query .= isset($viewDatas['order_value']) && $viewDatas['order_value'] == 'DESC' ? "ASC" : "DESC"; $query .= isset($viewDatas['order_value']) && $viewDatas['order_value'] == 'DESC' ? "ASC" : "DESC";
@ -241,7 +247,7 @@ class CommonHelper
'입력', '입력',
$action, $action,
[ [
"data-src" => current_url() . '/' . $action . '?' . $viewDatas['uri']->getQuery(), "data-src" => current_url() . '/' . $action . '?' . $this->getService()->getRequest()->getUri()->getQuery(),
"data-bs-toggle" => "modal", "data-bs-toggle" => "modal",
"data-bs-target" => "#index_action_form", "data-bs-target" => "#index_action_form",
...$extras ...$extras

View File

@ -6,9 +6,9 @@ use App\Models\MyLogModel as Model;
class MyLogHelper extends CommonHelper class MyLogHelper extends CommonHelper
{ {
public function __construct() public function __construct($service)
{ {
parent::__construct(); parent::__construct($service);
} }
public function getFieldView(string $field, array $viewDatas, array $extras = []): string public function getFieldView(string $field, array $viewDatas, array $extras = []): string

View File

@ -2,13 +2,11 @@
namespace App\Helpers; namespace App\Helpers;
use App\Models\UserModel as Model;
class UserHelper extends CommonHelper class UserHelper extends CommonHelper
{ {
public function __construct() public function __construct($service)
{ {
parent::__construct(); parent::__construct($service);
} }
public function getFieldForm(string $field, mixed $value, array $viewDatas, array $extras = []): string public function getFieldForm(string $field, mixed $value, array $viewDatas, array $extras = []): string
{ {
@ -18,7 +16,7 @@ class UserHelper extends CommonHelper
$value = $value ?: DEFAULTS['EMPTY']; $value = $value ?: DEFAULTS['EMPTY'];
switch ($field) { switch ($field) {
case 'id': case 'id':
case Model::TITLE: case $this->getService()->getModel()::TITLE:
$form = form_input($field, $value, $extras); $form = form_input($field, $value, $extras);
break; break;
case 'passwd': case 'passwd':
@ -47,7 +45,7 @@ class UserHelper extends CommonHelper
$form = form_dropdown( $form = form_dropdown(
$field, $field,
[ [
"" => lang($viewDatas['class_path'] . '.label.' . $field) . ' 선택', "" => lang($this->getService()->getClassPath() . '.label.' . $field) . ' 선택',
] + $viewDatas['field_options'][$field], ] + $viewDatas['field_options'][$field],
$value, $value,
$extras $extras
@ -64,7 +62,7 @@ class UserHelper extends CommonHelper
{ {
$value = $viewDatas['entity']->$field ?: DEFAULTS['EMPTY']; $value = $viewDatas['entity']->$field ?: DEFAULTS['EMPTY'];
switch ($field) { switch ($field) {
case Model::TITLE: case $this->getService()->getModel()::TITLE:
$value = form_label( $value = form_label(
$value, $value,
'view', 'view',

View File

@ -2,7 +2,7 @@
namespace App\Libraries\MySocket\GoogleSocket; namespace App\Libraries\MySocket\GoogleSocket;
use App\Entities\UserSNSEntity; use App\Entities\UserSNSEntity as Entity;
use CodeIgniter\Exceptions\ConfigException; use CodeIgniter\Exceptions\ConfigException;
use Google\Client; use Google\Client;
use Google\Service\Oauth2; use Google\Service\Oauth2;
@ -115,7 +115,7 @@ class API extends GoogleSocket
// 'picture' => 'https://lh3.googleusercontent.com/a/VDSJj3D925VP-pt9ppnwsPtm4pyYE6IO7bei-RyVM0Q=s96-c', // 'picture' => 'https://lh3.googleusercontent.com/a/VDSJj3D925VP-pt9ppnwsPtm4pyYE6IO7bei-RyVM0Q=s96-c',
// 'verifiedEmail' => true, // 'verifiedEmail' => true,
// )) // ))
public function getUserSNSEntity(): UserSNSEntity public function getEntity(): Entity
{ {
$this->getClient()->setAccessToken($this->getToken()); $this->getClient()->setAccessToken($this->getToken());
$oauth = new Oauth2($this->getClient()); $oauth = new Oauth2($this->getClient());
@ -123,6 +123,6 @@ class API extends GoogleSocket
$detail = var_export($userInfo, true); $detail = var_export($userInfo, true);
// log_message("debug", $detail); // log_message("debug", $detail);
// 사용자정보 설정하기 // 사용자정보 설정하기
return $this->setUserSNSEntity($userInfo->id, $userInfo->name, $userInfo->email, $detail); return $this->setEntity($userInfo->id, $userInfo->name, $userInfo->email, $detail);
} }
} }

View File

@ -3,7 +3,7 @@
namespace App\Libraries\MySocket\GoogleSocket; namespace App\Libraries\MySocket\GoogleSocket;
use GuzzleHttp\Client; use GuzzleHttp\Client;
use App\Entities\UserSNSEntity; use App\Entities\UserSNSEntity as Entity;
class CURL extends GoogleSocket class CURL extends GoogleSocket
{ {
@ -133,7 +133,7 @@ class CURL extends GoogleSocket
// 'picture' => 'https://lh3.googleusercontent.com/a/AAcHTteFSgefsdfsdRJBkJA2tBEmg4PQrvI1Ta_5IXu5=s96-c', // 'picture' => 'https://lh3.googleusercontent.com/a/AAcHTteFSgefsdfsdRJBkJA2tBEmg4PQrvI1Ta_5IXu5=s96-c',
// 'verifiedEmail' => true, // 'verifiedEmail' => true,
// )) // ))
public function getUserSNSEntity(): UserSNSEntity public function getEntity(): Entity
{ {
$options = [ $options = [
"headers" => [ "headers" => [
@ -166,6 +166,6 @@ class CURL extends GoogleSocket
throw new \Exception($message); throw new \Exception($message);
} }
// 사용자정보 설정하기 // 사용자정보 설정하기
return $this->setUserSNSEntity($userInfo["id"], $userInfo["name"], $userInfo["email"], $detail); return $this->setEntity($userInfo["id"], $userInfo["name"], $userInfo["email"], $detail);
} }
} }

View File

@ -2,16 +2,18 @@
namespace App\Libraries\MySocket\GoogleSocket; namespace App\Libraries\MySocket\GoogleSocket;
use CodeIgniter\Session\Session; use App\Entities\UserSNSEntity as Entity;
use CodeIgniter\Exceptions\PageNotFoundException;
use App\Models\UserSNSModel;
use App\Libraries\MySocket\MySocket; use App\Libraries\MySocket\MySocket;
use App\Entities\UserSNSEntity; use App\Models\UserSNSModel as Model;
use App\Services\UserSNSService as Service;
use CodeIgniter\Exceptions\PageNotFoundException;
use CodeIgniter\Session\Session;
use Config\Services;
abstract class GoogleSocket extends MySocket abstract class GoogleSocket extends MySocket
{ {
private string $_site = "GOOGLE"; private string $_site = "GOOGLE";
private ?UserSNSModel $_model = null; private ?Service $_service = null;
protected $_client = null; protected $_client = null;
private ?Session $_session = null; private ?Session $_session = null;
protected string $_access_token = ""; protected string $_access_token = "";
@ -19,11 +21,11 @@ abstract class GoogleSocket extends MySocket
public function __construct() {} public function __construct() {}
abstract public function createAuthUrl(): string; abstract public function createAuthUrl(): string;
abstract public function setToken(string $access_code): void; abstract public function setToken(string $access_code): void;
abstract public function getUserSNSEntity(): UserSNSEntity; abstract public function getEntity(): Entity;
final public function getSession(): Session final public function getSession(): Session
{ {
if ($this->_session == null) { if ($this->_session == null) {
$this->_session = \Config\Services::session(); $this->_session = Services::session();
} }
return $this->_session; return $this->_session;
} }
@ -35,20 +37,21 @@ abstract class GoogleSocket extends MySocket
{ {
return $this->_site; return $this->_site;
} }
final protected function getModel(): UserSNSModel public function getService(): Service
{ {
if ($this->_model === null) { if ($this->_service === null) {
$this->_model = model(UserSNSModel::class); $this->_service = new Service();
} }
return $this->_model; return $this->_service;
} }
final protected function setUserSNSEntity(string $id, string $name, string $email, string $detail): UserSNSEntity final protected function setEntity(string $id, string $name, string $email, string $detail): Entity
{ {
$this->getModel()->where(UserSNSModel::SITE, $this->getSite()); $this->getService()->getModel()->where(Model::SITE, $this->getSite());
$entity = $this->getModel()->getEntityByID($id); $this->getService()->getModel()->where('id', $id);
$entity = $this->getEntity();
if ($entity === null) { if ($entity === null) {
//Transaction Start //Transaction Start
$this->getModel()->transStart(); $this->getService()->getModel()->transStart();
try { try {
//없다면 새로 등록 //없다면 새로 등록
$formDatas = [ $formDatas = [
@ -59,11 +62,11 @@ abstract class GoogleSocket extends MySocket
'detail' => $detail, 'detail' => $detail,
'status' => 'unuse', 'status' => 'unuse',
]; ];
$entity = $this->getModel()->create($formDatas); $entity = $this->getService()->getModel()->create($formDatas);
$this->getModel()->transCommit(); $this->getService()->getModel()->transCommit();
} catch (\Exception $e) { } catch (\Exception $e) {
//Transaction Rollback //Transaction Rollback
$this->getModel()->transRollback(); $this->getService()->getModel()->transRollback();
log_message("error", $e->getMessage()); log_message("error", $e->getMessage());
throw new \Exception(__FUNCTION__ . " 실패하였습니다.\n" . $e->getMessage()); throw new \Exception(__FUNCTION__ . " 실패하였습니다.\n" . $e->getMessage());
} }

View File

@ -49,9 +49,6 @@ abstract class CommonModel extends Model
{ {
parent::__construct(); parent::__construct();
} }
abstract public function getFields(): array;
abstract public function getFilterFields(): array;
abstract public function getBatchJobFields(): array;
abstract public function setList_WordFilter(string $word): void; abstract public function setList_WordFilter(string $word): void;
final public function getTable(): string final public function getTable(): string
@ -60,15 +57,18 @@ abstract class CommonModel extends Model
} }
final public function getPKField(): string final public function getPKField(): string
{ {
return constant("static::PKField"); return constant("static::PK");
} }
final public function getTitleField(): string final public function getTitleField(): string
{ {
return constant("static::TitleField"); return constant("static::TITLE");
} }
final public function getPairField(): string final protected function getFieldRules(string $action, array $fields, $rules = []): array
{ {
return constant("static::PairField"); foreach ($fields as $field) {
$rules[$field] = $this->getFieldRule($action, $field);
}
return $rules;
} }
public function getFieldRule(string $action, string $field): string public function getFieldRule(string $action, string $field): string
{ {
@ -105,27 +105,6 @@ abstract class CommonModel extends Model
} }
return $rule; return $rule;
} }
final public function getFieldRules(string $action, array $fields, $rules = []): array
{
foreach ($fields as $field) {
$rules[$field] = $this->getFieldRule($action, $field);
}
return $rules;
}
public function getFormFieldOption(string $field, array $options = []): array
{
switch ($field) {
default:
foreach ($this->getEntitys() as $entity) {
$options[$entity->getPK()] = $entity->getTitle();
}
break;
}
// dd($options);
return $options;
}
// create, modify 직전 작업용 작업 // create, modify 직전 작업용 작업
protected function convertEntityData(string $field, array $formDatas): mixed protected function convertEntityData(string $field, array $formDatas): mixed
{ {
@ -181,7 +160,7 @@ abstract class CommonModel extends Model
throw new \Exception($message); throw new \Exception($message);
} }
} }
final public function create(array $formDatas, $entity): mixed public function create(array $formDatas, $entity): mixed
{ {
// Field에 맞는 Validation Rule 재정의 // Field에 맞는 Validation Rule 재정의
$this->setValidationRules($this->getFieldRules('create', $this->allowedFields)); $this->setValidationRules($this->getFieldRules('create', $this->allowedFields));
@ -199,8 +178,7 @@ abstract class CommonModel extends Model
// log_message("debug", $this->getTable() . " => " . __FUNCTION__ . " DB 작업 완료"); // log_message("debug", $this->getTable() . " => " . __FUNCTION__ . " DB 작업 완료");
return $entity; return $entity;
} }
public function modify($entity, array $formDatas): mixed
final protected function modify(array $formDatas, $entity): mixed
{ {
// Field에 맞는 Validation Rule 재정의 // Field에 맞는 Validation Rule 재정의
$this->setValidationRules($this->getFieldRules('modify', $this->allowedFields)); $this->setValidationRules($this->getFieldRules('modify', $this->allowedFields));
@ -213,6 +191,7 @@ abstract class CommonModel extends Model
return $entity; return $entity;
} }
//List관련
final public function setList_FieldFilter(string $field, int|string $value): void final public function setList_FieldFilter(string $field, int|string $value): void
{ {
$this->where($this->getTable() . '.' . $field, $value); $this->where($this->getTable() . '.' . $field, $value);

View File

@ -25,18 +25,6 @@ class MyLogModel extends CommonModel
{ {
parent::__construct(); parent::__construct();
} }
public function getFields(): array
{
return ['class_name', 'method_name', self::TITLE, 'user_uid', 'status'];
}
public function getFilterFields(): array
{
return ['user_uid', 'status'];
}
public function getBatchJobFields(): array
{
return [];
}
public function getFieldRule(string $action, string $field): string public function getFieldRule(string $action, string $field): string
{ {
if (is_array($field)) { if (is_array($field)) {

View File

@ -26,18 +26,6 @@ class UserModel extends CommonModel
{ {
parent::__construct(); parent::__construct();
} }
public function getFields(): array
{
return ['id', self::TITLE, 'email', 'mobile', 'role', 'status'];
}
public function getFilterFields(): array
{
return ['role', 'status'];
}
public function getBatchJobFields(): array
{
return ['status'];
}
public function getFieldRule(string $action, string $field): string public function getFieldRule(string $action, string $field): string
{ {
if (is_array($field)) { if (is_array($field)) {
@ -81,16 +69,6 @@ class UserModel extends CommonModel
} }
return $value; return $value;
} }
public function getFormFieldOption(string $field, array $options = []): array
{
switch ($field) {
default:
$this->orderBy(self::TITLE, 'asc');
$options = parent::getFormFieldOption($field, $options);
break;
}
return $options;
}
//List 검색용 //List 검색용
public function setList_WordFilter(string $word): void public function setList_WordFilter(string $word): void
{ {

View File

@ -0,0 +1,74 @@
<?php
namespace App\Models;
use App\Entities\UserSNSEntity as Entity;
use App\Models\CommonModel;
class UserSNSModel extends CommonModel
{
const TABLE = "user_sns";
const PK = "uid";
const TITLE = "name";
const PARENT = "user_uid";
const SITE = "site";
protected $table = self::TABLE;
protected $primaryKey = self::PK;
protected $returnType = Entity::class;
protected $allowedFields = [
"site",
"user_uid",
"id",
"name",
"email",
"detail",
"status"
];
public function __construct()
{
parent::__construct();
}
public function getFieldRule(string $action, string $field): string
{
switch ($field) {
case "id":
$rule = "required|trim|min_length[4]|is_unique[{$this->table}.{$field}]";
break;
case $this->getTitleField():
$rule = "required|trim|string";
break;
case "site":
$rule = "required|trim|string";
break;
case "email":
$rule = "required|trim|valid_email";
break;
case "detail":
$rule = "required|trim|string";
break;
default:
$rule = parent::getFieldRule($action, $field);
break;
}
return $rule;
}
protected function convertEntityData(string $field, array $formDatas): mixed
{
switch ($field) {
case "detail": //content등 textarea를 사용한 Field
$value = htmlentities($formDatas[$field], ENT_QUOTES);
break;
default:
$value = parent::convertEntityData($field, $formDatas);
break;
}
return $value;
}
//List 검색용
public function setList_WordFilter(string $word): void
{
$this->orLike(self::TABLE . '.id', $word, 'both');
$this->orLike(self::TABLE . "." . self::TITLE, $word, 'both');
$this->orLike(self::TABLE . '.email', $word, 'both');
}
}

View File

@ -2,8 +2,8 @@
namespace App\Services\Auth; namespace App\Services\Auth;
use App\Entities\UserEntity; use App\Entities\UserEntity as Entity;
use App\Models\UserModel; use App\Models\UserModel as Model;
use App\Services\CommonService; use App\Services\CommonService;
use CodeIgniter\Session\Session; use CodeIgniter\Session\Session;
@ -11,12 +11,9 @@ use CodeIgniter\Session\Session;
abstract class AuthService extends CommonService abstract class AuthService extends CommonService
{ {
private ?Session $_session = null; private ?Session $_session = null;
private ?UserModel $_model = null; private ?Model $_model = null;
public function __construct() public function __construct() {}
{
parent::__construct();
}
final public function getSession(): Session final public function getSession(): Session
{ {
if ($this->_session === null) { if ($this->_session === null) {
@ -25,14 +22,6 @@ abstract class AuthService extends CommonService
return $this->_session; return $this->_session;
} }
final public function getModel(): UserModel
{
if ($this->_model === null) {
$this->_model = new UserModel();
}
return $this->_model;
}
private function getAuthInfo(string $key = ""): array|string private function getAuthInfo(string $key = ""): array|string
{ {
$authInfo = $this->getSession()->get(SESSION_NAMES['AUTH']); $authInfo = $this->getSession()->get(SESSION_NAMES['AUTH']);
@ -95,7 +84,7 @@ abstract class AuthService extends CommonService
return '/'; // 기본 URL return '/'; // 기본 URL
} }
final public function login(UserEntity $entity): void final public function login(Entity $entity): void
{ {
$this->getSession()->set(SESSION_NAMES['ISLOGIN'], true); $this->getSession()->set(SESSION_NAMES['ISLOGIN'], true);
$this->getSession()->set(SESSION_NAMES['AUTH'], [ $this->getSession()->set(SESSION_NAMES['AUTH'], [

View File

@ -2,7 +2,8 @@
namespace App\Services\Auth; namespace App\Services\Auth;
use App\Entities\UserEntity; use App\Models\UserModel as Model;
use App\Entities\UserEntity as Entity;
// use App\Libraries\MySocket\GoogleSocket\CURL; // use App\Libraries\MySocket\GoogleSocket\CURL;
use CodeIgniter\Exceptions\PageNotFoundException; use CodeIgniter\Exceptions\PageNotFoundException;
@ -18,12 +19,21 @@ class GoogleService extends AuthService
} }
final public function getClassName(): string final public function getClassName(): string
{ {
return "Google"; return "AuthGoogle";
} }
final public function getClassPath(): string final public function getClassPath(): string
{ {
return $this->getClassName(); return $this->getClassName();
} }
public function getModelClass(): string
{
return Model::class;
}
public function getEntityClass(): string
{
return Entity::class;
}
public function getMySocket(string $access_code): mixed public function getMySocket(string $access_code): mixed
{ {
if ($this->_mySocket === null) { if ($this->_mySocket === null) {
@ -33,7 +43,7 @@ class GoogleService extends AuthService
return $this->_mySocket; return $this->_mySocket;
} }
public function checkUser(string $access_code): UserEntity public function checkUser(string $access_code): Entity
{ {
try { try {
// Google 서비스 설정 // Google 서비스 설정

View File

@ -2,7 +2,8 @@
namespace App\Services\Auth; namespace App\Services\Auth;
use App\Entities\UserEntity; use App\Models\UserModel as Model;
use App\Entities\UserEntity as Entity;
class LocalService extends AuthService class LocalService extends AuthService
{ {
@ -12,13 +13,22 @@ class LocalService extends AuthService
} }
final public function getClassName(): string final public function getClassName(): string
{ {
return "Local"; return "AuthLocal";
} }
final public function getClassPath(): string final public function getClassPath(): string
{ {
return $this->getClassName(); return $this->getClassName();
} }
public function checkUser(array $formDatas): UserEntity public function getModelClass(): string
{
return Model::class;
}
public function getEntityClass(): string
{
return Entity::class;
}
public function checkUser(array $formDatas): Entity
{ {
if (!isset($formDatas['id']) || !$formDatas['id']) { if (!isset($formDatas['id']) || !$formDatas['id']) {
throw new \Exception("사용자ID를 입력해주세요!"); throw new \Exception("사용자ID를 입력해주세요!");
@ -27,7 +37,8 @@ class LocalService extends AuthService
throw new \Exception("암호를 입력해주세요!"); throw new \Exception("암호를 입력해주세요!");
} }
$entity = $this->getModel()->getEntityByID($formDatas['id']); $this->getModel()->where("id", $formDatas['id']);
$entity = $this->getEntity();
if (is_null($entity) || !isset($entity->passwd)) { if (is_null($entity) || !isset($entity->passwd)) {
throw new \Exception("사용자ID: {$formDatas['id']}가 존재하지 않습니다."); throw new \Exception("사용자ID: {$formDatas['id']}가 존재하지 않습니다.");
} }

View File

@ -8,10 +8,13 @@ abstract class CommonService
{ {
private $_serviceDatas = []; private $_serviceDatas = [];
private $_model = null; private $_model = null;
public function __construct() {} protected ?IncomingRequest $request = null;
public function __construct(IncomingRequest $_request)
{
$this->request = $_request;
}
abstract public function getModelClass(): string; abstract public function getModelClass(): string;
abstract public function getEntityClass(): string; abstract public function getEntityClass(): string;
final public function __get($name) final public function __get($name)
{ {
if (!array_key_exists($name, $this->_serviceDatas)) { if (!array_key_exists($name, $this->_serviceDatas)) {
@ -24,6 +27,10 @@ abstract class CommonService
$this->_serviceDatas[$name] = $value; $this->_serviceDatas[$name] = $value;
} }
final public function getRequest(): IncomingRequest|null
{
return $this->request;
}
final public function getModel(): mixed final public function getModel(): mixed
{ {
if ($this->_model === null) { if ($this->_model === null) {
@ -35,114 +42,39 @@ abstract class CommonService
} }
final public function getEntity(): mixed final public function getEntity(): mixed
{ {
$result = $this->getModel()->get(); return $this->getModel()->first();
if (!$result) { //결과값이 없으면 null
return $result;
}
$entityClass = $this->getEntityClass();
return new $entityClass($result);
} }
final public function getEntities(): array final public function getEntities(array $columns = ['*']): array
{ {
$entitys = []; $entitys = [];
foreach ($this->getModel()->getAll() as $result) { foreach ($this->getModel()->select(implode(',', $columns))->findAll() as $entity) {
$entityClass = $this->getEntityClass(); $entitys[$entity->getPK()] = $entity;
$entity = new $entityClass($result);
$pairField = $this->getModel()->getPairField();
// echo "pairField:" . $pairField . "<BR>";
$entitys[$entity->$pairField] = $entity;
} }
return $entitys; return $entitys;
} // } //
final public function getCount(string $select = "COUNT(*) as cnt", string $column = 'cnt'): int //FieldForm관련용
public function getFieldRule(string $action, string $field): string
{ {
return $this->getModel()->count($select, $column)->countAllResults(); if (is_array($field)) {
} throw new \Exception(__FUNCTION__ . "=> field가 array 입니다.\n" . var_export($field, true));
//List 조건절 처리
private function setConditionForList(IncomingRequest $request, array $filter_fields): void
{
//조건절 처리
foreach ($filter_fields as $field) {
$this->$field = $request->getVar($field) ?? DEFAULTS['EMPTY'];
if ($this->$field !== DEFAULTS['EMPTY']) {
$this->getModel()->setList_FieldFilter($field, $this->$field);
}
} }
//검색어 처리 switch ($field) {
$this->word = $request->getVar('word') ?? DEFAULTS['EMPTY'];
if ($this->word !== DEFAULTS['EMPTY']) {
$this->getModel()->setList_WordFilter($this->word);
}
//검색일 처리
$this->start = $request->getVar('start') ?? DEFAULTS['EMPTY'];
$this->end = $request->getVar('end') ?: DEFAULTS['EMPTY'];
$this->getModel()->setList_DateFilter($this->start, $this->end);
}
//PageNation 처리
protected function setPageOptionsByPaginationForList(): void
{
$this->page_options = array("" => "줄수선택");
for ($i = $this->per_page; $i <= $this->total_count; $i += $this->per_page) {
$this->page_options[$i] = $i;
}
$this->page_options[$this->total_count] = $this->total_count;
}
protected function setPaginationForList(IncomingRequest $request, $pager_group = 'default', int $segment = 0, $template = 'bootstrap_full'): void
{
//Page, Per_page필요부분
$this->page = (int) $request->getVar('page') ?: 1;
$this->per_page = (int) $request->getVar('per_page') ?: intval(DEFAULT_LIST_PERPAGE ?? 20);
//줄수 처리용
$this->setPageOptionsByPaginationForList();
// 1.Views/Pagers/에 bootstrap_full.php,bootstrap_simple.php 생성
// 2.app/Config/Pager.php/$templates에 'bootstrap_full => 'Pagers\bootstrap_full',
// 'bootstrap_simple' => 'Pagers\bootstrap_simple', 추가
$pager = service("pager");
// $this->getService()->getModel()->paginate($this->per_page, $pager_group, $this->page, $segment);
$pager->makeLinks($this->page, $this->per_page, $this->total_count, $template, $segment, $pager_group);
$this->page = $pager->getCurrentPage($pager_group);
$this->total_page = $pager->getPageCount($pager_group);
$this->pagination - $pager->links($pager_group, $template);
}
protected function setOrderByForList(): void
{
$this->order_field = $this->request->getVar('order_field') ?: DEFAULTS['EMPTY'];
$this->order_value = $this->request->getVar('order_value') ?: DEFAULTS['EMPTY'];
if ($this->order_field !== DEFAULTS['EMPTY'] && $this->order_value !== DEFAULTS['EMPTY']) {
$this->getModel()->orderBy(sprintf("%s.%s %s", $this->getModel()::TABLE, $this->order_field, $this->order_value));
} else {
$this->getModel()->orderBy(sprintf("%s.%s %s", $this->getModel()::TABLE, $this->getModel()::PK, "DESC"));
}
}
final public function getList(IncomingRequest $request, array $fields, array $filter_fields): array
{
//조건절 처리
$this->setConditionForList($request, $filter_fields);
//TotalCount
$this->total_count = $this->getCount();
//Pagination 처리
$this->setPaginationForList($request);
//limit, offset 설정
$this->getModel()->limit($this->per_page);
$this->getModel()->offset(($this->page - 1) * $this->per_page);
return $this->getEntities();
}
final public function isIPAddress(string $ip, $type = false): bool
{
switch ($type) {
case 'ipv4':
$result = filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);
break;
case 'ipv6':
$result = filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6);
break;
case 'all':
$result = filter_var($ip, FILTER_VALIDATE_IP);
break;
default: default:
$result = filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE); $rule = $this->getModel()->getFieldRule($action, $field);
break; break;
} }
return $result; return $rule;
}
public function getFormFieldOption(string $field, array $options = []): array
{
switch ($field) {
default:
foreach ($this->getEntities() as $entity) {
$options[$entity->getPK()] = $entity->getTitle();
}
break;
}
// dd($options);
return $options;
} }
} }

View File

@ -1,51 +0,0 @@
<?php
namespace App\Services;
use App\Models\MapurlModel;
use App\Entities\MapurlEntity;
use App\Traits\MylogTrait;
class MapurlService extends CommonService
{
use MylogTrait;
private ?MapurlModel $_model = null;
public function __construct()
{
parent::__construct();
}
final public function getClassName(): string
{
return "Mapurl";
}
final public function getClassPath(): string
{
return $this->getClassName();
}
public function getModel(): MapurlModel
{
if ($this->_model === null) {
$this->_model = new MapurlModel();
}
return $this->_model;
}
public function create(array $formDatas): MapurlEntity
{
$entity = $this->getModel()->create($formDatas);
//생성값 formDatas Log남기기
$this->add_MylogTrait(__FUNCTION__, $formDatas, $entity);
return $entity;
}
public function modify(MapurlEntity $entity, array $formDatas): MapurlEntity
{
//변경전 entity 값, 변경값 formDatas Log남기기
$this->add_MylogTrait(__FUNCTION__, $formDatas, $entity);
return $this->getModel()->modify($entity, $formDatas);
}
public function delete(MapurlEntity $entity): void
{
//삭제전 entity 값 Log남기기
$this->add_MylogTrait(__FUNCTION__, [], $entity);
$this->getModel()->delete($entity->getPK());
}
}

View File

@ -5,12 +5,15 @@ namespace App\Services;
use App\Entities\MyLogEntity as Entity; use App\Entities\MyLogEntity as Entity;
use App\Models\MyLogModel as Model; use App\Models\MyLogModel as Model;
use App\Services\Auth\AuthService; use App\Services\Auth\AuthService;
use CodeIgniter\HTTP\IncomingRequest;
class MyLogService class MyLogService extends CommonService
{ {
private static ?Model $_model = null;
private static $_logBuffers = []; private static $_logBuffers = [];
public function __construct() {} public function __construct(IncomingRequest $request)
{
parent::__construct($request);
}
final public function getClassName(): string final public function getClassName(): string
{ {
return "MyLog"; return "MyLog";
@ -19,20 +22,36 @@ class MyLogService
{ {
return $this->getClassName(); return $this->getClassName();
} }
static public function getModel(): Model public function getModelClass(): string
{ {
if (self::$_model === null) { return Model::class;
self::$_model = new Model();
}
return self::$_model;
} }
static public function add(string $level, string $message): void public function getEntityClass(): string
{ {
self::$_logBuffers[] = sprintf("%s[%s]: %s", date("H:i:s"), $level, $message); return Entity::class;
}
static public function log(string $message, string $level = "info"): void
{
self::$_logBuffers[$level] = sprintf("%s[%s]: %s", date("H:i:s"), $level, $message);
log_message($level, $message); log_message($level, $message);
} }
public function info(string $message): void
static public function save($service, string $method, AuthService $myauth, string $title, string $status = "unuse"): Entity {
self::log($message, 'info');
}
public function error(string $message): void
{
self::log($message, 'error');
}
public function warning(string $message): void
{
self::log($message, 'warning');
}
public function debug(string $message): void
{
self::log($message, 'debug');
}
public function save($service, string $method, AuthService $myauth, string $title): Entity
{ {
$formDatas = [ $formDatas = [
'user_uid' => $myauth->getUIDByAuthInfo(), 'user_uid' => $myauth->getUIDByAuthInfo(),
@ -40,10 +59,8 @@ class MyLogService
'method_name' => $method, 'method_name' => $method,
'title' => $title, 'title' => $title,
'content' => implode("\n", self::$_logBuffers), 'content' => implode("\n", self::$_logBuffers),
'status' => $status,
]; ];
self::$_logBuffers = []; self::$_logBuffers = [];
// dd($formDatas); return $this->getModel()->create($formDatas, new Entity());
return self::getModel()->create($formDatas, new Entity());
} }
} }

View File

@ -0,0 +1,46 @@
<?php
namespace App\Services;
use App\Models\UserSNSModel as Model;
use App\Entities\UserSNSEntity as Entity;
use CodeIgniter\HTTP\IncomingRequest;
// use Google\Service\AndroidEnterprise\Resource\Users;
class UserSNSService extends CommonService
{
protected ?IncomingRequest $request = null;
public function __construct(?IncomingRequest $request = null)
{
parent::__construct($request);
}
final public function getClassName(): string
{
return "UserSNS";
}
final public function getClassPath(): string
{
return $this->getClassName();
}
public function getModelClass(): string
{
return Model::class;
}
public function getEntityClass(): string
{
return Entity::class;
}
public function getFields(): array
{
return [$this->getModel()::PARENT, 'site', 'id', $this->getModel()::TITLE, 'email'];
}
public function getFilterFields(): array
{
return [$this->getModel()::PARENT, 'status'];
}
public function getBatchJobFields(): array
{
return [];
}
}

View File

@ -2,15 +2,16 @@
namespace App\Services; namespace App\Services;
use App\Models\UserModel; use App\Entities\UserEntity as Entity;
use App\Entities\UserEntity; use App\Models\UserModel as Model;
use CodeIgniter\HTTP\IncomingRequest;
class UserService extends CommonService class UserService extends CommonService
{ {
private ?UserModel $_model = null; protected ?IncomingRequest $request = null;
public function __construct() public function __construct(IncomingRequest $request)
{ {
parent::__construct(); parent::__construct($request);
} }
final public function getClassName(): string final public function getClassName(): string
{ {
@ -20,19 +21,30 @@ class UserService extends CommonService
{ {
return $this->getClassName(); return $this->getClassName();
} }
public function getModel(): UserModel public function getModelClass(): string
{ {
if ($this->_model === null) { return Model::class;
$this->_model = new UserModel();
}
return $this->_model;
} }
public function create(array $formDatas): UserEntity public function getEntityClass(): string
{
return Entity::class;
}
public function getFormFieldOption(string $field, array $options = []): array
{
switch ($field) {
default:
$this->getModel()->orderBy($this->getModel()::TITLE, 'ASC');
$options = parent::getFormFieldOption($field, $options);
break;
}
return $options;
}
public function create(array $formDatas): Entity
{ {
$formDatas['role'] = implode(DEFAULTS["DELIMITER_ROLE"], $formDatas['role']); $formDatas['role'] = implode(DEFAULTS["DELIMITER_ROLE"], $formDatas['role']);
return $this->getModel()->create($formDatas); return $this->getModel()->create($formDatas, new Entity());
} }
public function modify(UserEntity $entity, array $formDatas): UserEntity public function modify(Entity $entity, array $formDatas): Entity
{ {
// die(var_export($formDatas, true)); // die(var_export($formDatas, true));
//암호를 입력하지 않았을시는 변경하기 않게 하기위함 //암호를 입력하지 않았을시는 변경하기 않게 하기위함
@ -47,7 +59,7 @@ class UserService extends CommonService
// die(var_export($formDatas, true)); // die(var_export($formDatas, true));
return $this->getModel()->modify($entity, $formDatas); return $this->getModel()->modify($entity, $formDatas);
} }
public function delete(UserEntity $entity): void public function delete(Entity $entity): void
{ {
$this->getModel()->delete($entity); $this->getModel()->delete($entity);
} }

View File

@ -29,7 +29,7 @@
</thead> </thead>
<tbody> <tbody>
<?php $cnt = 0 ?> <?php $cnt = 0 ?>
<?php foreach ($viewDatas['entitys'] as $entity): ?> <?php foreach ($viewDatas['entities'] as $entity): ?>
<tr <?= $viewDatas['helper']->getListRowColor($entity) ?>> <tr <?= $viewDatas['helper']->getListRowColor($entity) ?>>
<?php $viewDatas['cnt'] = $viewDatas['total_count'] - (($viewDatas['page'] - 1) * $viewDatas['per_page'] + $cnt); ?> <?php $viewDatas['cnt'] = $viewDatas['total_count'] - (($viewDatas['page'] - 1) * $viewDatas['per_page'] + $cnt); ?>
<?php $viewDatas['entity'] = $entity; ?> <?php $viewDatas['entity'] = $entity; ?>