cfmgrv4/app/Controllers/MVController.php
2024-09-24 19:18:05 +09:00

308 lines
12 KiB
PHP

<?php
namespace App\Controllers;
use Psr\Log\LoggerInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\RedirectResponse;
abstract class MVController extends CommonController
{
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
helper('common');
}
abstract protected function getMyLibrary(): mixed;
abstract protected function create_process_submit(): void;
abstract protected function modify_process_submit(): void;
//Field별 Form Input Option용
protected function getFormFieldInputOption(string $field, array $options = []): array
{
switch ($field) {
default:
$options = [
"" => lang($this->class_name . '.label.' . $field) . ' 선택',
...lang($this->class_name . '.' . strtoupper($field)),
];
break;
}
return $options;
}
//Field별 Form Input용
protected function getFormFieldInput(string $field, string $value, array $inputs = []): array
{
switch ($field) {
case 'status':
$inputs[$field] = form_dropdown(
$field,
$this->getFormFieldInputOption($field),
$value
);
break;
case 'updated_at':
case 'created_at':
$inputs[$field] = form_input($field, $value, ["class" => " calender"]);
break;
default:
$inputs[$field] = form_input($field, $value);
break;
}
return $inputs;
}
final protected function getFormFieldInputs(array $inputs = []): array
{
foreach ($this->fields as $field) {
if (is_array($field)) {
throw new \Exception(__FUNCTION__ . "에서 field array 입니다.\n" . var_export($field, true));
}
$inputs = $this->getFormFieldInput($field, old($field) ?? DEFAULTS['EMPTY'], $inputs);
}
return $inputs;
}
//전송된 데이터 Rule
protected function getFormFieldRule(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->getMyLibrary()->getMyStorage()->getFieldRule($field, $rules);
break;
}
return $rules;
}
final protected function getFormFieldRules(array $rules = []): array
{
foreach ($this->fields as $field) {
$rules = $this->getFormFieldRule($field, $rules);
}
return $rules;
}
//전송된 데이터
protected function getFormData(string $field): void
{
switch ($field) {
default:
$this->formDatas[$field] = $this->request->getVar($field);
break;
}
}
final protected function getFormDatas(): void
{
foreach ($this->fields as $field) {
$this->getFormData($field);
}
}
//전송된 데이터 재정의
protected function convertFormData(string $field): void
{
switch ($field) {
default:
break;
}
}
final protected function convertFormDatas(): void
{
foreach ($this->fields as $field) {
$this->convertFormData($field);
}
}
//전송된 데이터 검증
protected function validateFormData(string $field): void
{
switch ($field) {
default:
if (
!$this->validation->check(
$this->formDatas[$field],
$this->getMyLibrary()->getMyStorage()->getFieldRule($field)
)
) {
throw new \Exception("데이터 검증 오류발생\n" . implode("\n", $this->validation->getError()));
}
break;
}
}
final protected function validateFormDatas(): void
{
//변경할 값 확인 : Upload된 파일 검증시 $this->request->getVar()보다 먼처 체크필요
$this->validation = service('validation');
foreach ($this->fields as $field) {
$this->validateFormData($field);
}
}
// 생성
final protected function create_form_process(): RedirectResponse|string
{
helper(['form']);
try {
$this->forminputs = $this->getFormFieldInputs();
$this->session->keepFlashdata(SESSION_NAMES['RETURN_URL']);
$this->forms = ['attributes' => ['method' => "post",], 'hiddens' => []];
return view(
strtolower($this->class_name) . "/create",
['viewDatas' => $this->getAttributes()]
);
} catch (\Exception $e) {
log_message("error", $e->getMessage());
return redirect()->to($this->session->getFlashdata(SESSION_NAMES['RETURN_URL']) ?: "/")->with(SESSION_NAMES['RETURN_MSG'], $e->getMessage());
}
}
final protected function create_process(): mixed
{
$this->getMyLibrary()->getMyStorage()->transStart();
try {
$this->create_process_submit();
return redirect()->to($this->session->getFlashdata(SESSION_NAMES['RETURN_URL']) ?: "/");
} catch (\Exception $e) {
//Transaction Rollback
$this->getMyLibrary()->getMyStorage()->transRollback();
log_message("error", $e->getMessage());
$this->session->setFlashdata(SESSION_NAMES['RETURN_MSG'], __FUNCTION__ . " 실패하였습니다.\n" . $e->getMessage());
$this->session->keepFlashdata(SESSION_NAMES['RETURN_URL']);
return redirect()->back()->withInput();
}
}
// 수정
final protected function modify_form_process(): RedirectResponse|string
{
helper(['form']);
try {
$this->forminputs = $this->getFormFieldInputs();
$this->session->keepFlashdata(SESSION_NAMES['RETURN_URL']);
$this->forms = ['attributes' => ['method' => "post",], 'hiddens' => []];
return view(
strtolower($this->class_name) . "/modify",
['viewDatas' => $this->getAttributes()]
);
} catch (\Exception $e) {
log_message("error", $e->getMessage());
return redirect()->to($this->session->getFlashdata(SESSION_NAMES['RETURN_URL']) ?: "/")->with(SESSION_NAMES['RETURN_MSG'], $e->getMessage());
}
}
final protected function modify_process(): mixed
{
$this->getMyLibrary()->getMyStorage()->transStart();
try {
$this->modify_process_submit();
return redirect()->to($this->session->getFlashdata(SESSION_NAMES['RETURN_URL']) ?: "/");
} catch (\Exception $e) {
//Transaction Rollback
$this->getMyLibrary()->getMyStorage()->transRollback();
log_message("error", $e->getMessage());
$this->session->setFlashdata(SESSION_NAMES['RETURN_MSG'], __FUNCTION__ . " 실패하였습니다.\n" . $e->getMessage());
$this->session->keepFlashdata(SESSION_NAMES['RETURN_URL']);
return redirect()->back()->withInput();
}
}
// 리스트
protected function list_condition($isTotalCount = false): void
{
//조건절 처리
foreach ($this->filter_fields as $field) {
$this->$field = $this->request->getVar($field) ?? DEFAULTS['EMPTY'];
if ($this->$field !== DEFAULTS['EMPTY']) {
$this->getMyLibrary()->getMyStorage()->setList_FieldFilter($field, $this->$field);
}
}
//검색어 처리
$this->word = $this->request->getVar('word') ?? DEFAULTS['EMPTY'];
if ($this->word !== DEFAULTS['EMPTY']) {
$this->getMyLibrary()->getMyStorage()->setList_WordFilter($this->word);
}
//검색일 처리
$this->start = $this->request->getVar('start') ?? DEFAULTS['EMPTY'];
$this->end = $this->request->getVar('end') ?? DEFAULTS['EMPTY'];
if ($this->start !== DEFAULTS['EMPTY'] && $this->end !== DEFAULTS['EMPTY']) {
$this->getMyLibrary()->getMyStorage()->setList_DateFilter($this->start, $this->end);
}
if (!$isTotalCount) {
//Sorting 처리
$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->getMyLibrary()->getMyStorage()->setList_OrderBy("{$this->order_field} {$this->order_value}");
}
}
}
//Totalcount 처리
protected function list_total(): int
{
$this->list_condition(true);
return $this->getMyLibrary()->getMyStorage()->countAllResults();
}
//PageNation 처리
protected function list_pagination($pager_group = 'default', int $segment = 0, $template = 'bootstrap_full'): string
{
//Page, Per_page필요부분
$this->page = (int)$this->request->getVar('page') ?? 1;
$this->per_page = (int)$this->request->getVar('per_page') ?? $this->_per_page;
//줄수 처리용
$page_options = array("" => "줄수선택");
for ($i = 10; $i <= $this->total_count + $this->per_page; $i += 10) {
$page_options[$i] = $i;
}
$this->page_options = form_dropdown(
'per_page',
$page_options,
$this->per_page
);
// 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->getMyLibrary()->getMyStorage()->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);
return $pager->links($pager_group, $template);
}
protected function list_entitys(): array
{
$this->list_condition();
if (array_key_exists('page', $this->_viewDatas)) {
$this->getMyLibrary()->getMyStorage()->limit(
$this->per_page,
$this->page * $this->per_page - $this->per_page
);
}
return $this->getMyLibrary()->getMyStorage()->findAll();
}
public function list_process(): string
{
try {
//URL처리
$this->uri = $this->request->getUri();
//total 처리
$this->total_count = $this->list_total();
//pagenation 처리
$this->pagination = $this->list_pagination();
//모델 처리
$this->entitys = $this->list_entitys();
// dd($this->getMyLibrary()->getMyStorage()->getLastQuery());
//setting return_url to session flashdata
$this->session->setFlashdata(SESSION_NAMES['RETURN_URL'], current_url() . '?' . $this->request->getUri()->getQuery() ?: "");
return view(
strtolower($this->class_name) . "/index",
['viewDatas' => $this->getAttributes()]
);
} catch (\Exception $e) {
log_message("error", $e->getMessage());
return alert_CommonHelper($e->getMessage(), "back");
// return redirect()->back()->with('return_message', $e->getMessage());
}
}
}