myauth = service('myauth'); } 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 public function getService(): mixed { if (!$this->_service) { $serviceClass = $this->getServiceClass(); $this->_service = new $serviceClass($this->request); // $this->_service->setDebug(true); } return $this->_service; } protected function getResultPageByActon(string $action, string $message = MESSAGES["SUCCESS"]): RedirectResponse|string { switch ($action) { case 'create_form': case 'modify_form': case 'index': case 'view': $result = view($this->view_path . $action, ['viewDatas' => $this->getViewDatas()]); break; default: $result = redirect()->to($this->myauth->popPreviousUrl())->with('error', $message); break; } return $result; } final public function getViewDatas(): array { 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 getFormFieldOption(string $field, array $options): array { switch ($field) { default: $options[$field] = lang($this->getService()->getClassPath() . '.' . strtoupper($field)); // dd($options); break; } // dd($options); return $options; } final protected function getFormFieldOptions(array $fields, array $options = []): array { foreach ($fields as $field) { if (is_array($field)) { throw new \Exception(__FUNCTION__ . "에서 field array 입니다.\n" . var_export($field, true)); } $options = $this->getFormFieldOption($field, $options); } // dd($options); return $options; } protected function setValidation(Validation $validation, string $action, string $field, ?string $rule = null): Validation { switch ($field) { default: $validation->setRule($field, $field, $rule ?? $this->getService()->getModel()->getFieldRule($action, $field)); break; } return $validation; } //Index,FieldForm관련 //Field관련 protected function init(string $action, array $fields = []): void { $this->action = $action; $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->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->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->batchjob_fields = array_key_exists('batchjob_fields', $fields) && is_array($fields['batchjob_fields']) && count($fields['batchjob_fields']) ? $fields['filter_fields'] : $this->getBatchJobFields(); } //데이터 검증 final protected function doValidate(string $action, array $fields): array { //변경할 값 확인 : Upload된 파일 검증시 $this->request->getPOST()보다 먼처 체크필요 $validation = service('validation'); // var_dump($this->field_rules); // exit; foreach ($fields as $field) { $validation = $this->setValidation($validation, $this->action, $field, $this->field_rules[$field] ?? null); } if (!$validation->withRequest($this->request)->run()) { throw new \Exception("{$this->getService()->getClassName()} 작업 데이터 검증 오류발생\n" . implode( "\n", $validation->getErrors() )); } return $validation->getValidated(); } // 생성 protected function create_form_process(): void {} public function create_form(): RedirectResponse|string { try { $this->init(__FUNCTION__); helper(['form']); $this->create_form_process(); $this->forms = ['attributes' => ['method' => "post",], 'hiddens' => []]; return $this->getResultPageByActon($this->action); } catch (\Exception $e) { return redirect()->back()->withInput()->with('error', $e->getMessage()); } } protected function create_process(): mixed { //데이터 검증 $this->formDatas = $this->doValidate($this->action, $this->fields); return $this->getService()->create($this->formDatas); } public function create(): RedirectResponse|string { //Transaction Start $this->getService()->getModel()->transStart(); try { $this->init(__FUNCTION__); helper(['form']); $this->entity = $this->create_process(); $this->getService()->getModel()->transCommit(); return $this->getResultPageByActon($this->action); } catch (\Exception $e) { //Transaction Rollback $this->getService()->getModel()->transRollback(); return redirect()->back()->withInput()->with('error', $e->getMessage()); } } //수정관련 protected function modify_form_process(mixed $uid): mixed { $this->getService()->getModel()->where($this->getService()->getModel()::PK, $uid); $entity = $this->getService()->getEntity(); if (!$entity) { throw new \Exception("해당 정보를 찾을수 없습니다."); } return $entity; } public function modify_form(mixed $uid): RedirectResponse|string { try { $this->init(__FUNCTION__); helper(['form']); $this->entity = $this->modify_form_process($uid); $this->forms = ['attributes' => ['method' => "post",], 'hiddens' => []]; return $this->getResultPageByActon($this->action); } catch (\Exception $e) { return redirect()->back()->withInput()->with('error', $e->getMessage()); } } 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(); return $this->getResultPageByActon($this->action); } catch (\Exception $e) { //Transaction Rollback $this->getService()->getModel()->transRollback(); return redirect()->back()->withInput()->with('error', $e->getMessage()); } } //단일필드작업 protected function toggle_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); } final public function toggle(mixed $uid, string $field): RedirectResponse { //Transaction Start $this->getService()->getModel()->transStart(); try { $this->action = __FUNCTION__; $this->fields = [$field]; $this->entity = $this->toggle_process($uid); $this->getService()->getModel()->transCommit(); return $this->getResultPageByActon($this->action); } catch (\Exception $e) { $this->getService()->getModel()->transRollback(); return redirect()->back()->withInput()->with('error', $e->getMessage()); } } //일괄처리작업 protected function batchjob_process(string $uids): array { $temps = []; foreach (explode(",", $uids) as $uid) { $entity = $this->getService()->getEntity(); if (!$entity) { throw new \Exception("{$uid} 정보를 찾을수 없습니다."); } $temps[] = $entity; } $entities = []; foreach ($temps as $entity) { $entities[] = $this->getService()->modify($entity, $this->formDatas); } return $entities; } final public function batchjob(): RedirectResponse { //Transaction Start $this->getService()->getModel()->transStart(); try { $this->init(__FUNCTION__); //변경할 UIDS $uids = $this->request->getVar('batchjob_uids'); if (!$uids) { throw new \Exception("적용할 리스트를 선택하셔야합니다."); } //데이터가 있는경우 Field만 처리하기위해 $fields = []; foreach ($this->batchjob_fields as $field) { if ($this->request->getVar($field)) { $fields[$field] = $field; } } //데이터 검증 $this->formDatas = $this->doValidate($this->action, $fields); $this->entities = $this->batchjob_process($uids); return $this->getResultPageByActon($this->action); } catch (\Exception $e) { //Transaction Rollback $this->getService()->getModel()->transRollback(); return redirect()->back()->withInput()->with('error', $e->getMessage()); } } //삭제,일괄삭제 공통사용 protected function delete_process(mixed $entity): bool { $result = $this->getService()->delete($entity); if (!$result) { throw new \Exception("[$entity->getTitle()] 삭제를 실패하였습니다."); } return $result; } public function delete(mixed $uid): RedirectResponse|string { //Transaction Start $this->getService()->getModel()->transStart(); try { $this->init(__FUNCTION__); $this->getService()->getModel()->where($this->getService()->getModel()::PK, $uid); $entity = $this->getService()->getEntity(); if (!$entity) { throw new \Exception("{$uid} 정보를 찾을수 없습니다."); } $this->entity = $this->delete_process($entity); $this->getService()->getModel()->transCommit(); return $this->getResultPageByActon($this->action); } catch (\Exception $e) { //Transaction Rollback $this->getService()->getModel()->transRollback(); return redirect()->back()->withInput()->with('error', $e->getMessage()); } } //일괄삭제 protected function batchjob_delete_process(string $uids): void { $entities = []; foreach (explode(",", $uids) as $uid) { $this->getService()->getModel()->where($this->getService()->getModel()::PK, $uid); $entity = $this->getService()->getEntity(); if (!$entity) { throw new \Exception("{$uid} 정보를 찾을수 없습니다."); } $entities[] = $entity; } foreach ($entities as $entity) { try { if ($this->getService()->delete($entity)) { MyLogService::debug("[{$entity->getTitle()}]" . MESSAGES["DELETED"]); } } catch (PDOException $e) { MyLogService::debug("[{$entity->getTitle()}]" . MESSAGES["FAILED"] . ":" . $e->getMessage()); } } } final public function batchjob_delete(): RedirectResponse|string { //Transaction Start $this->getService()->getModel()->transStart(); try { $this->init(__FUNCTION__); //변경할 UIDS $uids = $this->request->getVar('batchjob_uids'); if (!$uids) { throw new \Exception("적용할 리스트를 선택하셔야합니다."); } $this->batchjob_delete_process($uids); MyLogService::save($this->getService(), __FUNCTION__, $this->myauth, MESSAGES["SUCCESS"]); $this->getService()->getModel()->transCommit(); return $this->getResultPageByActon($this->action); } catch (\Exception $e) { //Transaction Rollback $this->getService()->getModel()->transRollback(); MyLogService::save($this->getService(), __FUNCTION__, $this->myauth, MESSAGES["FAILED"]); return redirect()->back()->withInput()->with('error', $e->getMessage()); } } //View protected function view_process($uid): mixed { //자신정보정의 $this->getService()->getModel()->where($this->getService()->getModel()::PK, $uid); $entity = $this->getService()->getEntity(); if (!$entity) { throw new \Exception("해당 사용자정보를 찾을수 없습니다."); } return $entity; } public function view(string $uid): RedirectResponse|string { try { $this->init(__FUNCTION__); $this->entity = $this->view_process($uid); helper(['form']); $this->forms = ['attributes' => ['method' => "post",], 'hiddens' => []]; return $this->getResultPageByActon($this->action); } catch (\Exception $e) { return redirect()->back()->withInput()->with('error', $e->getMessage()); } } //리스트 //List 조건절 처리 protected function setConditionForList(array $filter_fields): void { //조건절 처리 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 처리 protected function getPageOptionsByPaginationForList(): 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; } 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 생성 // 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); return $pager->links($pager_group, $template); } 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_value = $this->request->getVar('order_value') ?: DEFAULTS['EMPTY']; if ($this->order_field !== DEFAULTS['EMPTY'] && $this->order_value !== DEFAULTS['EMPTY']) { $this->getService()->getModel()->orderBy(sprintf("%s.%s %s", $this->getService()->getModel()::TABLE, $this->order_field, $this->order_value)); } else { $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(); } public function index() { try { $this->init(__FUNCTION__); $this->entities = $this->index_process(); // 현재 URL을 스택에 저장 $this->myauth->pushCurrentUrl($this->request->getUri()->getPath() . ($this->request->getUri()->getQuery() ? "?" . $this->request->getUri()->getQuery() : "")); helper(['form']); return $this->getResultPageByActon($this->action); } catch (\Exception $e) { return redirect()->back()->withInput()->with('error', $e->getMessage()); } } //OUPUT Document 관련 private function download_process_save(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; default: if (!is_file($full_path)) { throw new \Exception("첨부파일이 확인되지 않습니다.\n"); } // //oupuput directly // header("Content-Type: application/vnd.ms-excel"); // header(sprintf("Content-Disposition: attachment; filename=%s", urlencode($output_name))); // header("Expires: 0"); // header("Cache-Control: must-revalidate"); // header("Pragma: public"); // header("Content-Length:" . filesize($full_path)); // return $writer->save('php://output'); break; } return array($full_path, $file_name); } //File Download관련 protected function download_process(string $output_type, mixed $uid = false): DownloadResponse|RedirectResponse { try { helper(['form']); //URL처리 $this->uri = $this->request->getUri(); switch ($output_type) { case 'excel': case 'pdf': // string buffer에서 읽어오는 경우 $this->entities = $this->index_process(); $html = view('templates' . DIRECTORY_SEPARATOR . $this->action, ['viewDatas' => $this->getViewDatas()]); //data loading $reader = new Html(); $loaded_data = $reader->loadFromString($html); list($full_path, $file_name) = $this->download_process_save($output_type, $loaded_data); $full_path .= DIRECTORY_SEPARATOR . $file_name; break; default: if (!$uid) { throw new \Exception("{$output_type}은 반드시 uid의 값이 필요합니다."); } $this->getService()->getModel()->where($this->getService()->getModel()::PK, $uid); $this->entity = $this->getService()->getEntity(); if (!$this->entity) { throw new \Exception("{$uid} 정보를 찾을수 없습니다."); } list($file_name, $uploaded_filename) = $this->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 redirect()->back()->withInput()->with('error', $e->getMessage()); } } // Download final public function download(string $output_type, mixed $uid = false): DownloadResponse|string { $this->init(__FUNCTION__); return $this->download_process($output_type, $uid); } }