v7.0.0-beta.2 release

This commit is contained in:
HeuJung committed 2026-04-20 20:37:49 +09:00
1 parent 6595fd0eb5
commit fa8eba7a0d
1165 files changed
+107118 -762127

No files matched your search

+280
View File
@@ -0,0 +1,280 @@
<?php
namespace App\Extension\Vendor;
use Illuminate\Support\Facades\Log;
/**
* 런타임 환경에서 composer 실행 가능 여부 및 ZipArchive 사용 가능 여부를 감지합니다.
*
* 공유 호스팅 환경(proc_open 차단, composer 미설치)에서 vendor 번들 모드로
* 자동 폴백하기 위한 판단 근거를 제공합니다.
*/
class EnvironmentDetector
{
/**
* 캐시된 composer 실행 가능 여부.
*/
private ?bool $cachedComposerExecutable = null;
/**
* 캐시된 composer 바이너리 경로.
*/
private ?string $cachedComposerBinary = null;
/**
* proc_open() 함수 사용 가능 여부.
*/
public function hasProcOpen(): bool
{
if (! function_exists('proc_open')) {
return false;
}
$disabled = array_map('trim', explode(',', (string) ini_get('disable_functions')));
return ! in_array('proc_open', $disabled, true);
}
/**
* shell_exec() 함수 사용 가능 여부.
*/
public function hasShellExec(): bool
{
if (! function_exists('shell_exec')) {
return false;
}
$disabled = array_map('trim', explode(',', (string) ini_get('disable_functions')));
return ! in_array('shell_exec', $disabled, true);
}
/**
* ZipArchive 클래스 사용 가능 여부.
*/
public function hasZipArchive(): bool
{
return class_exists(\ZipArchive::class);
}
/**
* composer 바이너리 경로 찾기.
*
* 우선순위: hint → config(process.composer_binary) → $_ENV['COMPOSER_BINARY']
* → PATH 검색 → composer.phar
*/
public function findComposerBinary(?string $hint = null): ?string
{
if ($this->cachedComposerBinary !== null) {
return $this->cachedComposerBinary ?: null;
}
$candidates = array_filter([
$hint,
config('process.composer_binary'),
$_ENV['COMPOSER_BINARY'] ?? null,
getenv('COMPOSER_BINARY') ?: null,
]);
foreach ($candidates as $candidate) {
if ($this->isExecutableCandidate($candidate)) {
return $this->cachedComposerBinary = $candidate;
}
}
$found = $this->searchComposerInPath();
if ($found !== null) {
return $this->cachedComposerBinary = $found;
}
// composer.phar 폴백
$pharCandidates = [
base_path('composer.phar'),
getcwd().DIRECTORY_SEPARATOR.'composer.phar',
];
foreach ($pharCandidates as $phar) {
if (is_file($phar)) {
return $this->cachedComposerBinary = $phar;
}
}
$this->cachedComposerBinary = '';
return null;
}
/**
* composer 실행 가능 여부 종합 판단.
*
* proc_open 사용 가능 + composer 바이너리 발견 + `composer --version` 종료 코드 0.
*/
public function canExecuteComposer(?string $hint = null): bool
{
if ($this->cachedComposerExecutable !== null && $hint === null) {
return $this->cachedComposerExecutable;
}
if (! $this->hasProcOpen()) {
return $this->cachedComposerExecutable = false;
}
$binary = $this->findComposerBinary($hint);
if ($binary === null) {
return $this->cachedComposerExecutable = false;
}
try {
$command = $this->buildComposerCommand($binary, ['--version', '--no-interaction']);
$process = @proc_open(
$command,
[
0 => ['pipe', 'r'],
1 => ['pipe', 'w'],
2 => ['pipe', 'w'],
],
$pipes,
null,
null,
['bypass_shell' => true]
);
if (! is_resource($process)) {
return $this->cachedComposerExecutable = false;
}
foreach ($pipes as $pipe) {
if (is_resource($pipe)) {
@fclose($pipe);
}
}
$exit = proc_close($process);
return $this->cachedComposerExecutable = ($exit === 0);
} catch (\Throwable $e) {
Log::warning('Composer 실행 가능 여부 확인 실패', [
'error' => $e->getMessage(),
'binary' => $binary,
]);
return $this->cachedComposerExecutable = false;
}
}
/**
* 지정 경로에 쓰기 가능한지 확인.
*/
public function canWriteVendor(string $targetPath): bool
{
$parent = dirname($targetPath);
return is_dir($parent) && is_writable($parent);
}
/**
* 인스톨러 Step 2 요구사항 체크용 종합 리포트.
*
* @return array{
* proc_open: bool,
* shell_exec: bool,
* zip_archive: bool,
* composer_binary: string|null,
* composer_executable: bool,
* can_use_composer: bool,
* can_use_bundle: bool,
* }
*/
public function summarize(?string $hint = null): array
{
$composerBinary = $this->findComposerBinary($hint);
$composerExecutable = $this->canExecuteComposer($hint);
$zipAvailable = $this->hasZipArchive();
return [
'proc_open' => $this->hasProcOpen(),
'shell_exec' => $this->hasShellExec(),
'zip_archive' => $zipAvailable,
'composer_binary' => $composerBinary,
'composer_executable' => $composerExecutable,
'can_use_composer' => $composerExecutable,
'can_use_bundle' => $zipAvailable,
];
}
/**
* 캐시 초기화 (테스트용).
*/
public function resetCache(): void
{
$this->cachedComposerExecutable = null;
$this->cachedComposerBinary = null;
}
/**
* composer 실행 명령 문자열 구성.
*
* @param array<int, string> $args
*/
private function buildComposerCommand(string $binary, array $args): string
{
$escaped = array_map('escapeshellarg', $args);
if (str_contains($binary, ' ')) {
// 전체 명령어로 취급
return $binary.' '.implode(' ', $escaped);
}
if (str_ends_with(strtolower($binary), '.phar')) {
$phpBinary = config('process.php_binary', 'php');
return escapeshellarg($phpBinary).' '.escapeshellarg($binary).' '.implode(' ', $escaped);
}
return escapeshellarg($binary).' '.implode(' ', $escaped);
}
/**
* PATH 환경변수에서 composer 검색.
*/
private function searchComposerInPath(): ?string
{
$pathEnv = getenv('PATH') ?: ($_SERVER['PATH'] ?? '');
if (empty($pathEnv)) {
return null;
}
$separator = DIRECTORY_SEPARATOR === '\\' ? ';' : ':';
$paths = explode($separator, $pathEnv);
$names = DIRECTORY_SEPARATOR === '\\'
? ['composer.bat', 'composer.exe', 'composer.phar', 'composer']
: ['composer', 'composer.phar'];
foreach ($paths as $dir) {
foreach ($names as $name) {
$candidate = rtrim($dir, '/\\').DIRECTORY_SEPARATOR.$name;
if (is_file($candidate)) {
return $candidate;
}
}
}
return null;
}
/**
* 후보 경로가 실행 가능한 파일인지 확인.
*/
private function isExecutableCandidate(?string $candidate): bool
{
if ($candidate === null || $candidate === '') {
return false;
}
// 공백 포함 시 전체 커맨드로 간주 — 파일 존재 검사 스킵
if (str_contains($candidate, ' ')) {
return true;
}
return is_file($candidate);
}
}
@@ -0,0 +1,45 @@
<?php
namespace App\Extension\Vendor\Exceptions;
/**
* Vendor 설치 실패 예외.
*
* 에러 키는 lang/{locale}/exceptions.php 의 vendor.* 하위에 정의되어 있음.
* 예: exceptions.vendor.composer_not_available
*/
class VendorInstallException extends \RuntimeException
{
/**
* @param string $errorKey 'exceptions.vendor.*' 하위 키 (예: 'composer_not_available')
* @param array<string, mixed> $context 다국어 파라미터 치환 컨텍스트
* @param \Throwable|null $previous 이전 예외
*/
public function __construct(
public readonly string $errorKey,
public readonly array $context = [],
?\Throwable $previous = null,
) {
$message = __('exceptions.vendor.'.$errorKey, $context);
if (is_array($message)) {
$message = 'exceptions.vendor.'.$errorKey;
}
// 권한 거부 등 진단 힌트가 있으면 메시지에 덧붙여 사용자에게 즉시 노출
if (isset($context['hint'])) {
$message = (string) $message.' — '.$context['hint'];
}
parent::__construct((string) $message, 0, $previous);
}
public function getErrorKey(): string
{
return $this->errorKey;
}
public function getContext(): array
{
return $this->context;
}
}
+40
View File
@@ -0,0 +1,40 @@
<?php
namespace App\Extension\Vendor;
/**
* Vendor 번들 무결성 검증 결과.
*/
class IntegrityResult
{
/**
* @param bool $valid 모든 검증 통과 여부
* @param array<string> $errors 검증 실패 키 목록 (다국어 키)
* @param array<string> $warnings 경고 목록 (valid=true여도 존재 가능)
* @param array<string, mixed> $meta manifest에서 읽은 메타정보
*/
public function __construct(
public readonly bool $valid,
public readonly array $errors = [],
public readonly array $warnings = [],
public readonly array $meta = [],
) {}
public static function valid(array $meta = [], array $warnings = []): self
{
return new self(valid: true, errors: [], warnings: $warnings, meta: $meta);
}
public static function invalid(array $errors, array $meta = []): self
{
return new self(valid: false, errors: $errors, warnings: [], meta: $meta);
}
public function errorMessages(): array
{
return array_map(
fn (string $key) => __('exceptions.vendor.'.$key),
$this->errors
);
}
}
+320
View File
@@ -0,0 +1,320 @@
<?php
namespace App\Extension\Vendor;
use App\Extension\Vendor\Exceptions\VendorInstallException;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;
/**
* vendor-bundle.zip 을 대상 디렉토리로 추출하여 vendor/를 구성합니다.
*
* 공유 호스팅 친화적 설계:
* - targetDir 자체(프로젝트 루트)의 쓰기 권한은 요구하지 않음
* - vendor/ 디렉토리 자체는 유지하고 **내부 항목만 조작**
* - 기존 내용은 vendor/.bundle_backup_{ts}/ 로 이동 (vendor/ 쓰기 권한만으로 가능)
* - 추출 실패 시 백업에서 복원, 성공 시 백업 삭제
*
* 이 접근은 웹 서버 사용자가 프로젝트 루트에는 쓰기 권한이 없지만
* vendor/ 디렉토리에만 권한이 부여된 전형적 공유 호스팅 환경을 지원합니다.
*/
class VendorBundleInstaller
{
public function __construct(
private readonly VendorIntegrityChecker $integrityChecker,
) {}
/**
* 번들 zip을 대상 디렉토리에 추출합니다.
*
* @param string $sourceDir vendor-bundle.zip 이 위치한 디렉토리
* @param string $targetDir vendor/가 배치될 디렉토리 (일반적으로 sourceDir과 동일)
*
* @throws VendorInstallException
*/
public function install(string $sourceDir, string $targetDir): VendorInstallResult
{
$startTime = microtime(true);
// 1. ZipArchive 확장 확인
if (! class_exists(\ZipArchive::class)) {
throw new VendorInstallException('zip_archive_not_available');
}
// 2. 무결성 검증
$integrity = $this->integrityChecker->verify($sourceDir);
if (! $integrity->valid) {
throw new VendorInstallException(
errorKey: 'bundle_integrity_failed',
context: ['details' => implode(', ', $integrity->errorMessages())],
);
}
$zipPath = $sourceDir.DIRECTORY_SEPARATOR.VendorIntegrityChecker::ZIP_FILENAME;
$vendorDir = $targetDir.DIRECTORY_SEPARATOR.'vendor';
$backupDirName = '.bundle_backup_'.date('Ymd_His');
$backupDir = $vendorDir.DIRECTORY_SEPARATOR.$backupDirName;
// 3. 쓰기 권한 유연 검사 — vendor/ 가 있으면 vendor/ 권한만, 없으면 targetDir 권한 필요
$this->validateTargetWritable($targetDir, $vendorDir);
// 4. zip slip 방지 사전 검증
$this->validateZipContents($zipPath);
// 5. 기존 vendor/ 내부 항목을 vendor/.bundle_backup_{ts}/ 로 이동
// (vendor/ 디렉토리 자체는 유지 — targetDir 쓰기 권한 불필요)
$hasBackup = false;
if (is_dir($vendorDir)) {
$hasBackup = $this->moveVendorContentsToBackup($vendorDir, $backupDir, $backupDirName);
} else {
// vendor/ 없음 — 신규 생성 (targetDir 쓰기 권한 필요, 위에서 이미 검증)
if (! @mkdir($vendorDir, 0755, true) && ! is_dir($vendorDir)) {
throw new VendorInstallException(
errorKey: 'target_not_writable',
context: ['path' => $vendorDir],
);
}
}
// 6. 추출
try {
$zip = new \ZipArchive;
$openResult = $zip->open($zipPath);
if ($openResult !== true) {
throw new VendorInstallException(
errorKey: 'extraction_failed',
context: ['message' => 'ZipArchive::open failed (code: '.$openResult.')'],
);
}
$extracted = $zip->extractTo($targetDir);
$zip->close();
if (! $extracted) {
throw new VendorInstallException(
errorKey: 'extraction_failed',
context: ['message' => 'ZipArchive::extractTo returned false'],
);
}
// 7. 성공: 백업 디렉토리 삭제 (vendor/.bundle_backup_{ts}/)
if ($hasBackup && is_dir($backupDir)) {
File::deleteDirectory($backupDir);
}
$duration = microtime(true) - $startTime;
$packageCount = (int) ($integrity->meta['package_count'] ?? 0);
$zipSize = @filesize($zipPath) ?: 0;
Log::info('Vendor 번들 추출 성공', [
'source_dir' => $sourceDir,
'target_dir' => $targetDir,
'package_count' => $packageCount,
'zip_size' => $zipSize,
'duration_seconds' => round($duration, 2),
]);
return new VendorInstallResult(
mode: VendorMode::Bundled,
strategy: 'bundled',
packageCount: $packageCount,
durationSeconds: $duration,
details: [
'zip_size' => $zipSize,
'source_dir' => $sourceDir,
],
);
} catch (\Throwable $e) {
// 실패: 백업에서 복원
if ($hasBackup && is_dir($backupDir)) {
$this->restoreVendorFromBackup($vendorDir, $backupDir, $backupDirName);
}
if ($e instanceof VendorInstallException) {
throw $e;
}
throw new VendorInstallException(
errorKey: 'extraction_failed',
context: ['message' => $e->getMessage()],
previous: $e,
);
}
}
/**
* 쓰기 권한 검사 — vendor/ 가 존재하면 vendor/ 권한만, 없으면 targetDir 권한 필요.
*
* 공유 호스팅 환경에서 targetDir (프로젝트 루트) 에는 쓰기 권한이 없고
* vendor/ 에만 권한이 부여된 케이스를 지원한다.
*
* @throws VendorInstallException
*/
private function validateTargetWritable(string $targetDir, string $vendorDir): void
{
if (is_dir($vendorDir)) {
if (! is_writable($vendorDir)) {
throw new VendorInstallException(
errorKey: 'target_not_writable',
context: $this->buildPermissionContext($vendorDir),
);
}
return;
}
// vendor/ 없음 — 생성을 위해 targetDir 에 쓰기 권한 필요
if (! is_dir($targetDir) || ! is_writable($targetDir)) {
throw new VendorInstallException(
errorKey: 'target_not_writable',
context: $this->buildPermissionContext($targetDir),
);
}
}
/**
* 권한 거부 컨텍스트에 소유권 정보를 포함합니다.
*
* 공유 호스팅에서 FTP 사용자와 PHP 실행 사용자가 다른 경우 진단을 돕기 위해
* 현재 실행 사용자, 디렉토리 소유자, 권장 조치를 함께 반환합니다.
*/
private function buildPermissionContext(string $path): array
{
$context = ['path' => $path];
if (! function_exists('posix_geteuid') || ! function_exists('posix_getpwuid')) {
return $context;
}
$currentUid = posix_geteuid();
$currentUser = posix_getpwuid($currentUid)['name'] ?? (string) $currentUid;
$context['current_user'] = "{$currentUser}({$currentUid})";
if (file_exists($path)) {
$ownerUid = fileowner($path);
$ownerUser = posix_getpwuid($ownerUid)['name'] ?? (string) $ownerUid;
$context['owner'] = "{$ownerUser}({$ownerUid})";
if ($currentUid !== $ownerUid) {
$context['hint'] = __('exceptions.vendor.target_not_writable_owner_hint', [
'path' => $path,
'current_user' => $context['current_user'],
'current_user_name' => $currentUser,
'owner' => $context['owner'],
'owner_name' => $ownerUser,
]);
}
}
return $context;
}
/**
* 기존 vendor/ 내부 항목을 vendor/.bundle_backup_{ts}/ 로 이동합니다.
*
* vendor/ 디렉토리 자체는 유지하므로 targetDir 쓰기 권한이 필요하지 않습니다.
*
* @return bool 백업 성공 여부 (false 시 in-place overwrite 로 추출 진행)
*/
private function moveVendorContentsToBackup(string $vendorDir, string $backupDir, string $backupDirName): bool
{
if (! @mkdir($backupDir) && ! is_dir($backupDir)) {
Log::warning('Vendor 번들 백업 디렉토리 생성 실패 — in-place overwrite 로 진행', [
'vendor_dir' => $vendorDir,
'backup_dir' => $backupDir,
]);
return false;
}
$items = @scandir($vendorDir) ?: [];
foreach ($items as $item) {
if ($item === '.' || $item === '..' || $item === $backupDirName) {
continue;
}
$src = $vendorDir.DIRECTORY_SEPARATOR.$item;
$dst = $backupDir.DIRECTORY_SEPARATOR.$item;
@rename($src, $dst);
}
return true;
}
/**
* 백업 디렉토리에서 vendor/ 로 내용을 복원합니다.
*
* 추출 중 실패한 경우 기존 상태로 되돌리기 위해 호출됩니다.
*/
private function restoreVendorFromBackup(string $vendorDir, string $backupDir, string $backupDirName): void
{
// 1. 추출로 이미 생성된 파일/디렉토리 정리 (백업 폴더 제외)
$items = @scandir($vendorDir) ?: [];
foreach ($items as $item) {
if ($item === '.' || $item === '..' || $item === $backupDirName) {
continue;
}
$path = $vendorDir.DIRECTORY_SEPARATOR.$item;
if (is_dir($path) && ! is_link($path)) {
File::deleteDirectory($path);
} elseif (file_exists($path)) {
@unlink($path);
}
}
// 2. 백업 항목을 원위치로 이동
$backupItems = @scandir($backupDir) ?: [];
foreach ($backupItems as $item) {
if ($item === '.' || $item === '..') {
continue;
}
$src = $backupDir.DIRECTORY_SEPARATOR.$item;
$dst = $vendorDir.DIRECTORY_SEPARATOR.$item;
@rename($src, $dst);
}
// 3. 빈 백업 디렉토리 제거
@rmdir($backupDir);
}
/**
* zip 내부 파일 경로의 안전성을 검증합니다 (zip slip 방지).
*
* @throws VendorInstallException
*/
private function validateZipContents(string $zipPath): void
{
$zip = new \ZipArchive;
if ($zip->open($zipPath) !== true) {
throw new VendorInstallException(
errorKey: 'extraction_failed',
context: ['message' => 'cannot open zip for validation'],
);
}
for ($i = 0; $i < $zip->numFiles; $i++) {
$name = $zip->getNameIndex($i);
if ($name === false) {
continue;
}
// 경로 탈출 방지
$normalized = str_replace('\\', '/', $name);
if (
str_contains($normalized, '../')
|| str_starts_with($normalized, '/')
|| preg_match('#^[A-Za-z]:/#', $normalized)
) {
$zip->close();
throw new VendorInstallException(
errorKey: 'bundle_contains_unsafe_path',
context: ['path' => $name],
);
}
}
$zip->close();
}
}
+41
View File
@@ -0,0 +1,41 @@
<?php
namespace App\Extension\Vendor;
/**
* Vendor 번들 빌드 결과 DTO.
*/
class VendorBundleResult
{
/**
* @param string $target 'core' | 'module:identifier' | 'plugin:identifier'
* @param string $zipPath 생성된 zip 파일 절대 경로
* @param string $manifestPath 생성된 vendor-bundle.json 절대 경로
* @param int $zipSize zip 파일 크기 (bytes)
* @param int $packageCount 번들에 포함된 composer 패키지 수
* @param bool $skipped 이미 최신 상태여서 빌드 스킵 여부
* @param string $reason 스킵 사유 또는 빌드 메시지
*/
public function __construct(
public readonly string $target,
public readonly string $zipPath,
public readonly string $manifestPath,
public readonly int $zipSize,
public readonly int $packageCount,
public readonly bool $skipped = false,
public readonly string $reason = '',
) {}
public function zipSizeHuman(): string
{
$units = ['B', 'KB', 'MB', 'GB'];
$size = $this->zipSize;
$unit = 0;
while ($size >= 1024 && $unit < count($units) - 1) {
$size /= 1024;
$unit++;
}
return sprintf('%.1f %s', $size, $units[$unit]);
}
}
+592
View File
@@ -0,0 +1,592 @@
<?php
namespace App\Extension\Vendor;
use App\Extension\Vendor\Exceptions\VendorInstallException;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;
/**
* 개발 환경에서 vendor/ 디렉토리를 zip으로 압축하여 번들 파일을 생성합니다.
*
* 빌드 타임에만 실행되며, 생성된 번들은 런타임에 VendorBundleInstaller가 소비합니다.
*
* 빌드 절차 (staging 기반):
* 1. storage/app/vendor-bundle-staging/{uniqid}/ 임시 디렉토리 생성
* 2. 소스의 composer.json + composer.lock 을 임시 디렉토리로 복사
* 3. 임시 디렉토리에서 `composer install --no-dev --no-scripts --prefer-dist` 실행
* 4. 생성된 vendor/ 를 (EXCLUDE_PATTERNS 적용 후) zip 으로 기록
* 5. manifest.json 기록
* 6. 임시 디렉토리 정리
*
* 이 방식은 개발 vendor/ 가 dev 의존성을 포함하고 있어도 번들에 dev 의존성이
* 섞여 들어가지 않도록 보장하며, composer 가 생성한 autoload 파일과 vendor/
* 내용이 완벽히 일치함을 보장합니다 (autoload_files.php 가 존재하지 않는
* dev 패키지를 require 하는 버그 방지).
*/
class VendorBundler
{
public const SCHEMA_VERSION = '1.0';
/**
* 압축 제외 경로 패턴 (패키지 디렉토리 내부 파일).
*
* @var array<int, string>
*/
private const EXCLUDE_PATTERNS = [
'.git',
'.github',
'tests',
'Tests',
'docs',
'.gitignore',
'.gitattributes',
'.gitkeep',
'phpunit.xml',
'phpunit.xml.dist',
'psalm.xml',
'psalm.xml.dist',
'.phpcs.xml',
'.phpcs.xml.dist',
];
/**
* 테스트에서 composer 실행을 대체하기 위한 주입 가능한 러너.
*
* null 이면 실제 composer 바이너리를 proc_open 으로 실행합니다.
* 테스트에서는 setComposerInstallRunner() 로 주입하여 가짜 vendor/ 구조를 생성합니다.
*/
private ?\Closure $composerInstallRunner = null;
public function __construct(
private readonly VendorIntegrityChecker $integrityChecker,
private readonly ?EnvironmentDetector $environmentDetector = null,
) {}
/**
* 테스트용 — composer 실행을 대체할 러너를 주입합니다.
*
* 러너는 `fn (string $stagingDir): void` 형식이며, 주어진 스테이징 디렉토리에
* vendor/ 구조를 직접 생성해야 합니다.
*/
public function setComposerInstallRunner(?\Closure $runner): void
{
$this->composerInstallRunner = $runner;
}
/**
* 코어(루트) vendor/를 번들링합니다.
*
* 코어는 소스 = 출력 경로가 base_path() 로 동일합니다.
*/
public function buildForCore(bool $force = false): VendorBundleResult
{
return $this->build(
sourcePath: base_path(),
outputPath: base_path(),
target: 'core',
force: $force,
);
}
/**
* 모듈/플러그인의 vendor/를 번들링합니다.
*
* 소스는 **활성 디렉토리** (예: modules/sirsoft-ecommerce/vendor/) 에서 읽고,
* 출력은 **_bundled 디렉토리** (예: modules/_bundled/sirsoft-ecommerce/vendor-bundle.zip) 에 저장합니다.
*
* 이유: _bundled 는 Git 추적 소스 디렉토리로 vendor/ 를 두지 않는 것이 원칙.
* 활성 디렉토리는 설치 시 composer install 이 실행되어 실제 패키지가 설치된 상태.
*
* @param string $type 'module' | 'plugin'
*/
public function buildForExtension(string $type, string $identifier, bool $force = false): VendorBundleResult
{
$activePath = match ($type) {
'module' => base_path('modules/'.$identifier),
'plugin' => base_path('plugins/'.$identifier),
default => throw new \InvalidArgumentException("Unsupported extension type: $type"),
};
$outputPath = match ($type) {
'module' => base_path('modules/_bundled/'.$identifier),
'plugin' => base_path('plugins/_bundled/'.$identifier),
};
if (! is_dir($outputPath)) {
throw new VendorInstallException(
errorKey: 'source_dir_not_found',
context: ['path' => $outputPath],
);
}
// 활성 디렉토리가 없으면 미설치 확장 — skip 처리 (예외 대신)
//
// 미설치 확장의 경우 composer.json 은 _bundled 에만 존재하므로
// 외부 의존성 여부를 _bundled 의 composer.json 에서 확인한다.
if (! is_dir($activePath)) {
$bundledComposerJson = $outputPath.DIRECTORY_SEPARATOR.'composer.json';
$reason = file_exists($bundledComposerJson) && $this->hasExternalDependencies($bundledComposerJson)
? 'extension-not-installed'
: 'no-external-dependencies';
return new VendorBundleResult(
target: $type.':'.$identifier,
zipPath: $outputPath.DIRECTORY_SEPARATOR.VendorIntegrityChecker::ZIP_FILENAME,
manifestPath: $outputPath.DIRECTORY_SEPARATOR.VendorIntegrityChecker::MANIFEST_FILENAME,
zipSize: 0,
packageCount: 0,
skipped: true,
reason: $reason,
);
}
return $this->build(
sourcePath: $activePath,
outputPath: $outputPath,
target: $type.':'.$identifier,
force: $force,
);
}
/**
* stale 여부 확인 — composer.json/lock 해시가 기존 manifest와 일치하는지 검사.
*
* 외부 패키지 의존성이 없는 확장은 번들링 대상이 아니므로 항상 false 를 반환합니다.
*
* @param string $sourcePath composer.json/lock 을 읽을 경로 (활성 디렉토리)
* @param string|null $outputPath 번들 출력 경로 (null 이면 sourcePath 와 동일 — 코어 케이스)
*/
public function isStale(string $sourcePath, ?string $outputPath = null): bool
{
$outputPath ??= $sourcePath;
$composerJsonPath = $sourcePath.DIRECTORY_SEPARATOR.'composer.json';
if (file_exists($composerJsonPath) && ! $this->hasExternalDependencies($composerJsonPath)) {
return false;
}
$manifestPath = $outputPath.DIRECTORY_SEPARATOR.VendorIntegrityChecker::MANIFEST_FILENAME;
$zipPath = $outputPath.DIRECTORY_SEPARATOR.VendorIntegrityChecker::ZIP_FILENAME;
if (! file_exists($manifestPath) || ! file_exists($zipPath)) {
return true;
}
$manifest = $this->integrityChecker->readManifest($outputPath);
if ($manifest === null) {
return true;
}
if (file_exists($composerJsonPath)) {
$currentHash = $this->integrityChecker->computeFileHash($composerJsonPath);
if (($manifest['composer_json_sha256'] ?? null) !== $currentHash) {
return true;
}
}
$composerLockPath = $sourcePath.DIRECTORY_SEPARATOR.'composer.lock';
if (file_exists($composerLockPath)) {
$currentHash = $this->integrityChecker->computeFileHash($composerLockPath);
if (($manifest['composer_lock_sha256'] ?? null) !== $currentHash) {
return true;
}
}
return false;
}
/**
* 빌드 실행.
*
* @param string $sourcePath composer.json, composer.lock, vendor/ 를 읽을 경로 (활성 디렉토리)
* @param string $outputPath vendor-bundle.zip 과 vendor-bundle.json 을 쓸 경로 (_bundled 또는 코어는 sourcePath 와 동일)
* @param string $target 라벨용 대상 식별자 (예: 'core', 'module:sirsoft-ecommerce')
* @param bool $force 해시 체크 무시 강제 재빌드
*/
private function build(string $sourcePath, string $outputPath, string $target, bool $force): VendorBundleResult
{
// 전제 조건 검증
$composerJsonPath = $sourcePath.DIRECTORY_SEPARATOR.'composer.json';
if (! file_exists($composerJsonPath)) {
throw new VendorInstallException(
errorKey: 'composer_json_not_found',
context: ['path' => $composerJsonPath],
);
}
$zipPath = $outputPath.DIRECTORY_SEPARATOR.VendorIntegrityChecker::ZIP_FILENAME;
$manifestPath = $outputPath.DIRECTORY_SEPARATOR.VendorIntegrityChecker::MANIFEST_FILENAME;
// 실제 외부 패키지 의존성이 없는 확장은 번들링 대상이 아님 — skip 처리
// (composer.json 에 `php: ^8.2` 런타임 제약만 있고 패키지 require 가 없는 경우)
if (! $this->hasExternalDependencies($composerJsonPath)) {
return new VendorBundleResult(
target: $target,
zipPath: $zipPath,
manifestPath: $manifestPath,
zipSize: 0,
packageCount: 0,
skipped: true,
reason: 'no-external-dependencies',
);
}
// stale 체크
if (! $force && ! $this->isStale($sourcePath, $outputPath)) {
$existingSize = file_exists($zipPath) ? (int) filesize($zipPath) : 0;
$existingManifest = $this->integrityChecker->readManifest($outputPath) ?? [];
$existingCount = (int) ($existingManifest['package_count'] ?? 0);
return new VendorBundleResult(
target: $target,
zipPath: $zipPath,
manifestPath: $manifestPath,
zipSize: $existingSize,
packageCount: $existingCount,
skipped: true,
reason: 'up-to-date',
);
}
// 기존 파일 제거
if (file_exists($zipPath)) {
@unlink($zipPath);
}
if (file_exists($manifestPath)) {
@unlink($manifestPath);
}
// === 스테이징 빌드 ===
// 개발 머신의 vendor/ 를 직접 사용하지 않고, composer install --no-dev 를
// 스테이징 디렉토리에서 새로 실행하여 dev 의존성과 완전히 분리된 번들을 생성한다.
$stagingDir = storage_path('app/vendor-bundle-staging/'.uniqid('build-', true));
File::ensureDirectoryExists($stagingDir, 0755);
try {
// 1. composer.json + composer.lock 을 스테이징으로 복사
File::copy($composerJsonPath, $stagingDir.DIRECTORY_SEPARATOR.'composer.json');
$sourceLockPath = $sourcePath.DIRECTORY_SEPARATOR.'composer.lock';
if (file_exists($sourceLockPath)) {
File::copy($sourceLockPath, $stagingDir.DIRECTORY_SEPARATOR.'composer.lock');
}
// 2. 스테이징에서 composer install --no-dev 실행
$this->runComposerInstall($stagingDir, $target);
// 3. 생성된 vendor/ 검증
$stagedVendor = $stagingDir.DIRECTORY_SEPARATOR.'vendor';
if (! is_dir($stagedVendor)) {
throw new VendorInstallException(
errorKey: 'vendor_dir_not_found',
context: ['path' => $stagedVendor.' (composer install 후에도 vendor/ 가 생성되지 않음)'],
);
}
// 4. zip 생성 (EXCLUDE_PATTERNS 만 적용 — 화이트리스트 불필요)
[$zipSize, $fileCount] = $this->writeZip($stagedVendor, $zipPath);
// 5. manifest 작성 — 스테이징의 composer.lock 을 기준으로 패키지 목록 추출
$stagedLockPath = $stagingDir.DIRECTORY_SEPARATOR.'composer.lock';
$packages = file_exists($stagedLockPath)
? $this->collectPackages($stagedLockPath)
: [];
$manifest = [
'schema_version' => self::SCHEMA_VERSION,
'generated_at' => date('c'),
'generator' => 'g7 vendor-bundle:build',
'target' => $target,
// manifest 의 해시는 **소스** 의 composer.json/lock 기준 — 런타임에서
// 소스 디렉토리(또는 번들과 함께 배포된) composer.json 과 비교하여
// stale 여부를 감지한다.
'composer_json_sha256' => $this->integrityChecker->computeFileHash($composerJsonPath),
'composer_lock_sha256' => file_exists($sourceLockPath)
? $this->integrityChecker->computeFileHash($sourceLockPath)
: null,
'zip_sha256' => $this->integrityChecker->computeFileHash($zipPath),
'zip_size' => $zipSize,
'package_count' => count($packages),
'php_requirement' => $this->extractPhpRequirement($composerJsonPath),
'g7_version' => config('app.version'),
'packages' => $packages,
];
File::put($manifestPath, json_encode($manifest, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
Log::info('Vendor 번들 빌드 완료', [
'target' => $target,
'zip_size' => $zipSize,
'package_count' => count($packages),
'file_count' => $fileCount,
]);
return new VendorBundleResult(
target: $target,
zipPath: $zipPath,
manifestPath: $manifestPath,
zipSize: $zipSize,
packageCount: count($packages),
skipped: false,
reason: 'built',
);
} finally {
// 스테이징 정리 (실패/성공 무관)
if (File::isDirectory($stagingDir)) {
File::deleteDirectory($stagingDir);
}
}
}
/**
* 스테이징 디렉토리에서 `composer install --no-dev` 를 실행합니다.
*
* 테스트에서는 setComposerInstallRunner() 로 주입된 closure 를 대신 호출합니다.
*
* @throws VendorInstallException composer 미설치, 실행 실패 시
*/
private function runComposerInstall(string $stagingDir, string $target): void
{
// 테스트용 러너 우선
if ($this->composerInstallRunner !== null) {
($this->composerInstallRunner)($stagingDir);
return;
}
$detector = $this->environmentDetector ?? app(EnvironmentDetector::class);
if (! $detector->canExecuteComposer()) {
throw new VendorInstallException(
errorKey: 'composer_not_available_for_build',
);
}
$binary = $detector->findComposerBinary();
if ($binary === null) {
throw new VendorInstallException(
errorKey: 'composer_not_available_for_build',
);
}
$phpBinary = config('process.php_binary', 'php');
if (str_contains($binary, ' ')) {
$composerCmd = $binary;
} elseif (str_ends_with(strtolower($binary), '.phar')) {
$composerCmd = escapeshellarg($phpBinary).' '.escapeshellarg($binary);
} else {
$composerCmd = escapeshellarg($binary);
}
$command = $composerCmd.' install --no-dev --no-scripts --prefer-dist --no-interaction --no-progress 2>&1';
Log::info('vendor-bundle 빌드: composer install 시작', [
'target' => $target,
'staging' => $stagingDir,
]);
$descriptors = [
0 => ['pipe', 'r'],
1 => ['pipe', 'w'],
2 => ['pipe', 'w'],
];
$process = @proc_open($command, $descriptors, $pipes, $stagingDir);
if (! is_resource($process)) {
throw new VendorInstallException(
errorKey: 'bundle_build_composer_failed',
context: ['exit' => -1, 'message' => "proc_open 실패: {$stagingDir}"],
);
}
fclose($pipes[0]);
$output = stream_get_contents($pipes[1]);
fclose($pipes[1]);
fclose($pipes[2]);
$exitCode = proc_close($process);
if ($exitCode !== 0) {
throw new VendorInstallException(
errorKey: 'bundle_build_composer_failed',
context: ['exit' => $exitCode, 'message' => (string) $output],
);
}
Log::info('vendor-bundle 빌드: composer install 완료', [
'target' => $target,
'staging' => $stagingDir,
]);
}
/**
* vendor/ 디렉토리를 재귀적으로 zip에 쓰기.
*
* 스테이징에서 composer install --no-dev 로 새로 생성된 vendor/ 를 대상으로 하므로
* 화이트리스트 필터링은 불필요하며, EXCLUDE_PATTERNS (tests/, docs/ 등) 만 적용한다.
*
* @return array{0: int, 1: int} [zipSize, fileCount]
*/
private function writeZip(string $vendorPath, string $zipPath): array
{
if (! class_exists(\ZipArchive::class)) {
throw new VendorInstallException('zip_archive_not_available');
}
$zip = new \ZipArchive;
if ($zip->open($zipPath, \ZipArchive::CREATE | \ZipArchive::OVERWRITE) !== true) {
throw new VendorInstallException(
errorKey: 'extraction_failed',
context: ['message' => 'cannot create zip for writing: '.$zipPath],
);
}
$iterator = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($vendorPath, \RecursiveDirectoryIterator::SKIP_DOTS),
\RecursiveIteratorIterator::SELF_FIRST
);
// 경로 정규화 — Windows 의 경로 구분자 차이를 제거하여 Linux 와 동일하게 처리
$normalizedVendorPath = rtrim(str_replace('\\', '/', $vendorPath), '/');
$vendorPathLen = strlen($normalizedVendorPath);
$fileCount = 0;
foreach ($iterator as $file) {
$realPath = $file->getRealPath();
if ($realPath === false) {
continue;
}
// vendor 루트로부터의 상대 경로 계산 (OS 일관)
$normalizedReal = str_replace('\\', '/', $realPath);
if (! str_starts_with($normalizedReal, $normalizedVendorPath.'/')) {
continue;
}
$subPath = substr($normalizedReal, $vendorPathLen + 1);
if ($subPath === '' || $subPath === false) {
continue;
}
$relativePath = 'vendor/'.$subPath;
if ($this->shouldExclude($relativePath)) {
continue;
}
if ($file->isDir()) {
$zip->addEmptyDir($relativePath);
} else {
$zip->addFile($realPath, $relativePath);
$fileCount++;
}
}
$zip->close();
$size = @filesize($zipPath) ?: 0;
return [$size, $fileCount];
}
/**
* 제외 패턴 검사.
*/
private function shouldExclude(string $relativePath): bool
{
$segments = explode('/', $relativePath);
foreach ($segments as $segment) {
if (in_array($segment, self::EXCLUDE_PATTERNS, true)) {
return true;
}
}
return false;
}
/**
* composer.lock 에서 설치된 패키지 목록 추출.
*
* @return array<int, array{name: string, version: string, type: string}>
*/
private function collectPackages(string $composerLockPath): array
{
$json = @file_get_contents($composerLockPath);
if ($json === false) {
return [];
}
try {
$data = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
return [];
}
$packages = [];
foreach (($data['packages'] ?? []) as $package) {
if (! is_array($package)) {
continue;
}
$packages[] = [
'name' => (string) ($package['name'] ?? ''),
'version' => (string) ($package['version'] ?? ''),
'type' => (string) ($package['type'] ?? 'library'),
];
}
return $packages;
}
/**
* composer.json 에서 php 요구 버전 추출.
*/
private function extractPhpRequirement(string $composerJsonPath): ?string
{
$json = @file_get_contents($composerJsonPath);
if ($json === false) {
return null;
}
try {
$data = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
return null;
}
return $data['require']['php'] ?? null;
}
/**
* composer.json 에 외부 패키지 의존성이 선언되어 있는지 확인합니다.
*
* 런타임 제약(php, ext-*)만 있는 경우 false 를 반환합니다.
* 이런 확장은 vendor 번들링 대상이 아니므로 skip 처리됩니다.
*/
private function hasExternalDependencies(string $composerJsonPath): bool
{
$json = @file_get_contents($composerJsonPath);
if ($json === false) {
return false;
}
try {
$data = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
return false;
}
$require = $data['require'] ?? [];
if (! is_array($require) || empty($require)) {
return false;
}
foreach (array_keys($require) as $package) {
// php 버전 제약과 ext-* PHP 확장 제약은 외부 의존성이 아님
if ($package === 'php' || str_starts_with($package, 'ext-')) {
continue;
}
return true;
}
return false;
}
}
+46
View File
@@ -0,0 +1,46 @@
<?php
namespace App\Extension\Vendor;
/**
* Vendor 설치 요청 컨텍스트.
*
* CLI/웹/API 모든 진입점에서 공통으로 사용되는 설치 파라미터 DTO.
*/
class VendorInstallContext
{
/**
* @param string $target 'core' | 'module' | 'plugin'
* @param string|null $identifier 코어는 null, 확장은 식별자
* @param string $sourceDir vendor 설치 소스 경로 (vendor-bundle.zip이 이 위치에 있어야 함)
* @param string $targetDir vendor/가 배치될 경로 (보통 sourceDir과 동일)
* @param VendorMode $requestedMode 사용자 요청 모드
* @param VendorMode|null $previousMode 업데이트 시 이전 설치 모드 (DB에서 조회)
* @param string|null $composerBinaryHint composer 바이너리 경로 힌트
* @param bool $noDev composer --no-dev 플래그
* @param string $operation 'install' | 'update'
*/
public function __construct(
public readonly string $target,
public readonly ?string $identifier,
public readonly string $sourceDir,
public readonly string $targetDir,
public readonly VendorMode $requestedMode = VendorMode::Auto,
public readonly ?VendorMode $previousMode = null,
public readonly ?string $composerBinaryHint = null,
public readonly bool $noDev = true,
public readonly string $operation = 'install',
) {}
public function isCore(): bool
{
return $this->target === 'core';
}
public function label(): string
{
return $this->isCore()
? 'core'
: sprintf('%s:%s', $this->target, $this->identifier);
}
}
+33
View File
@@ -0,0 +1,33 @@
<?php
namespace App\Extension\Vendor;
/**
* Vendor 설치 결과 DTO.
*/
class VendorInstallResult
{
/**
* @param VendorMode $mode 실제로 사용된 모드 (auto가 resolver에 의해 해석된 결과)
* @param string $strategy 'composer' | 'bundled' | 'skipped'
* @param int $packageCount 설치된 패키지 수 (bundled일 때 manifest 기준)
* @param float $durationSeconds 설치 소요 시간
* @param array<string, mixed> $details 부가 정보 (composer 출력, bundle 크기 등)
*/
public function __construct(
public readonly VendorMode $mode,
public readonly string $strategy,
public readonly int $packageCount = 0,
public readonly float $durationSeconds = 0.0,
public readonly array $details = [],
) {}
public static function skipped(VendorMode $mode, string $reason): self
{
return new self(
mode: $mode,
strategy: 'skipped',
details: ['skip_reason' => $reason],
);
}
}
+141
View File
@@ -0,0 +1,141 @@
<?php
namespace App\Extension\Vendor;
/**
* vendor-bundle.json 기반 번들 파일의 무결성을 검증합니다.
*
* 검증 항목:
* - vendor-bundle.zip 존재 + SHA256 일치
* - vendor-bundle.json 존재 + 파싱 가능 + 스키마 버전 지원
* - composer.json/composer.lock SHA256 일치 (소스 디렉토리에 존재 시)
*/
class VendorIntegrityChecker
{
/**
* 지원하는 manifest 스키마 버전 목록.
*/
public const SUPPORTED_SCHEMA_VERSIONS = ['1.0'];
public const MANIFEST_FILENAME = 'vendor-bundle.json';
public const ZIP_FILENAME = 'vendor-bundle.zip';
/**
* 주어진 소스 디렉토리의 번들 무결성을 검증합니다.
*
* @param string $sourceDir vendor-bundle.zip 이 위치한 디렉토리
*/
public function verify(string $sourceDir): IntegrityResult
{
$zipPath = $sourceDir.DIRECTORY_SEPARATOR.self::ZIP_FILENAME;
$manifestPath = $sourceDir.DIRECTORY_SEPARATOR.self::MANIFEST_FILENAME;
// 1. 파일 존재 확인
if (! file_exists($zipPath)) {
return IntegrityResult::invalid(['bundle_zip_missing']);
}
if (! file_exists($manifestPath)) {
return IntegrityResult::invalid(['bundle_manifest_missing']);
}
// 2. manifest 파싱
$manifestJson = @file_get_contents($manifestPath);
if ($manifestJson === false) {
return IntegrityResult::invalid(['bundle_manifest_invalid']);
}
try {
$manifest = json_decode($manifestJson, true, 512, JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
return IntegrityResult::invalid(['bundle_manifest_invalid']);
}
if (! is_array($manifest)) {
return IntegrityResult::invalid(['bundle_manifest_invalid']);
}
// 3. 스키마 버전 확인
$schemaVersion = $manifest['schema_version'] ?? null;
if (! in_array($schemaVersion, self::SUPPORTED_SCHEMA_VERSIONS, true)) {
return IntegrityResult::invalid(['bundle_schema_unsupported'], $manifest);
}
$errors = [];
$warnings = [];
// 4. zip SHA256 검증
$expectedZipHash = $manifest['zip_sha256'] ?? null;
if ($expectedZipHash === null) {
$errors[] = 'bundle_manifest_invalid';
} else {
$actualZipHash = $this->computeFileHash($zipPath);
if (! hash_equals((string) $expectedZipHash, $actualZipHash)) {
$errors[] = 'zip_hash_mismatch';
}
}
// 5. composer.json/lock 해시 비교 (소스에 존재할 때만)
$composerJsonPath = $sourceDir.DIRECTORY_SEPARATOR.'composer.json';
if (file_exists($composerJsonPath)) {
$expected = $manifest['composer_json_sha256'] ?? null;
if ($expected !== null) {
$actual = $this->computeFileHash($composerJsonPath);
if (! hash_equals((string) $expected, $actual)) {
$errors[] = 'composer_json_sha_mismatch';
}
}
}
$composerLockPath = $sourceDir.DIRECTORY_SEPARATOR.'composer.lock';
if (file_exists($composerLockPath)) {
$expected = $manifest['composer_lock_sha256'] ?? null;
if ($expected !== null) {
$actual = $this->computeFileHash($composerLockPath);
if (! hash_equals((string) $expected, $actual)) {
$errors[] = 'composer_lock_sha_mismatch';
}
}
}
if (! empty($errors)) {
return IntegrityResult::invalid($errors, $manifest);
}
return IntegrityResult::valid($manifest, $warnings);
}
/**
* 파일의 SHA256 해시를 계산합니다.
*/
public function computeFileHash(string $path): string
{
return hash_file('sha256', $path) ?: '';
}
/**
* manifest만 파싱하여 반환 (검증 없이 메타 조회용).
*
* @return array<string, mixed>|null
*/
public function readManifest(string $sourceDir): ?array
{
$path = $sourceDir.DIRECTORY_SEPARATOR.self::MANIFEST_FILENAME;
if (! file_exists($path)) {
return null;
}
$json = @file_get_contents($path);
if ($json === false) {
return null;
}
try {
$data = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
return null;
}
return is_array($data) ? $data : null;
}
}
+41
View File
@@ -0,0 +1,41 @@
<?php
namespace App\Extension\Vendor;
/**
* Vendor 설치 모드.
*
* - Auto: composer 사용 가능 시 composer, 불가 시 bundled
* - Composer: 강제 composer 실행 (불가 시 예외)
* - Bundled: 강제 vendor-bundle.zip 추출 (zip 없으면 예외)
*/
enum VendorMode: string
{
case Auto = 'auto';
case Composer = 'composer';
case Bundled = 'bundled';
/**
* 다국어 라벨.
*/
public function label(): string
{
return match ($this) {
self::Auto => __('vendor.mode.auto'),
self::Composer => __('vendor.mode.composer'),
self::Bundled => __('vendor.mode.bundled'),
};
}
/**
* 문자열에서 안전하게 변환 (null/auto 폴백).
*/
public static function fromStringOrAuto(?string $value): self
{
if ($value === null || $value === '') {
return self::Auto;
}
return self::tryFrom($value) ?? self::Auto;
}
}
+170
View File
@@ -0,0 +1,170 @@
<?php
namespace App\Extension\Vendor;
use App\Extension\Vendor\Exceptions\VendorInstallException;
use Illuminate\Support\Facades\Log;
/**
* Vendor 설치 진입점.
*
* CLI / 웹 인스톨러 / Admin API 모든 경로가 최종적으로 이 클래스를 경유합니다.
* 모드를 결정(resolveMode)하고 적절한 전략으로 위임합니다.
*
* Composer 전략은 외부 콜백(executeComposer)에 위임 — 코어(CoreUpdateService)와
* 확장(ExtensionManager)이 각자 기존 composer 실행 로직을 전달하는 형태.
*/
class VendorResolver
{
public function __construct(
private readonly EnvironmentDetector $environmentDetector,
private readonly VendorIntegrityChecker $integrityChecker,
private readonly VendorBundleInstaller $bundleInstaller,
) {}
/**
* 사용할 Vendor 모드를 결정합니다.
*
* 우선순위:
* 1. 명시적 요청 모드 (composer/bundled) → 그대로 사용
* 2. 업데이트 시 이전 설치 모드 상속 (auto가 아닐 때)
* 3. 전역 기본값 config('app.install.default_vendor_mode')
* 4. 환경 감지: composer 가능하면 composer, 불가 시 번들 존재 여부 확인
*
* @throws VendorInstallException
*/
public function resolveMode(VendorInstallContext $ctx): VendorMode
{
// 1. 명시적 지정
if ($ctx->requestedMode !== VendorMode::Auto) {
return $ctx->requestedMode;
}
// 2. 업데이트 시 이전 모드 상속
if ($ctx->operation === 'update'
&& $ctx->previousMode !== null
&& $ctx->previousMode !== VendorMode::Auto
) {
return $ctx->previousMode;
}
// 3. 전역 기본값
$configured = config('app.install.default_vendor_mode', 'auto');
if ($configured !== 'auto') {
$parsed = VendorMode::tryFrom((string) $configured);
if ($parsed !== null && $parsed !== VendorMode::Auto) {
return $parsed;
}
}
// 4. auto → 환경 감지
if ($this->environmentDetector->canExecuteComposer($ctx->composerBinaryHint)) {
return VendorMode::Composer;
}
// 5. composer 불가 → 번들 존재 확인
$zipPath = $ctx->sourceDir.DIRECTORY_SEPARATOR.VendorIntegrityChecker::ZIP_FILENAME;
if (file_exists($zipPath)) {
return VendorMode::Bundled;
}
throw new VendorInstallException('no_vendor_strategy_available');
}
/**
* Vendor 설치를 수행합니다.
*
* @param VendorInstallContext $ctx 설치 컨텍스트
* @param callable|null $composerExecutor Composer 모드일 때 실행될 콜백
* 시그니처: fn(VendorInstallContext $ctx): VendorInstallResult
*
* @throws VendorInstallException
*/
public function install(VendorInstallContext $ctx, ?callable $composerExecutor = null): VendorInstallResult
{
$mode = $this->resolveMode($ctx);
Log::info('Vendor 설치 모드 결정됨', [
'target' => $ctx->label(),
'requested_mode' => $ctx->requestedMode->value,
'resolved_mode' => $mode->value,
'operation' => $ctx->operation,
]);
$this->validateModeFeasibility($mode, $ctx, $composerExecutor);
return match ($mode) {
VendorMode::Composer => $this->executeComposer($ctx, $composerExecutor),
VendorMode::Bundled => $this->executeBundle($ctx),
VendorMode::Auto => throw new VendorInstallException('no_vendor_strategy_available'),
};
}
/**
* 선택된 모드가 실제로 가능한지 사전 검증합니다.
*
* @throws VendorInstallException
*/
private function validateModeFeasibility(
VendorMode $mode,
VendorInstallContext $ctx,
?callable $composerExecutor,
): void {
if ($mode === VendorMode::Composer) {
if (! $this->environmentDetector->canExecuteComposer($ctx->composerBinaryHint)) {
throw new VendorInstallException('composer_not_available');
}
if ($composerExecutor === null) {
throw new VendorInstallException(
errorKey: 'composer_execution_failed',
context: ['message' => 'composer executor callback not provided'],
);
}
return;
}
if ($mode === VendorMode::Bundled) {
$zipPath = $ctx->sourceDir.DIRECTORY_SEPARATOR.VendorIntegrityChecker::ZIP_FILENAME;
if (! file_exists($zipPath)) {
throw new VendorInstallException(
errorKey: 'bundle_zip_missing',
context: ['path' => $zipPath],
);
}
$integrity = $this->integrityChecker->verify($ctx->sourceDir);
if (! $integrity->valid) {
throw new VendorInstallException(
errorKey: 'bundle_integrity_failed',
context: ['details' => implode(', ', $integrity->errorMessages())],
);
}
}
}
private function executeComposer(VendorInstallContext $ctx, callable $composerExecutor): VendorInstallResult
{
$startTime = microtime(true);
$result = $composerExecutor($ctx);
$duration = microtime(true) - $startTime;
if ($result instanceof VendorInstallResult) {
return $result;
}
// 콜백이 단순 true/void를 반환한 경우 — 기본 결과 생성
return new VendorInstallResult(
mode: VendorMode::Composer,
strategy: 'composer',
packageCount: 0,
durationSeconds: $duration,
details: ['raw_result' => $result],
);
}
private function executeBundle(VendorInstallContext $ctx): VendorInstallResult
{
return $this->bundleInstaller->install($ctx->sourceDir, $ctx->targetDir);
}
}