From 642d0473e09ccdc5402bd25be0e15d93fdd9dd0d Mon Sep 17 00:00:00 2001 From: "choi.jh" Date: Fri, 14 Nov 2025 17:28:28 +0900 Subject: [PATCH] trafficmonitor init...2 --- app/Services/CommonService.php | 49 +++++++++++++++++++++++++--------- 1 file changed, 36 insertions(+), 13 deletions(-) diff --git a/app/Services/CommonService.php b/app/Services/CommonService.php index 5951ea0..c98f8ae 100644 --- a/app/Services/CommonService.php +++ b/app/Services/CommonService.php @@ -21,7 +21,7 @@ abstract class CommonService { $this->_classPaths[] = $path; } - final public function getClassPaths($isArray = true, $delimeter = DIRECTORY_SEPARATOR): array|string + final public function getClassPaths($isArray = true, $delimeter = DIRECTory_SEPARATOR): array|string { return $isArray ? $this->_classPaths : implode($delimeter, $this->_classPaths); } @@ -116,12 +116,26 @@ abstract class CommonService log_message('debug', $this->model->getLastQuery()); if ($result === false) { $errors = $this->model->errors(); - $errorMsg = is_array($errors) ? implode(", ", $errors) : "삽입 작업이 실패했습니다."; + $errorMsg = is_array($errors) ? implode(", ", $errors) : "DB 저장 작업이 실패했습니다."; throw new RuntimeException(__METHOD__ . "에서 오류발생: " . $errorMsg); } - // $pk는 auto-increment가 사용된 경우 새로 생성된 ID, 아니면 기존 $uid (업데이트의 경우) - $pk = $this->model->useAutoIncrement() && is_numeric($result) && (int)$result > 0 ? (int)$result : $uid; + $pk = $uid; // 기본적으로 기존 $uid (업데이트의 경우) + + // AUTO_INCREMENT 필드를 사용하는 경우, INSERT 작업이라면 새로 생성된 ID를 가져옵니다. + // INSERT 작업은 보통 $uid가 0 또는 null/빈 문자열일 때 실행됩니다. + if ($this->model->useAutoIncrement() && (empty($uid) || $uid === 0)) { + // CodeIgniter 모델의 getInsertID()를 사용하여 새로 생성된 PK를 확실히 가져옵니다. + $insertID = $this->model->getInsertID(); + if ($insertID > 0) { + $pk = $insertID; + } + } elseif ($this->model->useAutoIncrement() && is_numeric($result) && (int)$result > 0) { + // save()가 성공적인 INSERT 후 PK를 반환하는 경우를 대비 (CI4의 동작) + $pk = (int)$result; + } + + // 최종적으로 PK가 유효한지 확인합니다. if (empty($pk)) { $errors = $this->model->errors(); $errorMsg = is_array($errors) && !empty($errors) ? implode(", ", $errors) : "DB 작업 성공 후 PK를 확인할 수 없거나 모델 오류 발생:{$pk}"; @@ -132,9 +146,14 @@ abstract class CommonService protected function save_process(CommonEntity $entity): CommonEntity { + // INSERT 시 Entity의 PK는 0 또는 NULL이어야 함 (DB가 ID를 생성하도록) + $initialPK = $entity->getPK(); $result = $this->model->save($entity); + // 최종적으로 DB에 반영된 PK를 반환받습니다. (UPDATE이면 기존 PK, INSERT이면 새 PK) - $finalPK = $this->handle_save_result($result, $entity->getPK()); + $finalPK = $this->handle_save_result($result, $initialPK); + + // handle_save_result에서 확인된 최종 PK를 사용하여 DB에서 최신 엔티티를 가져옴 return $this->getEntity($finalPK); } @@ -146,6 +165,8 @@ abstract class CommonService if (!$this->getFormService()->validate($formDatas)) { throw new ValidationException(implode("\n", service('validation')->getErrors())); } + // NOTE: create_process에서 엔티티를 생성할 때, 자동 증가(AUTO_INCREMENT) 필드는 + // DB가 처리하도록 NULL이나 빈 값(0)으로 두는 것이 일반적입니다. $entity = $this->create_process($formDatas); return $this->save_process($entity); } @@ -160,22 +181,23 @@ abstract class CommonService $pkField = $this->model->getPKField(); - // DTO에서 넘어온 데이터에 PK 필드가 포함되어 있으면 제거하여, - // 기존 엔티티의 PK를 덮어쓰지 못하도록 방어 + // DTO 데이터에서 PK 필드가 있다면 제거하여, fill()에서 기존 PK를 덮어쓰지 않도록 합니다. if (isset($formDatas[$pkField])) { unset($formDatas[$pkField]); } + // 1. 데이터를 Entity에 채웁니다. $entity->fill($formDatas); - // <<< FIX: fill() 후 PK가 유실되었는지 확인하고 강제로 재설정 (방어적 코딩) >>> - if (empty($entity->getPK())) { - log_message('warning', "modify_process에서 fill() 후 PK가 유실되어 uid {$uid}를 강제로 재설정합니다."); - // Entity의 PK 필드를 직접 설정하여 UPDATE가 실행되도록 보장 + // 2. (핵심 방어) fill() 작업이 Entity의 PK를 훼손했더라도, + // 기존 $uid 값을 사용하여 Entity의 PK를 강제로 복원합니다. + // 이것이 Model::save()가 UPDATE를 실행하도록 보장하는 최종 방어선입니다. + $currentPK = $entity->getPK(); + if ($currentPK != $uid) { + log_message('warning', "modify_process: Entity PK 훼손 감지. '{$currentPK}' 대신 원본 UID '{$uid}'로 강제 복원."); $entity->{$pkField} = $uid; } - // save_process 진입 전 Entity의 PK 최종 확인 로그 log_message('debug', "save_process 진입 전 Entity PK: " . $entity->getPK() . " (기대값: {$uid})"); return $entity; @@ -197,8 +219,9 @@ abstract class CommonService $entity = $this->modify_process($uid, $formDatas); return $entity; } - public function batchjob(string|int $uid, array $formDatas): CommonEntity + public function batchjob(string|int $uid, object $dto): CommonEntity { + $formDatas = $dto->toArray(); if (!$this->getFormService()->validate($formDatas)) { throw new ValidationException(implode("\n", service('validation')->getErrors())); }