_classPaths[] = $path; } final public function getClassPaths($isArray = true, $delimeter = DIRECTORY_SEPARATOR): array|string { return $isArray ? $this->_classPaths : implode($delimeter, $this->_classPaths); } /** * 단일 엔티티를 조회합니다. * @return CommonEntity|null CommonEntity 인스턴스 또는 찾지 못했을 경우 null */ final public function getEntity(string|int|array $where, ?string $message = null): ?CommonEntity { try { $entity = is_array($where) ? $this->model->where($where)->first() : $this->model->find($where); if (!$entity) { return null; } if (!$entity instanceof CommonEntity) { throw new \Exception(__METHOD__ . "에서 결과값 오류발생:\n" . var_export($entity, true)); } return $this->getEntity_process($entity); } catch (DatabaseException $e) { $errorMessage = sprintf( "\n------DB Query 오류 (%s)-----\nQuery: %s\nError: %s\n------------------------------\n", __FUNCTION__, $this->model->getLastQuery() ?? "No Query Available", $e->getMessage() ); log_message('error', $errorMessage); throw new RuntimeException($errorMessage, $e->getCode(), $e); } catch (\Exception $e) { $errorMessage = sprintf( "\n------일반 오류 (%s)-----\nError: %s\n------------------------------\n", __FUNCTION__, $e->getMessage() ); throw new \Exception($errorMessage, $e->getCode(), $e); } } final public function getEntities(mixed $where = null, array $columns = ['*']): array { try { $entities = $this->getEntities_process($where, $columns); log_message('debug', $this->model->getLastQuery()); return $entities; } catch (DatabaseException $e) { $errorMessage = sprintf( "\n------DB Query 오류 (%s)-----\nQuery: %s\nError: %s\n------------------------------\n", __FUNCTION__, $this->model->getLastQuery() ?? "No Query Available", $e->getMessage() ); log_message('error', $errorMessage); throw new RuntimeException($errorMessage, $e->getCode(), $e); } catch (\Exception $e) { $errorMessage = sprintf( "\n------일반 오류 (%s)-----\nError: %s\n------------------------------\n", __FUNCTION__, $e->getMessage() ); throw new \Exception($errorMessage, $e->getCode(), $e); } } final public function getNextPK(): int { $pkField = $this->model->getPKField(); $row = $this->model->selectMax($pkField)->get()->getRow(); return isset($row->{$pkField}) ? ((int)$row->{$pkField} + 1) : 1; } //Entity관련 protected function getEntity_process(CommonEntity $entity): CommonEntity { return $entity; } //entities를 가져오는 조건 protected function getEntities_process(mixed $where = null, array $columns = ['*']): array { if ($where) { $this->model->where($where); } $entities = []; foreach ($this->model->select(implode(',', $columns))->findAll() as $entity) { $entities[$entity->getPK()] = $this->getEntity_process($entity); } return $entities; } //CURD 결과처리용 protected function handle_save_result(mixed $result, int|string $uid): int|string { log_message('debug', $this->model->getLastQuery()); if ($result === false) { $errors = $this->model->errors(); $errorMsg = is_array($errors) ? implode(", ", $errors) : "삽입 작업이 실패했습니다."; throw new RuntimeException(__METHOD__ . "에서 오류발생: " . $errorMsg); } // $pk는 auto-increment가 사용된 경우 새로 생성된 ID, 아니면 기존 $uid (업데이트의 경우) $pk = $this->model->useAutoIncrement() && is_numeric($result) && (int)$result > 0 ? (int)$result : $uid; if (empty($pk)) { $errors = $this->model->errors(); $errorMsg = is_array($errors) && !empty($errors) ? implode(", ", $errors) : "DB 작업 성공 후 PK를 확인할 수 없거나 모델 오류 발생:{$pk}"; throw new RuntimeException(__METHOD__ . "에서 오류발생: " . $errorMsg); } return $pk; } protected function save_process(CommonEntity $entity): CommonEntity { $result = $this->model->save($entity); // 최종적으로 DB에 반영된 PK를 반환받습니다. (UPDATE이면 기존 PK, INSERT이면 새 PK) $finalPK = $this->handle_save_result($result, $entity->getPK()); return $this->getEntity($finalPK); } //생성용 abstract protected function create_process(array $formDatas): CommonEntity; public function create(object $dto): CommonEntity { $formDatas = $dto->toArray(); if (!$this->getFormService()->validate($formDatas)) { throw new ValidationException(implode("\n", service('validation')->getErrors())); } $entity = $this->create_process($formDatas); return $this->save_process($entity); } //수정용 protected function modify_process(string|int $uid, array $formDatas): CommonEntity { $entity = $this->getEntity($uid); if (!$entity) { throw new \Exception(__METHOD__ . "에서 오류발생: {$uid}에 해당하는 정보을 찾을수 없습니다."); } $pkField = $this->model->getPKField(); // DTO에서 넘어온 데이터에 PK 필드가 포함되어 있으면 제거하여, // 기존 엔티티의 PK를 덮어쓰지 못하도록 방어 if (isset($formDatas[$pkField])) { unset($formDatas[$pkField]); } $entity->fill($formDatas); // <<< FIX: fill() 후 PK가 유실되었는지 확인하고 강제로 재설정 (방어적 코딩) >>> if (empty($entity->getPK())) { log_message('warning', "modify_process에서 fill() 후 PK가 유실되어 uid {$uid}를 강제로 재설정합니다."); // Entity의 PK 필드를 직접 설정하여 UPDATE가 실행되도록 보장 $entity->{$pkField} = $uid; } // save_process 진입 전 Entity의 PK 최종 확인 로그 log_message('debug', "save_process 진입 전 Entity PK: " . $entity->getPK() . " (기대값: {$uid})"); return $entity; } public function modify(string|int $uid, object $dto): CommonEntity { $formDatas = $dto->toArray(); if (!$this->getFormService()->validate($formDatas)) { throw new ValidationException(implode("\n", service('validation')->getErrors())); } $entity = $this->modify_process($uid, $formDatas); return $this->save_process($entity); } //배치 작업용 수정 protected function batchjob_process(string|int $uid, array $formDatas): CommonEntity { // modify_process를 호출하여 로직 재사용 (PK 로드 및 PK 제거/방어 로직 포함) $entity = $this->modify_process($uid, $formDatas); return $entity; } public function batchjob(string|int $uid, array $formDatas): CommonEntity { if (!$this->getFormService()->validate($formDatas)) { throw new ValidationException(implode("\n", service('validation')->getErrors())); } $entity = $this->batchjob_process($uid, $formDatas); return $this->save_process($entity); } //삭제용 (일반) protected function delete_process(string|int $uid): CommonEntity { if (!$uid) { throw new \Exception("삭제에 필요한 PrimaryKey 가 정의 되지 않았습니다."); } $entity = $this->getEntity($uid); if (!$entity) { throw new \Exception(__METHOD__ . "에서 오류발생: {$uid}에 해당하는 정보을 찾을수 없습니다."); } return $entity; } final public function delete(string|int $uid): CommonEntity { $entity = $this->delete_process($uid); $result = $this->model->delete($entity->getPK()); log_message('debug', $this->model->getLastQuery()); if ($result === false) { $errors = $this->model->errors(); $errorMsg = is_array($errors) ? implode(", ", $errors) : "삭제 작업이 실패했습니다."; throw new RuntimeException(__METHOD__ . "에서 오류발생: " . $errorMsg); } return $entity; } //삭제용 (배치 작업) protected function batchjob_delete_process(string|int $uid): CommonEntity { // delete_process를 호출하여 로직 재사용 (CommonEntity 로드 및 유효성 검사) $entity = $this->delete_process($uid); return $entity; } final public function batchjob_delete(string|int $uid): CommonEntity { $entity = $this->batchjob_delete_process($uid); $result = $this->model->delete($entity->getPK()); log_message('debug', $this->model->getLastQuery()); if ($result === false) { $errors = $this->model->errors(); $errorMsg = is_array($errors) ? implode(", ", $errors) : "삭제 작업이 실패했습니다."; throw new RuntimeException(__METHOD__ . "에서 오류발생: " . $errorMsg); } return $entity; } //Index용 final public function getTotalCount(): int { return $this->model->countAllResults(); } //Limit처리 final public function setLimit(int $perpage): void { $this->model->limit($perpage); } //Offset처리 final public function setOffset(int $offset): void { $this->model->offset($offset); } public function setFilter(string $field, mixed $filter_value): void { switch ($field) { default: $this->model->where("{$this->model->getTable()}.{$field}", $filter_value); break; } } //검색어조건절처리 public function setSearchWord(string $word): void { $this->model->orLike($this->model->getTable() . "." . $this->model->getTitleField(), $word, 'both'); } //날자검색 public function setDateFilter(string $start, string $end): void { $this->model->where(sprintf("%s.created_at >= '%s 00:00:00'", $this->model->getTable(), $start)); $this->model->where(sprintf("%s.created_at <= '%s 23:59:59'", $this->model->getTable(), $end)); } //OrderBy 처리 public function setOrderBy(mixed $field = null, mixed $value = null): void { if ($field !== null && $value !== null) { $this->model->orderBy(sprintf(" %s.%s %s", $this->model->getTable(), $field, $value)); } } }