trafficmonitor/app/Controllers/CommonController.php

252 lines
11 KiB
PHP

<?php
namespace App\Controllers;
use App\Controllers\BaseController;
use App\DTOs\AuthDTO;
use App\Services\CommonService;
use App\Traits\LogTrait;
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
{
use LogTrait;
protected $authService = null;
protected $service = null;
protected $myAuth = null;
protected $action = null;
protected array $_paths = [];
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
//로그인관련
$this->authService = service('myauth');
$this->myAuth = AuthDTO::fromByAuthService($this->authService);
}
final public function getPaths(): array
{
return $this->_paths;
}
final protected function doValidation(string $action): array
{
$dynamicRules = [];
foreach ($this->service->getFormRules($action) as $field => $rule) {
list($field, $rule) = $this->getFormRule($action, $field, $rule);
$dynamicRules[$field] = $rule;
}
//변경할 값 확인 : Upload된 파일 검증시 $this->request->getPOST()보다 먼처 체크필요
if (!$this->validate($dynamicRules)) {
throw new \Exception(static::class . "에서 작업 데이터 검증 오류발생\n" . implode(
"\n",
$this->validator->getErrors()
));
}
return $this->validator->getValidated();
}
//공통 필수기능
protected function getFormRule(string $action, string $field, string $rule): array
{
switch ($field) {
default:
break;
}
return array($field, $rule);
}
protected function action_init_process(string $action, array $viewDatas = []): array
{
$viewDatas['action'] = $action;
$viewDatas['view_paths'] = $this->getPaths();
$viewDatas['view_file'] = $this->request->getVar('ActionTemplate') ?? $viewDatas['action'];
$viewDatas['formFields'] = $this->service->getFormFields();
$viewDatas['formFilters'] = $this->service->getFormFilters();
$viewDatas['formRules'] = $this->service->getFormRules($viewDatas['action']);
$viewDatas['formOptions'] = $this->service->getFormOptions($viewDatas['action']);
if (array_key_exists('formDatas', $viewDatas)) {
$viewDatas['formDatas'] = [];
}
return $viewDatas;
}
protected function action_post_process(string $action, array $viewDatas): string|RedirectResponse
{
$view_paths = array_key_exists('view_paths', $viewDatas) ? $viewDatas['paths'] : $this->getPaths();
$lastest_path = array_pop($view_paths); //paths는 마지막을 뺀 앞단까지만 남음
switch ($action) {
case 'create_form':
case 'modify_form':
// ✅ 중간 안내 화면으로
// return view('posts/success_redirect', [
// 'message' => '게시글이 성공적으로 등록되었습니다.',
// 'redirectUrl' => route_to('posts_list')
// ]);
// 중요한 작업 (결제 완료, 오류 등) → “로딩 페이지(View)”로 안내 후 JS redirect
$full_path = implode(DIRECTORY_SEPARATOR, [
...$view_paths,
$this->request->getVar('ActionTemplate') ?? $lastest_path,
array_key_exists('view_file', $viewDatas) ? $viewDatas['view_file'] : $action
]);
$view_datas = [
'control' => $viewDatas,
'forms' => ['attributes' => ['method' => "post",], 'hiddens' => []],
];
helper(['form', __FUNCTION__]);
$result = view($full_path, ['viewDatas' => $view_datas]);
break;
default:
// ✅ Flashdata로 성공 메시지 저장
// 일반 CRUD (create/update/delete) → Flashdata + redirect()
session()->setFlashdata('success', array_key_exists('message', $viewDatas) ?: static::class . "/{$action}이 완료되었습니다.");
$result = redirect()->route(
implode(DIRECTORY_SEPARATOR, $view_paths)
);
break;
}
return $result;
}
protected function create_form_process(array $viewDatas): array
{
return $viewDatas;
}
public function create_form(): string|RedirectResponse
{
try {
//초기화
$action = __FUNCTION__;
$viewDatas = ['formDatas' => []];
$viewDatas = $this->action_init_process($action, $viewDatas);
$viewDatas = $this->create_form_process($viewDatas);
return $this->action_post_process($action, $viewDatas);
} catch (\Exception $e) {
$viewDatas['error'] = $e->getMessage();
//리디렉션 대신 폼 뷰를 다시 렌더링하도록 form_post_process 호출
return $this->action_post_process($action, $viewDatas);
}
}
protected function create_process(string $action, array $viewDatas): string|RedirectResponse
{
$this->doValidation($action);
return $this->action_post_process($action, $viewDatas);
}
public function create(): string|RedirectResponse
{
try {
//초기화
$action = __FUNCTION__;
$viewDatas = ['formDatas' => $this->request->getPost()];
$viewDatas = $this->action_init_process($action, $viewDatas);
return $this->create_process($action, $viewDatas);
} catch (\Exception $e) {
return redirect()->back()->withInput()->with('error', $e->getMessage());
}
}
//리스트관련
//조건절 처리
// protected function index_condition_process(): void
// {
// //Filter조건절 처리
// $index_filters = [];
// foreach ($this->service->getFormFilters() as $field) {
// $value = $this->request->getVar($field) ?? null;
// if ($value) {
// $this->service->index_condition_filterField($field, $value);
// $index_filters[$field] = $value;
// }
// }
// $this->index_filters = $$index_filters;
// //검색어조건절 처리
// $index_word = $this->request->getVar('index_word');
// if ($index_word !== null && $index_word !== '') {
// $this->service->index_condition_filterWord($index_word);
// }
// $this->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->service->index_condition_filterDate($index_start, $index_end);
// }
// $this->service->setControlDatas('index_start', $index_start);
// $this->service->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->service->getEntities() as $entity) {
// $entities[] = $entity;
// }
// return $entities;
// }
// public function index(): RedirectResponse|string
// {
// try {
// $this->service->setAction(__FUNCTION__);
// $this->service->setFormFields();
// //전달값정의
// $this->service->setFormDatas($this->request->getGet());
// $this->service->setFormFilters();
// $this->service->setFormRules();
// $this->service->setFormOptions();
// //일괄작업용 Fields정의
// $this->service->setControlDatas('batchjob_fields', $this->service->getBatchjobFields());
// //일괄작업용 버튼정의
// $this->service->setControlDatas('batchjob_buttions', $this->service->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->service->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->service->setOrderBy($this->order_field, $this->order_value);
// $this->service->setLimit($this->per_page);
// $this->service->setOffset(($this->page - 1) * $this->per_page);
// $this->index_condition_process();
// $this->entities = $this->index_process();
// return $this->getResultSuccess();
// } catch (\Exception $e) {
// return $this->getResultFail($e->getMessage());
// }
// }
}