trafficmonitor/app/Services/PipelineRunnerService.php
2025-11-05 18:58:37 +09:00

54 lines
1.7 KiB
PHP

<?php
namespace App\Services;
use App\Traits\LogTrait;
use Throwable;
use function PHPUnit\Framework\throwException;
class PipelineRunnerService
{
use LogTrait;
protected array $steps = [];
/**
* 파이프라인에 처리 단계를 추가합니다.
* @param object $stepStep 클래스의 인스턴스
*/
public function addStep(object $step): self
{
// 단계 클래스를 저장합니다.
$this->steps[] = $step;
return $this;
}
/**
* 파이프라인의 모든 단계를 순차적으로 실행하고 컨텍스트를 전달합니다.
*/
public function run(array $initialContext = []): array
{
$db = \Config\Database::connect();
$db->transBegin(); // 1. 트랜잭션 시작 (원자성 확보)
try {
// 1. 초기값 선언
$context = $initialContext;
// 2. 파이프라인 정의 및 Step에 서비스 인스턴스 주입
$this->log_info("--- ✅ Step 시작 ---\n");
foreach ($this->steps as $step) {
if (!method_exists($step, 'execute')) {
throw new \RuntimeException(sprintf("[%s]에서 'execute' 없습니다.", get_class($step)));
}
// 3. 파이프라인 실행
// 이전 단계에서 반환된 context를 현재 단계에 전달하고, 현재 단계의 반환값을 다음 context로 설정합니다.
$context = $step->execute($context);
}
$this->log_info("--- ✅ Step 완료 ---\n");
} catch (Throwable $e) {
$db->transRollback();
// 여기서 $e는 Step에서 발생한 원본 Throwable 객체입니다.
$this->log_error(static::class . "에서 오류발생:" . $e->getMessage());
}
return $context;
}
}