dbmsv2/app/Controllers/CommonController.php
2025-09-10 17:48:54 +09:00

714 lines
28 KiB
PHP

<?php
namespace App\Controllers;
use App\Controllers\BaseController;
use App\Libraries\LogCollector;
use App\Services\MyLogService;
use CodeIgniter\HTTP\DownloadResponse;
use CodeIgniter\HTTP\RedirectResponse;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Validation\Validation;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Reader\Html;
use PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf;
use Psr\Log\LoggerInterface;
abstract class CommonController extends BaseController
{
private $_myAuth = null;
private ?MyLogService $_myLogService = null;
private $_viewDatas = [];
abstract public function getService(): mixed;
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
$this->isLoggedIn = false;
$this->uri = $request->getUri();
if ($this->getMyAuth()->isLoggedIn()) {
$this->isLoggedIn = true;
$this->myAuthName = $this->getMyAuth()->getNameByAuthInfo();
$this->myAuthUID = $this->getMyAuth()->getUIDByAuthInfo();
}
}
final public function __get($name)
{
if (!array_key_exists($name, $this->_viewDatas)) {
return null;
}
return $this->_viewDatas[$name];
}
final public function __set($name, $value): void
{
$this->_viewDatas[$name] = $value;
}
final protected function getMyAuth(): mixed
{
if (!$this->_myAuth) {
$this->_myAuth = service('myauth');
}
return $this->_myAuth;
}
final protected function getViewDatas(): array
{
return $this->_viewDatas;
}
final protected function getMyLogService(): mixed
{
if (!$this->_myLogService) {
$this->_myLogService = new MyLogService();
}
return $this->_myLogService;
}
//Index,FieldForm관련
final protected function setAction(string $action): void
{
$this->getService()->setControlDatas('action', $action);
}
final protected function getAction(): string
{
if (!$this->getService()->getControlDatas('action')) {
throw new \Exception("action이 정의되지 않았습니다.");
}
return $this->getService()->getControlDatas('action');
}
//FormFields정의
final protected function getFormFields($fields = []): array
{
return array_merge($fields, $this->getService()->getControlDatas('actionFields'));
}
final protected function setFormFields(?array $fields = null): void
{
switch ($this->getAction()) {
case 'index':
$actionFields = $this->getService()->getIndexFields();
break;
case 'view':
$actionFields = $this->getService()->getViewFields();
break;
default:
$actionFields = $this->getService()->getFormFields();
break;
}
$this->getService()->setControlDatas('actionFields', is_array($fields) ? $fields : $actionFields);
}
final protected function getFormFilters($filters = []): array
{
return array_merge($filters, $this->getService()->getControlDatas('actionFilters'));
}
final protected function setFormFilters(?array $filters = null): void
{
switch ($this->getAction()) {
case 'index':
$actionFilters = $this->getService()->getIndexFilters();
break;
case 'view':
$actionFilters = $this->getService()->getViewFilters();
break;
default:
$actionFilters = $this->getService()->getFormFilters();
break;
}
$this->getService()->setControlDatas('actionFilters', is_array($filters) ? $filters : $actionFilters);
}
//FormRules정의
final protected function getFormRules(array $rules = []): array
{
foreach ($this->getService()->getControlDatas('field_rules') as $field => $rule) {
$rules[$field] = $rule;
}
return $rules;
}
final protected function setFormRules(): void
{
$rules = [];
foreach ($this->getService()->getControlDatas('actionFields') as $field) {
$rules = $this->getFormRule($field, $rules);
}
$this->getService()->setControlDatas('field_rules', $rules);
}
//FormOptions정의
final protected function getFormOptions(array $options = []): array
{
foreach ($this->getService()->getControlDatas('field_optons') as $field => $option) {
$options[$field] = $option;
}
return $options;
}
final protected function setFormOptions(): void
{
//기존 Filter Options 가져와서 field에 해당하는 option이 없으면 field를 key로 배열추가 후 다시 filter_options 전체 적용
$options = [];
foreach ($this->getService()->getControlDatas('actionFilters') as $field) {
$options[$field] = $this->getFormOption($field, $options);
}
$this->getService()->setControlDatas('field_optons', $options);
}
//FormDatas 전달값,Default값
final protected function getFormDatas(): array
{
return $this->getService()->getControlDatas('form_datas');
}
final protected function setFormDatas(array $requestDatas, array $formDatas = []): void
{
foreach ($this->getService()->getControlDatas('actionFields') as $field) {
$formDatas = $this->setFormData($field, $requestDatas, $formDatas);
}
$this->getService()->setControlDatas('form_datas', $formDatas);
}
//FormDatas 검증
final protected function doValidations(): void
{
//변경할 값 확인 : Upload된 파일 검증시 $this->request->getPOST()보다 먼처 체크필요
$validation = service('validation');
foreach ($this->getService()->getControlDatas('field_rules') as $field => $rule) {
$validation = $this->doValidation($validation, $field, $rule);
}
if (!$validation->run($this->getFormDatas())) {
throw new \Exception("{$this->getService()->getClassName()} 작업 데이터 검증 오류발생\n" . implode(
"\n",
$validation->getErrors()
));
}
// return $validation->getValidated();
}
//공통 필수기능
//FieldForm관련용
protected function getFormRule(string $field, array $rules = []): array
{
if (is_array($field)) {
throw new \Exception(__FUNCTION__ . "=> field가 array 입니다.\n" . var_export($field, true));
}
switch ($field) {
default:
$rules[$field] = $this->getService()->getFormRule($this->getAction(), $field);
break;
}
if (!is_array($rules)) {
throw new \Exception(__FUNCTION__ . "에서 {$field}의 Rules 값이 array가 아닙니다.\n" . var_export($rules, true));
}
return $rules;
}
protected function getFormOption(string $field, array $options = []): array
{
switch ($field) {
default:
$options = $this->getService()->getFormOption($field, $options);
break;
}
if (!is_array($options)) {
throw new \Exception(__FUNCTION__ . "에서 {$field}의 options 값이 array가 아닙니다.\n" . var_export($options, true));
}
return $options;
}
//FormData Field별 전달값 처리
protected function setFormData(string $field, array $requestDatas, array $formDatas): array
{
switch ($field) {
default:
$formDatas[$field] = $requestDatas[$field] ?? null;
break;
}
return $formDatas;
}
protected function doValidation(Validation $validation, string $field, string $rule): Validation
{
switch ($field) {
default:
$validation->setRule($field, $field, $rule);
break;
}
return $validation;
}
//Process Result처리
protected function getResultFail(string $message = MESSAGES["FAILED"]): RedirectResponse
{
// $this->getMyLogService()->save($this->getService()->getClassName(), $this->getAction(), $message, $this->getMyAuth()->getUIDByAuthInfo());
if ($this->request->getMethod() === 'POST') {
return redirect()->back()->withInput()->with('error', $message);
}
return redirect()->to($this->getMyAuth()->popPreviousUrl())->with('error', $message);
}
protected function getResultSuccess(string $message = MESSAGES["SUCCESS"], ?string $actionTemplate = null): RedirectResponse|string
{
helper(['form']);
switch ($this->getService()->getControlDatas('action')) {
case 'create':
case 'modify':
// $this->getMyLogService()->save($this->getService()->getClassName(), $this->getAction(), $message, $this->getMyAuth()->getUIDByAuthInfo());
$result = $this->view($this->entity->getPK());
break;
case 'create_form':
case 'modify_form':
case 'login_form':
case 'view':
case 'index':
case 'download':
$this->service = $this->getService();
$this->control = $this->getService()->getControlDatas();
$this->getService()->getHelper()->setViewDatas($this->getViewDatas());
$actionTemplate = $this->request->getVar('ActionTemplate') ?? $actionTemplate;
if ($actionTemplate) {
$view_file = $this->view_path . $actionTemplate . DIRECTORY_SEPARATOR . $this->getAction();
} else {
$view_file = $this->view_path . $this->getAction();
}
$result = view($view_file, ['viewDatas' => $this->getViewDatas()]);
break;
default:
$result = redirect()->to($this->getMyAuth()->popPreviousUrl())->with('error', $message);
break;
}
return $result;
}
//Index,FieldForm관련
//생성 기본기능
protected function create_form_process(): void {}
public function create_form(): RedirectResponse|string
{
try {
$this->setAction(__FUNCTION__);
$this->setFormFields();
$this->setFormFilters();
$this->setFormRules();
$this->setFormOptions();
//기본값정의
$this->setFormDatas($this->request->getGet());
$this->create_form_process();
helper(['form']);
$this->forms = ['attributes' => ['method' => "post",], 'hiddens' => []];
return $this->getResultSuccess();
} catch (\Exception $e) {
// dd($e->getMessage());
return $this->getResultFail($e->getMessage());
}
}
protected function create_process(array $formDatas): mixed
{
return $this->getService()->create($formDatas);
}
public function create(): RedirectResponse|string
{
$db = \Config\Database::connect();
$db->transStart();
try {
$this->setAction(__FUNCTION__);
$this->setFormFields();
$this->setFormFilters();
$this->setFormRules();
//전달값정의
$this->setFormDatas($this->request->getPost());
$this->doValidations();
$this->entity = $this->create_process($this->getFormDatas());
$db->transCommit();
return $this->getResultSuccess();
} catch (\Exception $e) {
$db->transRollback();
return $this->getResultFail($e->getMessage());
}
}
//수정 기본기능
protected function modify_form_process(mixed $entity): mixed
{
return $entity;
}
public function modify_form(mixed $uid): RedirectResponse|string
{
try {
$this->setAction(__FUNCTION__);
$this->setFormFields();
$this->setFormFilters();
$this->setFormRules();
$this->setFormOptions();
//기본값정의
$this->setFormDatas($this->request->getGet());
//기존 Entity 가져오기
$entity = $this->getService()->getEntity($uid);
if (!$entity) {
throw new \Exception("{$uid}에 대한 정보를 찾을수 없습니다.");
}
$this->entity = $this->modify_form_process($entity);
helper(['form']);
$this->forms = ['attributes' => ['method' => "post",], 'hiddens' => []];
return $this->getResultSuccess();
} catch (\Exception $e) {
return $this->getResultFail($e->getMessage());
}
}
protected function modify_process(mixed $entity, array $formDatas): mixed
{
return $this->getService()->modify($entity, $formDatas);
}
public function modify(int $uid): RedirectResponse|string
{
//Transaction Start
$db = \Config\Database::connect();
$db->transStart();
try {
$this->setAction(__FUNCTION__);
$this->setFormFields();
$this->setFormFilters();
$this->setFormRules();
//전달값정의
$this->setFormDatas($this->request->getPost());
$this->doValidations();
//기존 Entity 가져오기
$entity = $this->getService()->getEntity($uid);
if (!$entity) {
throw new \Exception("{$uid}에 대한 정보를 찾을수 없습니다.");
}
$this->entity = $this->modify_process($entity, $this->getFormDatas());
$db->transCommit();
return $this->getResultSuccess();
} catch (\Exception $e) {
$db->transRollback();
return $this->getResultFail($e->getMessage());
}
}
//단일필드작업기능
protected function toggle_process(mixed $entity, array $formDatas): mixed
{
return $this->getService()->toggle($entity, $formDatas);
}
public function toggle(mixed $uid, string $field): RedirectResponse|string
{
//Transaction Start
$db = \Config\Database::connect();
$db->transStart();
try {
$this->setAction(__FUNCTION__);
$this->setFormFields([$field]);
$this->setFormRules();
//기본값정의
$this->setFormDatas($this->request->getGet());
$this->doValidations();
//기존 Entity 가져오기
$entity = $this->getService()->getEntity($uid);
if (!$entity) {
throw new \Exception("{$uid}에 대한 정보를 찾을수 없습니다.");
}
$this->entity = $this->toggle_process($entity, $this->getFormDatas());
$db->transCommit();
return $this->getResultSuccess();
} catch (\Exception $e) {
$db->transRollback();
return $this->getResultFail($e->getMessage());
}
}
//일괄처리작업기능
protected function batchjob_process(mixed $entity, array $formDatas): mixed
{
return $this->getService()->batchjob($entity, $formDatas);
}
private function batchjob_pre_process(): array
{
$selectedFields = [];
$formDatas = [];
foreach ($this->getService()->getBatchjobFields() as $field) {
$value = $this->request->getPost($field);
if ($value) {
$selectedFields[] = $field;
$formDatas[$field] = $value;
}
}
if (!count($selectedFields)) {
throw new \Exception("변경할 조건항목을 선택하셔야합니다.");
}
//변경할 UIDS 정의
$uids = $this->request->getPost('batchjob_uids[]');
if (!is_array($uids) || !count($uids)) {
throw new \Exception("적용할 리스트을 선택하셔야합니다.");
}
return [$selectedFields, $formDatas, $uids];
}
public function batchjob(): RedirectResponse|string
{
//Transaction Start
$db = \Config\Database::connect();
$db->transStart();
try {
$this->setAction(__FUNCTION__);
list($selectedFields, $formDatas, $uids) = $this->batchjob_pre_process();
$this->setFormFields($selectedFields);
$this->setFormRules();
//기본값정의
$this->setFormDatas($this->request->getPost());
$this->doValidations();
$entities = [];
foreach ($uids as $uid) {
//기존 Entity 가져오기
$entity = $this->getService()->getEntity($uid);
if (!$entity) {
throw new \Exception("{$uid}에 대한 정보를 찾을수 없습니다.");
}
$entities[] = $this->batchjob_process($entity, $formDatas);
}
$this->entities = $entities;
$db->transCommit();
LogCollector::debug(sprintf("%s에서 총 %s개중 %s개 일괄작업을 완료하였습니다.", __METHOD__, count($uids), count($this->entities)));
return $this->getResultSuccess();
} catch (\Exception $e) {
$db->transRollback();
return $this->getResultFail($e->getMessage());
}
}
//삭제관련
protected function delete_process(mixed $entity): mixed
{
return $this->getService()->delete($entity);
}
public function delete(mixed $uid): RedirectResponse|string
{
//Transaction Start
$db = \Config\Database::connect();
$db->transStart();
try {
$this->setAction(__FUNCTION__);
//기존 Entity 가져오기
$entity = $this->getService()->getEntity($uid);
if (!$entity) {
throw new \Exception("{$uid}에 대한 정보를 찾을수 없습니다.");
}
$this->delete_process($entity);
$db->transCommit();
return $this->getResultSuccess();
} catch (\Exception $e) {
$db->transRollback();
return $this->getResultFail($e->getMessage());
}
}
//일괄삭제관련
protected function batchjob_delete_process(mixed $entity): mixed
{
return $this->getService()->delete($entity);
}
private function batchjob_delete_pre_process(): array
{
//변경할 UIDS
$uids = $this->request->getPost('batchjob_uids[]');
if (!is_array($uids) || !count($uids)) {
throw new \Exception("적용할 리스트를 선택하셔야합니다.");
}
return $uids;
}
public function batchjob_delete(): RedirectResponse|string
{
//Transaction Start
$db = \Config\Database::connect();
$db->transStart();
try {
$this->setAction(__FUNCTION__);
$uids = $this->batchjob_delete_pre_process();
$entities = [];
foreach ($uids as $uid) {
//기존 Entity 가져오기
$entity = $this->getService()->getEntity($uid);
if (!$entity) {
throw new \Exception("{$uid}에 대한 정보를 찾을수 없습니다.");
}
$entities[] = $this->batchjob_delete_process($entity);
}
$this->entities = $entities;
$db->transCommit();
LogCollector::debug(sprintf("%s에서 총 %s개중 %s개 일괄삭제를 완료하였습니다.", __METHOD__, count($uids), count($this->entities)));
return $this->getResultSuccess();
} catch (\Exception $e) {
$db->transRollback();
return $this->getResultFail($e->getMessage());
}
}
//View 관련
protected function view_process(mixed $entity): mixed
{
return $entity;
}
public function view(string $uid): RedirectResponse|string
{
try {
$this->setAction(__FUNCTION__);
$this->setFormFields();
$this->setFormFilters();
$this->setFormRules();
$this->setFormOptions();
//기본값정의
$this->setFormDatas($this->request->getGet());
//기존 Entity 가져오기
$entity = $this->getService()->getEntity($uid);
if (!$entity) {
throw new \Exception("{$uid}에 대한 정보를 찾을수 없습니다.");
}
$this->entity = $this->view_process($entity);
helper(['form']);
$this->forms = ['attributes' => ['method' => "post",], 'hiddens' => []];
return $this->getResultSuccess();
} catch (\Exception $e) {
return $this->getResultFail($e->getMessage());
}
}
//리스트관련
//조건절 처리
protected function index_condition_process(): void
{
//Filter조건절 처리
$index_filters = [];
foreach ($this->getService()->getControlDatas('actionFilters') as $field) {
$value = $this->request->getGet($field);
if ($value) {
$this->getService()->index_condition_filterField($field, $value);
$index_filters[$field] = $value;
}
}
$this->getService()->setControlDatas('index_filters', $index_filters);
//검색어조건절 처리
$index_word = $this->request->getVar('index_word');
if ($index_word !== null && $index_word !== '') {
$this->getService()->index_condition_filterWord($index_word);
}
$this->getService()->setControlDatas('index_word', $index_word);
//날자검색
$index_start = $this->request->getVar('index_start');
$index_end = $this->request->getVar('index_end');
if ($index_start !== null && $index_start !== '' && $index_end !== null && $index_end !== '') {
$this->getService()->index_condition_filterDate($index_start, $index_end);
}
$this->getService()->setControlDatas('index_start', $index_start);
$this->getService()->setControlDatas('index_end', $index_end);
}
//PageNation 처리
protected function index_pagenation_process($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);
// 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");
$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);
return $pager->links($pager_group, $template);
}
//Page출력 처리
protected function index_pageOptions_process(): array
{
$page_options = ["" => "줄수선택"];
for ($i = $this->per_page; $i <= $this->total_count; $i += $this->per_page) {
$page_options[$i] = $i;
}
$page_options[$this->total_count] = $this->total_count;
return $page_options;
}
//Entities처리
protected function index_process(array $entities = []): array
{
foreach ($this->getService()->getEntities() as $entity) {
$entities[] = $entity;
}
return $entities;
}
public function index(): RedirectResponse|string
{
try {
$this->setAction(__FUNCTION__);
$this->setFormFields();
$this->setFormFilters();
$this->setFormRules();
//기본값정의
$this->setFormDatas($this->request->getGet());
$this->setFormOptions();
//일괄작업용 Fields정의
$this->getService()->setControlDatas('batchjob_fields', $this->getService()->getBatchjobFields());
//일괄작업용 버튼정의
$this->getService()->setControlDatas('batchjob_buttions', $this->getService()->getBatchjobButtons());
helper(['form']);
//Return Url정의
$this->getMyAuth()->pushCurrentUrl($this->request->getUri()->getPath() . ($this->request->getUri()->getQuery() ? "?" . $this->request->getUri()->getQuery() : ""));
//조건절 처리
$this->index_condition_process();
//TotalCount (SoftDelete적용이 되려면 countAllResults를 사용해야함)
$this->total_count = $this->getService()->getTotalCount();
//Pagination 처리
$this->pagination = $this->index_pagenation_process();
//줄수 처리용
$this->page_options = $this->index_pageOptions_process();
//조건절 처리
//OrcerBy , Limit 처리
$this->order_field = $this->request->getVar('order_field');
$this->order_value = $this->request->getVar('order_value');
$this->getService()->setOrderBy($this->order_field, $this->order_value);
$this->getService()->setLimit($this->per_page);
$this->getService()->setOffset(($this->page - 1) * $this->per_page);
$this->index_condition_process();
$this->entities = $this->index_process();
return $this->getResultSuccess();
} catch (\Exception $e) {
return $e->getMessage();
// return $this->getResultFail($e->getMessage());
}
}
//OUPUT Document 관련
private function download_process(string $document_type, mixed $loaded_data): array
{
$full_path = WRITEPATH . DIRECTORY_SEPARATOR . "excel";
switch ($document_type) {
case 'excel':
$file_name = sprintf("%s_%s.xlsx", $this->getService()->getClassName(), date('Y-m-d_Hm'));
$writer = IOFactory::createWriter($loaded_data, 'Xlsx');
$writer->save($full_path . DIRECTORY_SEPARATOR . $file_name);
break;
case 'pdf':
$file_name = sprintf("%s_%s.pdf", $this->getService()->getClassName(), date('Y-m-d_Hm'));
$writer = new Mpdf($loaded_data);
$writer->save($full_path . DIRECTORY_SEPARATOR . $file_name);
break;
}
return array($full_path, $file_name);
}
// Download
public function download(string $output_type, mixed $uid = false): DownloadResponse|RedirectResponse|string
{
try {
$this->setAction(__FUNCTION__);
$this->setFormFields();
$this->setFormFilters();
$this->setFormRules();
$this->setFormOptions();
//URL처리
// $this->uri = $this->request->getUri();
switch ($output_type) {
case 'excel':
case 'pdf':
helper(['form']);
$this->index_process();
$html = $this->getResultSuccess();
//data loading
$reader = new Html();
$loaded_data = $reader->loadFromString($html);
list($full_path, $file_name) = $this->download_process($output_type, $loaded_data);
$full_path .= DIRECTORY_SEPARATOR . $file_name;
break;
default:
if (!$uid) {
throw new \Exception("{$output_type}은 반드시 uid의 값이 필요합니다.");
}
$entity = $this->getService()->getEntity($uid);
if (!$entity) {
throw new \Exception("{$uid}에 대한 정보를 찾을수 없습니다.");
}
$this->entity = $entity;
list($file_name, $uploaded_filename) = $entity->getDownlaodFile();
$full_path = WRITEPATH . DIRECTORY_SEPARATOR . "uploads" . DIRECTORY_SEPARATOR . $uploaded_filename;
break;
}
return $this->response->download($full_path, null)->setFileName($file_name);
} catch (\Exception $e) {
return $this->getResultFail($e->getMessage());
}
}
}