v7.0.0-beta.2 release
This commit is contained in:
1 parent
6595fd0eb5
commit
fa8eba7a0d
1165 files changed
+107118
-762127
No files matched your search
@@ -0,0 +1,134 @@
|
||||
<?php
|
||||
|
||||
namespace App\Extension\Helpers;
|
||||
|
||||
use App\Contracts\Repositories\ModuleRepositoryInterface;
|
||||
use App\Contracts\Repositories\PluginRepositoryInterface;
|
||||
use Composer\Semver\Semver;
|
||||
use Illuminate\Support\Facades\App;
|
||||
|
||||
/**
|
||||
* 확장 의존성 정보 보강 헬퍼
|
||||
*
|
||||
* manifest 의 dependencies 필드(`{modules|plugins}.{id}: versionConstraint`) 를 받아
|
||||
* 각 의존 확장의 설치 버전, 활성 여부, 버전 제약 충족 여부를 포함한 상세 배열로 변환합니다.
|
||||
* ModuleManager / PluginManager / TemplateResource 가 공용으로 사용합니다.
|
||||
*/
|
||||
class DependencyEnricher
|
||||
{
|
||||
/**
|
||||
* 의존성 배열을 상세 정보로 보강합니다.
|
||||
*
|
||||
* @param array $dependencies manifest 의 dependencies 배열 (`['modules' => [...], 'plugins' => [...]]`)
|
||||
* @return array<int, array<string, mixed>> 보강된 의존성 목록 (type 필드로 module/plugin 구분)
|
||||
*/
|
||||
public static function enrich(array $dependencies): array
|
||||
{
|
||||
$result = [];
|
||||
|
||||
foreach (self::enrichByType($dependencies, 'modules') as $item) {
|
||||
$result[] = $item;
|
||||
}
|
||||
|
||||
foreach (self::enrichByType($dependencies, 'plugins') as $item) {
|
||||
$result[] = $item;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 타입(modules/plugins)의 의존성만 보강합니다.
|
||||
*
|
||||
* @param array $dependencies manifest 의 dependencies 배열
|
||||
* @param string $type 'modules' 또는 'plugins'
|
||||
* @return array<int, array<string, mixed>> 보강된 의존성 목록
|
||||
*/
|
||||
protected static function enrichByType(array $dependencies, string $type): array
|
||||
{
|
||||
if (! isset($dependencies[$type]) || ! is_array($dependencies[$type])) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$singular = $type === 'modules' ? 'module' : 'plugin';
|
||||
$repository = $type === 'modules'
|
||||
? app(ModuleRepositoryInterface::class)
|
||||
: app(PluginRepositoryInterface::class);
|
||||
|
||||
$result = [];
|
||||
|
||||
foreach ($dependencies[$type] as $identifier => $versionConstraint) {
|
||||
$record = $repository->findByIdentifier($identifier);
|
||||
$activeRecord = $repository->findActiveByIdentifier($identifier);
|
||||
|
||||
$installedVersion = $record?->version;
|
||||
$isActive = (bool) $activeRecord;
|
||||
$isMet = $isActive
|
||||
&& $installedVersion
|
||||
&& self::checkVersionConstraint($installedVersion, (string) $versionConstraint);
|
||||
|
||||
$result[] = [
|
||||
'identifier' => $identifier,
|
||||
'name' => self::resolveName($record, $identifier),
|
||||
'type' => $singular,
|
||||
'required_version' => $versionConstraint,
|
||||
'installed_version' => $installedVersion,
|
||||
'is_active' => $isActive,
|
||||
'is_met' => $isMet,
|
||||
];
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Semver 제약 조건을 검증합니다.
|
||||
*
|
||||
* @param string $installedVersion 설치된 버전
|
||||
* @param string $versionConstraint 요구 버전 제약
|
||||
* @return bool 제약 충족 여부
|
||||
*/
|
||||
public static function checkVersionConstraint(string $installedVersion, string $versionConstraint): bool
|
||||
{
|
||||
try {
|
||||
return Semver::satisfies($installedVersion, $versionConstraint);
|
||||
} catch (\Exception $e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 확장 모델에서 현재 로케일의 이름을 추출합니다.
|
||||
*
|
||||
* @param object|null $record 확장 모델 (Module/Plugin)
|
||||
* @param string $fallback 모델이 없을 때 반환할 식별자
|
||||
* @return string 이름
|
||||
*/
|
||||
protected static function resolveName(?object $record, string $fallback): string
|
||||
{
|
||||
if (! $record) {
|
||||
return $fallback;
|
||||
}
|
||||
|
||||
$name = $record->name ?? null;
|
||||
|
||||
if (is_array($name)) {
|
||||
$locale = App::getLocale();
|
||||
$fallbackLocale = config('app.fallback_locale', 'ko');
|
||||
|
||||
return (string) ($name[$locale] ?? $name[$fallbackLocale] ?? reset($name) ?: $fallback);
|
||||
}
|
||||
|
||||
if (is_string($name) && str_starts_with($name, '{')) {
|
||||
$decoded = json_decode($name, true);
|
||||
if (is_array($decoded)) {
|
||||
$locale = App::getLocale();
|
||||
$fallbackLocale = config('app.fallback_locale', 'ko');
|
||||
|
||||
return (string) ($decoded[$locale] ?? $decoded[$fallbackLocale] ?? reset($decoded) ?: $fallback);
|
||||
}
|
||||
}
|
||||
|
||||
return (string) ($name ?? $fallback);
|
||||
}
|
||||
}
|
||||
@@ -205,9 +205,17 @@ class ExtensionMenuSyncHelper
|
||||
/**
|
||||
* 현재 확장에 속하지 않는 stale 메뉴를 정리합니다.
|
||||
*
|
||||
* ⚠️ 주의: 이 메서드는 정적 정의(getAdminMenus()) 기반으로만 판단하므로,
|
||||
* 확장이 런타임에 동적으로 생성한 메뉴도 삭제됩니다.
|
||||
* 자동 호출은 폐기되었으며, 필요 시 UpgradeStep에서 명시적으로 호출하세요.
|
||||
* 정책:
|
||||
* - config/확장 정의에 없는 메뉴는 **user_overrides 유무 무관 삭제**
|
||||
* - 필드 단위 보존은 **upsert 시점(`syncMenu()`)** 에서만 작동 (유지 row 에 한해 override 필드만 보존)
|
||||
* - row 자체의 존재 여부는 config 기준으로만 결정 (사용자 수정 이력이 있어도 정의에서 제거되면 삭제)
|
||||
*
|
||||
* 자식 메뉴는 부모 삭제 시 함께 정리 (orphan 회피).
|
||||
*
|
||||
* 자동 호출 경로:
|
||||
* - `CoreUpdateService::syncCoreMenus()` 말미 (완전 동기화 원칙)
|
||||
* - `ModuleManager::updateModule()` 말미 (확장 동기화)
|
||||
* - UpgradeStep 에서 명시 호출
|
||||
*
|
||||
* @param ExtensionOwnerType $extensionType 확장 타입
|
||||
* @param string $extensionIdentifier 확장 식별자
|
||||
@@ -225,20 +233,22 @@ class ExtensionMenuSyncHelper
|
||||
|
||||
$deleted = 0;
|
||||
foreach ($existingMenus as $menu) {
|
||||
if (! in_array($menu->slug, $currentSlugs, true)) {
|
||||
// role_menus 피벗 정리
|
||||
$menu->roles()->detach();
|
||||
if (in_array($menu->slug, $currentSlugs, true)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 자식 메뉴 먼저 삭제
|
||||
foreach ($menu->children as $child) {
|
||||
$child->roles()->detach();
|
||||
$this->menuRepository->delete($child);
|
||||
$deleted++;
|
||||
}
|
||||
// role_menus 피벗 정리
|
||||
$menu->roles()->detach();
|
||||
|
||||
$this->menuRepository->delete($menu);
|
||||
// 자식 메뉴 먼저 삭제 (orphan 회피)
|
||||
foreach ($menu->children as $child) {
|
||||
$child->roles()->detach();
|
||||
$this->menuRepository->delete($child);
|
||||
$deleted++;
|
||||
}
|
||||
|
||||
$this->menuRepository->delete($menu);
|
||||
$deleted++;
|
||||
}
|
||||
|
||||
if ($deleted > 0) {
|
||||
|
||||
@@ -57,6 +57,17 @@ class ExtensionPendingHelper
|
||||
$dirName = basename($dir);
|
||||
$identifier = $data['identifier'] ?? $dirName;
|
||||
|
||||
// 디렉토리명과 identifier 가 일치하는 경우만 등록.
|
||||
// _pending / _bundled 에는 업데이트·백업 과정의 임시 디렉토리
|
||||
// (예: sirsoft-admin_basic_20260402_081819, sirsoft-admin_basic_updating_<uniq>,
|
||||
// sirsoft-admin_basic_old_<uniq>) 가 남을 수 있고, 그 내부에 원본 manifest 가 그대로
|
||||
// 있어 identifier 가 원본과 동일해진다. 이 경우 표준 경로({basePath}/{subDir}/{identifier})
|
||||
// 와 실제 디렉토리 경로가 어긋나 install 이 실패하므로, 엄격히 일치하는 경로만
|
||||
// 정식 확장 소스로 인정한다.
|
||||
if ($dirName !== $identifier) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$result[$identifier] = array_merge($data, [
|
||||
'identifier' => $identifier,
|
||||
'directory' => $dirName,
|
||||
@@ -178,6 +189,19 @@ class ExtensionPendingHelper
|
||||
|
||||
// 교체 완료 후 _old 삭제 (실패해도 무해)
|
||||
File::deleteDirectory($oldPath);
|
||||
|
||||
// 원자적 rename 은 inode 단위로 교체되므로 PHP realpath/stat 캐시가
|
||||
// 이전 디렉토리의 파일 존재 여부를 기준으로 판단할 수 있다. 직후 Composer
|
||||
// PSR-4 autoload 가 신규 파일(beta.1 에 없던 Seeder/Model)을 file_exists 로
|
||||
// 탐색할 때 false 반환 → "Class not found" fatal 로 업그레이드 스텝이 실패.
|
||||
// clearstatcache(true) 로 전체 stat 캐시를 비워 신규 파일이 즉시 보이도록 한다.
|
||||
clearstatcache(true);
|
||||
|
||||
// opcache 가 활성화된 프로덕션에서는 활성 디렉토리 하위의 이전 컴파일 바이트코드가
|
||||
// 남아있을 수 있어 신규 PHP 파일을 즉시 invalidate (재컴파일 유도).
|
||||
if (function_exists('opcache_reset')) {
|
||||
@opcache_reset();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -127,9 +127,14 @@ class ExtensionRoleSyncHelper
|
||||
/**
|
||||
* 현재 확장에 속하지 않는 stale 권한을 정리합니다.
|
||||
*
|
||||
* ⚠️ 주의: 이 메서드는 정적 정의(getPermissions()) 기반으로만 판단하므로,
|
||||
* 확장이 런타임에 동적으로 생성한 권한도 삭제됩니다.
|
||||
* 자동 호출은 폐기되었으며, 필요 시 UpgradeStep에서 명시적으로 호출하세요.
|
||||
* Permission 은 설계상 **관리자가 직접 수정할 수 없는 테이블** 이므로 `user_overrides`
|
||||
* 컬럼 자체가 없습니다 (Menu/Role 과 달리). 따라서 단순 diff 로 삭제합니다.
|
||||
* 자식 권한도 동일하게 순수 orphan 삭제.
|
||||
*
|
||||
* 자동 호출 경로:
|
||||
* - `CoreUpdateService::syncCoreRolesAndPermissions()` 말미 (완전 동기화 원칙)
|
||||
* - `ModuleManager::updateModule()` 말미
|
||||
* - UpgradeStep 에서 명시 호출
|
||||
*
|
||||
* @param ExtensionOwnerType $extensionType 확장 타입
|
||||
* @param string $extensionIdentifier 확장 식별자
|
||||
@@ -147,18 +152,22 @@ class ExtensionRoleSyncHelper
|
||||
|
||||
$deleted = 0;
|
||||
foreach ($existingPermissions as $permission) {
|
||||
if (! in_array($permission->identifier, $currentIdentifiers, true)) {
|
||||
// 역할 연결 해제
|
||||
$permission->roles()->detach();
|
||||
// 자식 권한도 정리
|
||||
foreach ($permission->children as $child) {
|
||||
$child->roles()->detach();
|
||||
$this->permissionRepository->delete($child);
|
||||
$deleted++;
|
||||
}
|
||||
$this->permissionRepository->delete($permission);
|
||||
if (in_array($permission->identifier, $currentIdentifiers, true)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 역할 연결 해제
|
||||
$permission->roles()->detach();
|
||||
|
||||
// 자식 권한도 정리 (orphan 회피)
|
||||
foreach ($permission->children as $child) {
|
||||
$child->roles()->detach();
|
||||
$this->permissionRepository->delete($child);
|
||||
$deleted++;
|
||||
}
|
||||
|
||||
$this->permissionRepository->delete($permission);
|
||||
$deleted++;
|
||||
}
|
||||
|
||||
if ($deleted > 0) {
|
||||
@@ -172,6 +181,70 @@ class ExtensionRoleSyncHelper
|
||||
return $deleted;
|
||||
}
|
||||
|
||||
/**
|
||||
* 현재 확장에 속하지 않는 stale 역할을 정리합니다.
|
||||
*
|
||||
* 정책:
|
||||
* - config/확장 정의에 없는 역할은 **user_overrides 유무 무관 삭제**
|
||||
* - 필드 단위 보존은 upsert 시점(`syncRole()`) 에서만 작동
|
||||
* - 예외: `user_roles` 피벗에 참조 사용자가 있으면 **삭제 차단** + 경고 로그
|
||||
* (사용자를 다른 역할로 수동 재배정 후 재실행)
|
||||
*
|
||||
* @param ExtensionOwnerType $extensionType 확장 타입
|
||||
* @param string $extensionIdentifier 확장 식별자
|
||||
* @param array $currentIdentifiers 현재 유효한 역할 식별자 목록
|
||||
* @return int 삭제된 역할 수
|
||||
*/
|
||||
public function cleanupStaleRoles(
|
||||
ExtensionOwnerType $extensionType,
|
||||
string $extensionIdentifier,
|
||||
array $currentIdentifiers,
|
||||
): int {
|
||||
$existingRoles = $this->roleRepository->getByExtension($extensionType, $extensionIdentifier);
|
||||
|
||||
$deleted = 0;
|
||||
$blocked = 0;
|
||||
|
||||
foreach ($existingRoles as $role) {
|
||||
if (in_array($role->identifier, $currentIdentifiers, true)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// user_roles 피벗 참조 검사 — 하나라도 있으면 삭제 차단 (안전 가드)
|
||||
$userCount = $role->users()->count();
|
||||
if ($userCount > 0) {
|
||||
Log::warning('stale 역할 삭제 차단 — 참조 사용자 존재', [
|
||||
'identifier' => $role->identifier,
|
||||
'id' => $role->id,
|
||||
'user_count' => $userCount,
|
||||
'remediation' => '사용자를 다른 역할로 재배정 후 재실행 필요',
|
||||
]);
|
||||
$blocked++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
// 조건 통과 → 삭제 (role_permissions, role_menus 는 cascade 또는 모델 이벤트로 정리)
|
||||
$this->roleRepository->delete($role);
|
||||
Log::info('stale 역할 삭제', [
|
||||
'identifier' => $role->identifier,
|
||||
'id' => $role->id,
|
||||
]);
|
||||
$deleted++;
|
||||
}
|
||||
|
||||
if ($deleted > 0 || $blocked > 0) {
|
||||
Log::info('stale 역할 정리 결과', [
|
||||
'extension_type' => $extensionType->value,
|
||||
'extension_identifier' => $extensionIdentifier,
|
||||
'deleted' => $deleted,
|
||||
'blocked' => $blocked,
|
||||
]);
|
||||
}
|
||||
|
||||
return $deleted;
|
||||
}
|
||||
|
||||
/**
|
||||
* 확장의 전체 역할-권한 할당을 일괄 동기화합니다.
|
||||
*
|
||||
|
||||
@@ -60,6 +60,24 @@ class FileHandleHelper
|
||||
return [];
|
||||
}
|
||||
|
||||
// 존재하지 않는 디렉토리는 잠금이 있을 수 없음 → WMI 전체 스캔 회피
|
||||
// (Get-Process 의 Modules 열거는 수백 프로세스에 접근 핸들을 열어 20초+ 소요 가능)
|
||||
if (! is_dir($directoryPath)) {
|
||||
$output('[lock-detect] 디렉토리가 존재하지 않으므로 잠금 감지를 건너뜁니다: '.$directoryPath);
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
// 파일이 전혀 없는 디렉토리도 파일 수준 잠금이 있을 수 없음
|
||||
// 디렉토리 핸들 자체를 잠그는 드문 케이스는 Restart Manager 로는 감지 불가하고
|
||||
// WMI 모듈 검색의 비용이 압도적으로 크므로 빠른 경로로 처리한다.
|
||||
$files = self::sampleFiles($directoryPath, $maxFiles);
|
||||
if (empty($files)) {
|
||||
$output('[lock-detect] 디렉토리가 비어 있으므로 잠금 감지를 건너뜁니다: '.$directoryPath);
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
$allProcesses = [];
|
||||
|
||||
// 1순위: WMI CommandLine + 프로세스 모듈 검색
|
||||
@@ -70,27 +88,18 @@ class FileHandleHelper
|
||||
}
|
||||
|
||||
// 2순위: Restart Manager API (파일 수준 잠금)
|
||||
$files = self::sampleFiles($directoryPath, $maxFiles);
|
||||
if (! empty($files)) {
|
||||
$output('[lock-detect] 2단계: Restart Manager API ('.count($files).'개 파일)...');
|
||||
$rmResults = self::detectViaRestartManager($files, $onOutput);
|
||||
foreach ($rmResults as $proc) {
|
||||
if (! isset($allProcesses[$proc['pid']])) {
|
||||
$allProcesses[$proc['pid']] = $proc;
|
||||
}
|
||||
$output('[lock-detect] 2단계: Restart Manager API ('.count($files).'개 파일)...');
|
||||
$rmResults = self::detectViaRestartManager($files, $onOutput);
|
||||
foreach ($rmResults as $proc) {
|
||||
if (! isset($allProcesses[$proc['pid']])) {
|
||||
$allProcesses[$proc['pid']] = $proc;
|
||||
}
|
||||
}
|
||||
|
||||
// 3순위: handle.exe 폴백
|
||||
if (empty($allProcesses)) {
|
||||
$output('[lock-detect] 3단계: handle.exe 폴백...');
|
||||
$handleResults = self::detectViaHandle($directoryPath, $onOutput);
|
||||
foreach ($handleResults as $proc) {
|
||||
if (! isset($allProcesses[$proc['pid']])) {
|
||||
$allProcesses[$proc['pid']] = $proc;
|
||||
}
|
||||
}
|
||||
}
|
||||
// 빈 결과 = "잠금 없음" 이라는 정상 응답이므로 폴백을 호출하지 않는다.
|
||||
// (handle.exe 는 Sysinternals 외부 도구이고, Windows Store App Execution Alias 와
|
||||
// 충돌하는 경우 무한 대기하므로 명시적으로 사용 가능한 경우에만 호출.)
|
||||
|
||||
// 현재 PHP 프로세스 제외
|
||||
$currentPid = self::currentPid();
|
||||
@@ -165,12 +174,8 @@ class FileHandleHelper
|
||||
$processes = self::findLockingProcesses($directoryPath, 30, $onOutput);
|
||||
|
||||
if (empty($processes)) {
|
||||
$output('');
|
||||
$output('ℹ️ 잠금 프로세스가 감지되지 않았습니다.');
|
||||
$output(' 수동 해결: 해당 디렉토리를 참조하는 프로세스를 닫은 후 재시도하세요.');
|
||||
$output('');
|
||||
|
||||
return false;
|
||||
// 해제할 잠금이 없으므로 호출자는 안전하게 진행 가능
|
||||
return true;
|
||||
}
|
||||
|
||||
$output('');
|
||||
@@ -224,9 +229,14 @@ class FileHandleHelper
|
||||
/**
|
||||
* WMI로 해당 디렉토리 경로를 참조하는 프로세스를 탐지합니다.
|
||||
*
|
||||
* Get-CimInstance Win32_Process의 CommandLine에 디렉토리 경로가 포함된 프로세스와,
|
||||
* Get-Process의 Modules에서 해당 디렉토리 내 DLL을 로드한 프로세스를 찾습니다.
|
||||
* Node.js 워처, IDE, 파일 탐색기 등 프로세스 종류 무관하게 감지합니다.
|
||||
* Get-CimInstance Win32_Process의 CommandLine에 디렉토리 경로가 포함된 프로세스를 찾습니다.
|
||||
*
|
||||
* 과거 버전은 Get-Process 의 Modules 컬렉션(로드된 DLL) 까지 스캔했지만,
|
||||
* 이는 모든 프로세스에 접근 핸들을 열어 DLL 테이블을 열거하므로
|
||||
* 활성 프로세스가 수백 개인 Windows 환경에서 20초+ 블로킹을 유발합니다.
|
||||
* Modules 스캔은 Node.js native addon 등 드문 케이스만 감지하므로
|
||||
* 비용 대비 효과가 낮아 CommandLine 검색만 유지합니다.
|
||||
* (Node 워처, IDE, 파일 탐색기 등 실사용 케이스는 CommandLine 으로 충분히 감지됩니다.)
|
||||
*
|
||||
* @param string $directoryPath 디렉토리 경로
|
||||
* @param \Closure|null $onOutput 진단 출력 콜백
|
||||
@@ -247,25 +257,21 @@ class FileHandleHelper
|
||||
$escapedPath = str_replace("'", "''", $normalizedPath);
|
||||
|
||||
// 간결한 인라인 PowerShell — 임시 파일 불필요
|
||||
// CommandLine 검색만 수행 (Modules 스캔은 수백 프로세스 핸들 오픈으로 인해 제거됨)
|
||||
$psCommand = implode('; ', [
|
||||
'$ErrorActionPreference = "SilentlyContinue"',
|
||||
'$p = "'.addcslashes($escapedPath, '"').'"',
|
||||
'$pl = $p.ToLower()',
|
||||
'$r = @{}',
|
||||
// Strategy 1: CommandLine search
|
||||
'Get-CimInstance Win32_Process | ForEach-Object { if ($_.CommandLine) { $cl = $_.CommandLine.ToLower().Replace("/","\\"); if ($cl.Contains($pl)) { $r[$_.ProcessId] = "$($_.ProcessId)|$($_.Name)|$($_.CommandLine.Substring(0,[Math]::Min(120,$_.CommandLine.Length)))" } } }',
|
||||
// Strategy 2: Modules search
|
||||
'Get-Process | ForEach-Object { if (-not $r.ContainsKey($_.Id)) { try { foreach ($m in $_.Modules) { if ($m.FileName -and $m.FileName.ToLower().StartsWith($pl)) { $r[$_.Id] = "$($_.Id)|$($_.ProcessName)|module:$($m.FileName)"; break } } } catch {} } }',
|
||||
// Output
|
||||
'foreach ($v in $r.Values) { Write-Output $v }',
|
||||
]);
|
||||
|
||||
$cmdOutput = [];
|
||||
$exitCode = 0;
|
||||
exec(
|
||||
'powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -Command '.escapeshellarg($psCommand).' 2>NUL',
|
||||
$cmdOutput,
|
||||
$exitCode
|
||||
// exec() 대신 proc_open 사용 — PHPUnit 환경에서 상속된 부모 파이프로 인한
|
||||
// PowerShell 하위 프로세스 블로킹을 회피한다.
|
||||
[$cmdOutput, $exitCode] = self::runCommandWithTimeout(
|
||||
'powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -Command '.escapeshellarg($psCommand),
|
||||
30
|
||||
);
|
||||
|
||||
$output("[WMI] PowerShell exit code: {$exitCode}, 출력: ".count($cmdOutput).'줄');
|
||||
@@ -320,14 +326,16 @@ class FileHandleHelper
|
||||
$stderrPath = $scriptPath.'.err';
|
||||
|
||||
try {
|
||||
$cmdOutput = [];
|
||||
$exitCode = 0;
|
||||
exec(
|
||||
'powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File '.escapeshellarg($scriptPath).' 2>'.escapeshellarg($stderrPath),
|
||||
$cmdOutput,
|
||||
$exitCode
|
||||
[$cmdOutput, $exitCode, $stderrCaptured] = self::runCommandWithTimeout(
|
||||
'powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File '.escapeshellarg($scriptPath),
|
||||
30,
|
||||
true
|
||||
);
|
||||
|
||||
if ($stderrCaptured !== '') {
|
||||
@file_put_contents($stderrPath, $stderrCaptured);
|
||||
}
|
||||
|
||||
$output("[RestartManager] exit code: {$exitCode}, 출력: ".count($cmdOutput).'줄');
|
||||
|
||||
if (file_exists($stderrPath)) {
|
||||
@@ -480,14 +488,25 @@ PSFOOTER;
|
||||
return [];
|
||||
}
|
||||
|
||||
$cmdOutput = [];
|
||||
$exitCode = 0;
|
||||
// PATH 에 handle.exe 가 있는지 사전 검사 (없는 경우 즉시 skip)
|
||||
// - handle.exe 미설치 시 cmd.exe 가 명령을 찾는 데 수십 초가 걸리거나
|
||||
// EULA 다이얼로그로 인해 무한 대기에 빠질 수 있음.
|
||||
// - 결과는 정적 캐시하여 같은 프로세스에서 반복 검사 회피.
|
||||
static $handleAvailable = null;
|
||||
if ($handleAvailable === null) {
|
||||
$handleAvailable = self::isCommandAvailable('handle.exe');
|
||||
}
|
||||
|
||||
if (! $handleAvailable) {
|
||||
$logOutput('[handle.exe] PATH 에서 찾을 수 없어 건너뜁니다.');
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
$dirPath = str_replace('/', '\\', $directoryPath);
|
||||
exec(
|
||||
'handle.exe -nobanner -accepteula '.escapeshellarg($dirPath).' 2>NUL',
|
||||
$cmdOutput,
|
||||
$exitCode
|
||||
[$cmdOutput, $exitCode] = self::runCommandWithTimeout(
|
||||
'handle.exe -nobanner -accepteula '.escapeshellarg($dirPath),
|
||||
5
|
||||
);
|
||||
|
||||
if ($exitCode !== 0 || empty($cmdOutput)) {
|
||||
@@ -501,6 +520,43 @@ PSFOOTER;
|
||||
return self::parseHandleOutput($cmdOutput);
|
||||
}
|
||||
|
||||
/**
|
||||
* Windows PATH 에서 명령어 실행 파일이 발견되는지 빠르게 확인합니다.
|
||||
*
|
||||
* Windows Store App Execution Alias(`%LOCALAPPDATA%\Microsoft\WindowsApps\*.exe`)는
|
||||
* 실제 실행 파일이 아닌 0바이트 stub 으로, 호출 시 Microsoft Store 앱을 실행하려
|
||||
* 시도하면서 무한 대기를 유발합니다. PATH 검색 결과에서 이런 경로를 제외합니다.
|
||||
*
|
||||
* @param string $command 명령어 파일명 (예: 'handle.exe')
|
||||
*/
|
||||
private static function isCommandAvailable(string $command): bool
|
||||
{
|
||||
if (! self::isWindows()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// `where` 는 PATH 검색이 빠르며, 미발견 시 1초 이내에 exit code 1 반환
|
||||
[$out, $code] = self::runCommandWithTimeout('where '.escapeshellarg($command), 3);
|
||||
|
||||
if ($code !== 0 || empty($out)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Windows Store App Execution Alias 경로 제외
|
||||
foreach ($out as $path) {
|
||||
$path = trim($path);
|
||||
if ($path === '' || stripos($path, '\\Microsoft\\WindowsApps\\') !== false) {
|
||||
continue;
|
||||
}
|
||||
// 0 바이트 파일은 stub 으로 간주
|
||||
if (@filesize($path) > 0) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// 파서/유틸리티
|
||||
// ========================================================================
|
||||
@@ -606,6 +662,116 @@ PSFOOTER;
|
||||
return $processes;
|
||||
}
|
||||
|
||||
/**
|
||||
* 외부 명령을 타임아웃과 함께 실행합니다 (부모 파이프 비상속).
|
||||
*
|
||||
* exec()/shell_exec() 는 내부적으로 `sh -c` 또는 `cmd.exe /c` 를 통해 자식
|
||||
* 프로세스를 스폰하며, 부모 PHP 프로세스의 stdin/stdout/stderr 핸들을 그대로
|
||||
* 상속시킵니다. PHPUnit 과 같이 stdout 을 자체 파이프로 모니터링하는 환경에서는
|
||||
* 자식 프로세스가 상속된 파이프에 블로킹 쓰기를 수행할 때 무한 대기가 발생합니다.
|
||||
*
|
||||
* proc_open 으로 자체 파이프를 명시적으로 열면 상속을 차단하여 이 문제를 회피합니다.
|
||||
* 또한 poll 루프에서 deadline 을 초과하면 강제 종료(TerminateProcess)합니다.
|
||||
*
|
||||
* @param string $command 실행할 명령 문자열
|
||||
* @param int $timeoutSeconds 최대 실행 시간(초)
|
||||
* @param bool $returnStderr true 면 세 번째 요소로 stderr 문자열을 함께 반환
|
||||
* @return array{0: string[], 1: int, 2?: string} [stdout 라인 배열, exit code, (stderr 문자열)]
|
||||
*/
|
||||
private static function runCommandWithTimeout(string $command, int $timeoutSeconds, bool $returnStderr = false): array
|
||||
{
|
||||
$descriptors = [
|
||||
0 => ['pipe', 'r'],
|
||||
1 => ['pipe', 'w'],
|
||||
2 => ['pipe', 'w'],
|
||||
];
|
||||
|
||||
$pipes = [];
|
||||
$process = @proc_open($command, $descriptors, $pipes, null, null, [
|
||||
'bypass_shell' => false,
|
||||
'create_new_console' => false,
|
||||
]);
|
||||
|
||||
if (! is_resource($process)) {
|
||||
return $returnStderr ? [[], -1, ''] : [[], -1];
|
||||
}
|
||||
|
||||
// stdin 즉시 닫기 (하위 프로세스가 입력 대기 방지)
|
||||
fclose($pipes[0]);
|
||||
|
||||
stream_set_blocking($pipes[1], false);
|
||||
stream_set_blocking($pipes[2], false);
|
||||
|
||||
$stdout = '';
|
||||
$stderr = '';
|
||||
$deadline = microtime(true) + $timeoutSeconds;
|
||||
$timedOut = false;
|
||||
|
||||
while (true) {
|
||||
$status = proc_get_status($process);
|
||||
if (! $status['running']) {
|
||||
break;
|
||||
}
|
||||
|
||||
if (microtime(true) >= $deadline) {
|
||||
$timedOut = true;
|
||||
break;
|
||||
}
|
||||
|
||||
$read = [$pipes[1], $pipes[2]];
|
||||
$write = null;
|
||||
$except = null;
|
||||
// 100ms 씩 poll (Windows 는 select() 정확도 한계)
|
||||
$ready = @stream_select($read, $write, $except, 0, 100_000);
|
||||
|
||||
if ($ready > 0) {
|
||||
foreach ($read as $stream) {
|
||||
$chunk = fread($stream, 8192);
|
||||
if ($chunk !== false && $chunk !== '') {
|
||||
if ($stream === $pipes[1]) {
|
||||
$stdout .= $chunk;
|
||||
} else {
|
||||
$stderr .= $chunk;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 남은 출력 흡수
|
||||
$stdout .= stream_get_contents($pipes[1]) ?: '';
|
||||
$stderr .= stream_get_contents($pipes[2]) ?: '';
|
||||
|
||||
fclose($pipes[1]);
|
||||
fclose($pipes[2]);
|
||||
|
||||
if ($timedOut) {
|
||||
// Windows: taskkill /F /T 로 자식 트리까지 종료
|
||||
$status = proc_get_status($process);
|
||||
if (! empty($status['pid'])) {
|
||||
if (PHP_OS_FAMILY === 'Windows') {
|
||||
@exec('taskkill /F /T /PID '.$status['pid'].' 2>NUL');
|
||||
} else {
|
||||
@posix_kill($status['pid'], 9);
|
||||
}
|
||||
}
|
||||
proc_terminate($process, 9);
|
||||
}
|
||||
|
||||
$exitCode = proc_close($process);
|
||||
|
||||
$lines = $stdout === '' ? [] : preg_split("/\r\n|\n|\r/", rtrim($stdout, "\r\n"));
|
||||
if ($lines === false) {
|
||||
$lines = [];
|
||||
}
|
||||
|
||||
if ($returnStderr) {
|
||||
return [$lines, $exitCode, $stderr];
|
||||
}
|
||||
|
||||
return [$lines, $exitCode];
|
||||
}
|
||||
|
||||
/**
|
||||
* 시스템 프로세스 여부를 확인합니다.
|
||||
*
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Extension\Helpers;
|
||||
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class FilePermissionHelper
|
||||
{
|
||||
@@ -10,12 +11,16 @@ class FilePermissionHelper
|
||||
* 디렉토리를 재귀적으로 복사하면서 기존 파일/디렉토리의 퍼미션을 보존합니다.
|
||||
*
|
||||
* - 기존 디렉토리: 퍼미션/소유자/그룹 유지
|
||||
* - 신규 디렉토리: 부모 디렉토리의 퍼미션 상속
|
||||
* - 신규 디렉토리: 부모 디렉토리의 퍼미션/소유자/그룹 상속
|
||||
* - 기존 파일: 퍼미션/소유자/그룹 유지한 채 내용만 교체
|
||||
* - 신규 파일: PHP 기본 퍼미션 적용 (umask 기반)
|
||||
* - 신규 파일: 부모 디렉토리의 소유자/그룹 상속 (퍼미션은 PHP 기본 umask)
|
||||
* - removeOrphans=false: 소스에 없고 대상에만 있는 파일 유지 (사용자 추가 파일 보호)
|
||||
* - removeOrphans=true: 소스에 없고 대상에만 있는 파일/디렉토리 삭제 (excludes 제외)
|
||||
*
|
||||
* 신규 항목의 소유권 상속은 sudo 로 실행된 업데이트 프로세스가 root 소유로 파일을
|
||||
* 생성하는 것을 방지한다. vendor/ 처럼 cleanDirectory 후 재생성되는 디렉토리 구조
|
||||
* 전체가 기존 부모(= vendor/) 의 소유권을 승계하도록 보장한다.
|
||||
*
|
||||
* @param string $source 소스 디렉토리 경로
|
||||
* @param string $destination 대상 디렉토리 경로
|
||||
* @param \Closure|null $onProgress 진행 콜백
|
||||
@@ -27,10 +32,8 @@ class FilePermissionHelper
|
||||
public static function copyDirectory(string $source, string $destination, ?\Closure $onProgress = null, array $excludes = [], string $relativePath = '', bool $removeOrphans = false): void
|
||||
{
|
||||
if (! File::isDirectory($destination)) {
|
||||
// 신규 디렉토리: 부모 디렉토리의 퍼미션 상속
|
||||
$parentDir = dirname($destination);
|
||||
$parentPerms = File::isDirectory($parentDir) ? (fileperms($parentDir) & 0777) : 0755;
|
||||
File::ensureDirectoryExists($destination, $parentPerms, true);
|
||||
// 신규 디렉토리: 부모 디렉토리의 퍼미션/소유권 상속
|
||||
static::createDirectoryInheritingParent($destination);
|
||||
}
|
||||
// 기존 디렉토리: 퍼미션 건드리지 않음 (그대로 유지)
|
||||
|
||||
@@ -130,7 +133,11 @@ class FilePermissionHelper
|
||||
* 퍼미션과 소유권을 보존하면서 파일을 복사합니다.
|
||||
*
|
||||
* - 기존 파일: 복사 후 원래 퍼미션/소유자/그룹 복원
|
||||
* - 신규 파일: PHP 기본 퍼미션 적용 (umask 기반)
|
||||
* - 신규 파일: 부모 디렉토리의 소유자/그룹 상속 (퍼미션은 PHP 기본 umask)
|
||||
*
|
||||
* 신규 파일에 부모 소유권을 상속시키는 이유는 sudo 로 실행된 업데이트가 root 소유로
|
||||
* 파일을 생성하는 문제를 방지하기 위함이다. vendor/ 내부처럼 cleanDirectory 후
|
||||
* 전량 재생성되는 경로에서 필요하다.
|
||||
*
|
||||
* @param string $source 소스 파일
|
||||
* @param string $destination 대상 파일
|
||||
@@ -138,11 +145,12 @@ class FilePermissionHelper
|
||||
*/
|
||||
public static function copyFile(string $source, string $destination): void
|
||||
{
|
||||
$isExisting = File::exists($destination);
|
||||
$existingPerms = null;
|
||||
$existingOwner = null;
|
||||
$existingGroup = null;
|
||||
|
||||
if (File::exists($destination)) {
|
||||
if ($isExisting) {
|
||||
$existingPerms = fileperms($destination);
|
||||
$existingOwner = fileowner($destination);
|
||||
$existingGroup = filegroup($destination);
|
||||
@@ -151,14 +159,192 @@ class FilePermissionHelper
|
||||
File::ensureDirectoryExists(dirname($destination));
|
||||
File::copy($source, $destination);
|
||||
|
||||
if ($existingPerms !== null) {
|
||||
@chmod($destination, $existingPerms);
|
||||
if ($isExisting) {
|
||||
// 기존 파일: 원래 퍼미션/소유권 복원
|
||||
if ($existingPerms !== null) {
|
||||
@chmod($destination, $existingPerms);
|
||||
}
|
||||
if ($existingOwner !== null && function_exists('chown')) {
|
||||
@chown($destination, $existingOwner);
|
||||
}
|
||||
if ($existingGroup !== null && function_exists('chgrp')) {
|
||||
@chgrp($destination, $existingGroup);
|
||||
}
|
||||
} else {
|
||||
// 신규 파일: 부모 디렉토리의 소유자/그룹 상속
|
||||
static::inheritOwnershipFromParent($destination);
|
||||
}
|
||||
if ($existingOwner !== null && function_exists('chown')) {
|
||||
@chown($destination, $existingOwner);
|
||||
}
|
||||
|
||||
/**
|
||||
* 부모 디렉토리의 퍼미션·소유자·그룹을 상속하여 신규 디렉토리를 생성합니다.
|
||||
*
|
||||
* @param string $path 생성할 디렉토리 경로
|
||||
* @return void
|
||||
*/
|
||||
protected static function createDirectoryInheritingParent(string $path): void
|
||||
{
|
||||
$parentDir = dirname($path);
|
||||
$parentExists = File::isDirectory($parentDir);
|
||||
$parentPerms = $parentExists ? (fileperms($parentDir) & 0777) : 0755;
|
||||
|
||||
File::ensureDirectoryExists($path, $parentPerms, true);
|
||||
|
||||
if ($parentExists) {
|
||||
static::applyOwnership($path, fileowner($parentDir), filegroup($parentDir));
|
||||
}
|
||||
if ($existingGroup !== null && function_exists('chgrp')) {
|
||||
@chgrp($destination, $existingGroup);
|
||||
}
|
||||
|
||||
/**
|
||||
* 부모 디렉토리의 소유자·그룹을 대상 경로에 상속합니다.
|
||||
*
|
||||
* @param string $path 소유권을 상속받을 파일 또는 디렉토리
|
||||
* @return void
|
||||
*/
|
||||
protected static function inheritOwnershipFromParent(string $path): void
|
||||
{
|
||||
$parentDir = dirname($path);
|
||||
if (! File::isDirectory($parentDir)) {
|
||||
return;
|
||||
}
|
||||
|
||||
static::applyOwnership($path, fileowner($parentDir), filegroup($parentDir));
|
||||
}
|
||||
|
||||
/**
|
||||
* 소유자·그룹을 적용합니다. sudo 없이 실행 시 silent fail 로 현행 동작 유지.
|
||||
*
|
||||
* @param string $path 대상 경로
|
||||
* @param int|false $owner fileowner() 반환값 (false 허용)
|
||||
* @param int|false $group filegroup() 반환값 (false 허용)
|
||||
* @return void
|
||||
*/
|
||||
protected static function applyOwnership(string $path, int|false $owner, int|false $group): void
|
||||
{
|
||||
if ($owner !== false && function_exists('chown')) {
|
||||
@chown($path, $owner);
|
||||
}
|
||||
if ($group !== false && function_exists('chgrp')) {
|
||||
@chgrp($path, $group);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 웹서버(www-data 등) 계정의 소유자를 추정합니다.
|
||||
*
|
||||
* Laravel 표준상 웹서버가 쓰기 접근해야 하는 디렉토리(`storage/*`, `bootstrap/cache`)
|
||||
* 를 순회하여 base_path() 소유자와 **다른** 첫 소유자를 "웹서버 계정" 으로 판정한다.
|
||||
* 모든 후보가 base_path() 와 동일하면 대칭 구성으로 보고 base_path() 소유자를 반환.
|
||||
*
|
||||
* 사용 예:
|
||||
* - sudo 실행된 업데이트가 원본 스냅샷을 수집하지 못한 경우의 fallback
|
||||
* - 외부 프로세스(composer 등) 가 root 로 오염시킨 경로의 원본 추정
|
||||
*
|
||||
* @return array{0: int|false, 1: int|false, 2: string} [owner, group, source]
|
||||
*/
|
||||
public static function inferWebServerOwnership(): array
|
||||
{
|
||||
$baseOwner = @fileowner(base_path());
|
||||
$baseGroup = @filegroup(base_path());
|
||||
|
||||
if ($baseOwner === false) {
|
||||
return [false, false, 'none'];
|
||||
}
|
||||
|
||||
$candidates = [
|
||||
'storage/logs',
|
||||
'storage/framework/views',
|
||||
'storage/framework/cache',
|
||||
'storage/app',
|
||||
'storage',
|
||||
'bootstrap/cache',
|
||||
];
|
||||
|
||||
foreach ($candidates as $candidate) {
|
||||
$path = base_path($candidate);
|
||||
if (! File::isDirectory($path)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$owner = @fileowner($path);
|
||||
if ($owner !== false && $owner !== $baseOwner) {
|
||||
return [$owner, @filegroup($path), $candidate];
|
||||
}
|
||||
}
|
||||
|
||||
return [$baseOwner, $baseGroup, 'base_path (대칭 구성)'];
|
||||
}
|
||||
|
||||
/**
|
||||
* 경로와 그 하위 항목의 소유자·그룹을 재귀적으로 복원합니다.
|
||||
*
|
||||
* 현재 소유자가 기준과 이미 일치하면 해당 항목은 스킵. symbolic link 는 링크 자체만
|
||||
* 처리하고 대상은 따라가지 않는다. @chown/@chgrp suppress 로 권한 부족 / chown 미지원
|
||||
* 환경에서도 silent fail.
|
||||
*
|
||||
* @param string $path 대상 경로 (파일 또는 디렉토리)
|
||||
* @param int $owner 기준 소유자 UID
|
||||
* @param int|false $group 기준 그룹 GID (false = 그룹 유지)
|
||||
* @return int 실제 소유권을 변경한 항목 수
|
||||
*/
|
||||
public static function chownRecursive(string $path, int $owner, int|false $group): int
|
||||
{
|
||||
if (! function_exists('chown')) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// 재귀 전체 기간 동안 실패/성공을 집계하고 종료 시 요약 로그를 남긴다.
|
||||
// 경로당 개별 로그는 재귀가 깊어지면 로그 폭주 유발 → 최초 실패 1건만 즉시 로깅.
|
||||
$report = ['changed' => 0, 'failed' => 0, 'first_failure' => null];
|
||||
self::chownRecursiveInternal($path, $owner, $group, $report);
|
||||
|
||||
if ($report['failed'] > 0) {
|
||||
Log::warning('chownRecursive: 부분 실패', [
|
||||
'root' => $path,
|
||||
'owner' => $owner,
|
||||
'group' => $group,
|
||||
'changed' => $report['changed'],
|
||||
'failed' => $report['failed'],
|
||||
'first_failure' => $report['first_failure'],
|
||||
]);
|
||||
}
|
||||
|
||||
return $report['changed'];
|
||||
}
|
||||
|
||||
/**
|
||||
* chownRecursive 의 내부 재귀 구현. 실패 카운터를 참조 전달로 집계한다.
|
||||
*
|
||||
* @param string $path 대상 경로
|
||||
* @param int $owner 기준 소유자 UID
|
||||
* @param int|false $group 기준 그룹 GID
|
||||
* @param array{changed:int, failed:int, first_failure:string|null} $report 집계 구조 (참조)
|
||||
*/
|
||||
private static function chownRecursiveInternal(string $path, int $owner, int|false $group, array &$report): void
|
||||
{
|
||||
$currentOwner = @fileowner($path);
|
||||
if ($currentOwner !== false && $currentOwner !== $owner) {
|
||||
if (@chown($path, $owner)) {
|
||||
$report['changed']++;
|
||||
} else {
|
||||
if ($report['first_failure'] === null) {
|
||||
$report['first_failure'] = $path;
|
||||
Log::warning('chown 최초 실패', ['path' => $path, 'owner' => $owner]);
|
||||
}
|
||||
$report['failed']++;
|
||||
}
|
||||
if ($group !== false && function_exists('chgrp')) {
|
||||
@chgrp($path, $group);
|
||||
}
|
||||
}
|
||||
|
||||
if (! is_dir($path) || is_link($path)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$items = new \FilesystemIterator($path, \FilesystemIterator::SKIP_DOTS);
|
||||
foreach ($items as $item) {
|
||||
self::chownRecursiveInternal($item->getPathname(), $owner, $group, $report);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
<?php
|
||||
|
||||
namespace App\Extension\Helpers;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
/**
|
||||
* 범용 엔티티 동기화 헬퍼.
|
||||
*
|
||||
* 단일 스코프·단일 키 구조의 모듈 내부 도메인 엔티티를 대상으로
|
||||
* upsert + stale cleanup 패턴을 제공합니다.
|
||||
*
|
||||
* 전용 helper (ExtensionMenuSyncHelper, ExtensionRoleSyncHelper,
|
||||
* NotificationSyncHelper) 와의 역할 구분:
|
||||
* - 전용 helper: 다중 모델 관계·피벗 참조 차단 등 도메인 로직 포함
|
||||
* - 본 helper: 단일 테이블 · 단일 unique 키 · 선택적 scope 필터 범용 처리
|
||||
*
|
||||
* 사용 조건: 대상 모델은 `HasUserOverrides` trait 적용 필수.
|
||||
*/
|
||||
class GenericEntitySyncHelper
|
||||
{
|
||||
/**
|
||||
* 엔티티를 동기화합니다 (user_overrides 보존 upsert).
|
||||
*
|
||||
* 내부적으로 `HasUserOverrides::syncOrCreateFromUpgrade` 를 위임 호출합니다.
|
||||
*
|
||||
* @template T of Model
|
||||
* @param class-string<T> $modelClass HasUserOverrides 적용 모델 클래스
|
||||
* @param array<string, mixed> $finder updateOrCreate 의 unique 키 조건
|
||||
* @param array<string, mixed> $attributes 갱신할 속성
|
||||
* @return T 동기화된 모델 인스턴스
|
||||
*/
|
||||
public function sync(string $modelClass, array $finder, array $attributes): Model
|
||||
{
|
||||
return $modelClass::syncOrCreateFromUpgrade($finder, $attributes);
|
||||
}
|
||||
|
||||
/**
|
||||
* 주어진 scope 내에서 currentKeys 에 없는 row 를 삭제합니다 (완전 동기화).
|
||||
*
|
||||
* 정책: `user_overrides` 무관 — seeder/config 에 없는 row 는 삭제.
|
||||
*
|
||||
* @param class-string<Model> $modelClass 대상 모델 클래스
|
||||
* @param array<string, mixed> $scopeFilter 삭제 대상 한정 조건 (예: ['extension_identifier' => 'x', 'type' => 'refund']). 빈 배열이면 전체 테이블 대상.
|
||||
* @param string $keyField 비교 기준 컬럼명 (예: 'code', 'slug', 'type')
|
||||
* @param array<int, string|int> $currentKeys 현재 유효한 키 목록
|
||||
* @return int 삭제된 행 수
|
||||
*/
|
||||
public function cleanupStale(
|
||||
string $modelClass,
|
||||
array $scopeFilter,
|
||||
string $keyField,
|
||||
array $currentKeys,
|
||||
): int {
|
||||
$query = $modelClass::query();
|
||||
foreach ($scopeFilter as $column => $value) {
|
||||
$query->where($column, $value);
|
||||
}
|
||||
$query->whereNotIn($keyField, $currentKeys);
|
||||
|
||||
$targets = $query->get(['id', $keyField]);
|
||||
foreach ($targets as $row) {
|
||||
$row->delete();
|
||||
}
|
||||
|
||||
$count = $targets->count();
|
||||
if ($count > 0) {
|
||||
Log::info('stale 엔티티 정리 완료', [
|
||||
'model' => $modelClass,
|
||||
'scope' => $scopeFilter,
|
||||
'key_field' => $keyField,
|
||||
'deleted' => $count,
|
||||
'keys' => $targets->pluck($keyField)->all(),
|
||||
]);
|
||||
}
|
||||
|
||||
return $count;
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,11 @@
|
||||
|
||||
namespace App\Extension\Helpers;
|
||||
|
||||
use Illuminate\Http\Client\ConnectionException;
|
||||
use Illuminate\Http\Client\PendingRequest;
|
||||
use Illuminate\Http\Client\Response;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
/**
|
||||
@@ -9,6 +14,9 @@ use Illuminate\Support\Facades\Log;
|
||||
*
|
||||
* 코어 업데이트(CoreUpdateService)와 확장 수동 설치(ModuleService, PluginService, TemplateService)
|
||||
* 모두에서 사용할 수 있는 GitHub API 관련 공통 메서드를 제공합니다.
|
||||
*
|
||||
* 모든 원격 HTTP 호출은 Laravel Http 파사드를 사용합니다.
|
||||
* `allow_url_fopen=Off` 환경(공유 호스팅)에서도 정상 동작합니다.
|
||||
*/
|
||||
class GithubHelper
|
||||
{
|
||||
@@ -43,26 +51,20 @@ class GithubHelper
|
||||
*/
|
||||
public static function checkRepoExists(string $owner, string $repo, string $token = ''): bool
|
||||
{
|
||||
$apiUrl = "https://api.github.com/repos/{$owner}/{$repo}";
|
||||
try {
|
||||
$response = static::request($token, 5)
|
||||
->get("https://api.github.com/repos/{$owner}/{$repo}");
|
||||
} catch (ConnectionException $e) {
|
||||
Log::warning('GitHub 저장소 확인 연결 실패', [
|
||||
'owner' => $owner,
|
||||
'repo' => $repo,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
$context = stream_context_create([
|
||||
'http' => [
|
||||
'method' => 'GET',
|
||||
'header' => static::buildHeaders($token),
|
||||
'timeout' => 5,
|
||||
'ignore_errors' => true,
|
||||
],
|
||||
]);
|
||||
|
||||
$response = @file_get_contents($apiUrl, false, $context);
|
||||
|
||||
if ($response === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$statusCode = static::extractStatusCode($http_response_header ?? []);
|
||||
|
||||
return $statusCode === 200;
|
||||
return $response->successful();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -77,30 +79,21 @@ class GithubHelper
|
||||
{
|
||||
$apiUrl = "https://api.github.com/repos/{$owner}/{$repo}/releases/latest";
|
||||
|
||||
$context = stream_context_create([
|
||||
'http' => [
|
||||
'method' => 'GET',
|
||||
'header' => static::buildHeaders($token),
|
||||
'timeout' => 10,
|
||||
'ignore_errors' => true,
|
||||
],
|
||||
]);
|
||||
try {
|
||||
$response = static::request($token, 10)->get($apiUrl);
|
||||
} catch (ConnectionException $e) {
|
||||
Log::warning('GitHub API 연결 실패', ['url' => $apiUrl, 'error' => $e->getMessage()]);
|
||||
|
||||
$response = @file_get_contents($apiUrl, false, $context);
|
||||
|
||||
if ($response === false) {
|
||||
return ['version' => null, 'zipball_url' => null, 'error' => __('common.errors.github_api_failed')];
|
||||
}
|
||||
|
||||
$statusCode = static::extractStatusCode($http_response_header ?? []);
|
||||
|
||||
if ($statusCode !== 200) {
|
||||
if (! $response->successful()) {
|
||||
return ['version' => null, 'zipball_url' => null, 'error' => null];
|
||||
}
|
||||
|
||||
$data = json_decode($response, true);
|
||||
$data = $response->json();
|
||||
|
||||
if (! isset($data['tag_name'])) {
|
||||
if (! is_array($data) || ! isset($data['tag_name'])) {
|
||||
return ['version' => null, 'zipball_url' => null, 'error' => null];
|
||||
}
|
||||
|
||||
@@ -166,7 +159,9 @@ class GithubHelper
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 URL에서 아카이브를 다운로드합니다.
|
||||
* 특정 URL에서 아카이브를 다운로드하여 파일로 저장합니다.
|
||||
*
|
||||
* Http 파사드의 `sink()`를 사용하여 메모리 사용을 최소화합니다.
|
||||
*
|
||||
* @param string $url 다운로드 URL
|
||||
* @param string $savePath 저장할 파일 경로
|
||||
@@ -176,22 +171,100 @@ class GithubHelper
|
||||
*/
|
||||
public static function downloadArchive(string $url, string $savePath, string $token = ''): void
|
||||
{
|
||||
$context = stream_context_create([
|
||||
'http' => [
|
||||
'method' => 'GET',
|
||||
'header' => static::buildHeaders($token),
|
||||
'follow_location' => true,
|
||||
'timeout' => 120,
|
||||
],
|
||||
]);
|
||||
try {
|
||||
$response = static::request($token, 120)
|
||||
->sink($savePath)
|
||||
->get($url);
|
||||
} catch (ConnectionException $e) {
|
||||
// 연결 실패 시에도 sink가 생성했을 수 있는 빈/부분 파일 정리
|
||||
if (File::exists($savePath)) {
|
||||
File::delete($savePath);
|
||||
}
|
||||
|
||||
$content = @file_get_contents($url, false, $context);
|
||||
Log::warning('GitHub 아카이브 다운로드 연결 실패', ['url' => $url, 'error' => $e->getMessage()]);
|
||||
|
||||
if ($content === false) {
|
||||
throw new \RuntimeException(__('common.errors.github_archive_download_failed', ['url' => $url]));
|
||||
}
|
||||
|
||||
\Illuminate\Support\Facades\File::put($savePath, $content);
|
||||
if (! $response->successful()) {
|
||||
// sink로 저장된 미완성 파일 정리
|
||||
if (File::exists($savePath)) {
|
||||
File::delete($savePath);
|
||||
}
|
||||
|
||||
throw new \RuntimeException(__('common.errors.github_archive_download_failed', ['url' => $url]));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 URL에서 아카이브를 다운로드하여 바이너리 내용을 반환합니다.
|
||||
*
|
||||
* `downloadArchive()`와 달리 파일로 저장하지 않고 메모리로 내용을 반환합니다.
|
||||
* 호출부가 바이너리 내용을 직접 처리해야 하는 경우에만 사용하세요.
|
||||
*
|
||||
* @param string $url 다운로드 URL
|
||||
* @param string $token GitHub Personal Access Token
|
||||
* @return string 다운로드된 바이너리 내용
|
||||
*
|
||||
* @throws \RuntimeException 다운로드 실패 시
|
||||
*/
|
||||
public static function downloadArchiveContent(string $url, string $token = ''): string
|
||||
{
|
||||
try {
|
||||
$response = static::request($token, 120)->get($url);
|
||||
} catch (ConnectionException $e) {
|
||||
Log::warning('GitHub 아카이브 다운로드 연결 실패', ['url' => $url, 'error' => $e->getMessage()]);
|
||||
|
||||
throw new \RuntimeException(__('settings.core_update.download_failed', ['version' => basename($url)]));
|
||||
}
|
||||
|
||||
if (! $response->successful()) {
|
||||
throw new \RuntimeException(__('settings.core_update.download_failed', ['version' => basename($url)]));
|
||||
}
|
||||
|
||||
return $response->body();
|
||||
}
|
||||
|
||||
/**
|
||||
* GitHub 아카이브 URL을 해석합니다 (v 접두사 유/무 모두 시도).
|
||||
*
|
||||
* HEAD 요청으로 200/302 응답이 오는 첫 번째 URL을 반환합니다.
|
||||
*
|
||||
* @param string $owner 저장소 소유자
|
||||
* @param string $repo 저장소 이름
|
||||
* @param string $version 버전 태그 (v 접두사 유/무 무관)
|
||||
* @param string $archiveType 아카이브 타입 (zipball/tarball)
|
||||
* @param string $token GitHub Personal Access Token
|
||||
* @return string|null 유효한 아카이브 URL 또는 null
|
||||
*/
|
||||
public static function resolveArchiveUrl(string $owner, string $repo, string $version, string $archiveType = 'zipball', string $token = ''): ?string
|
||||
{
|
||||
$tagVariants = ["v{$version}", $version];
|
||||
|
||||
foreach ($tagVariants as $tag) {
|
||||
// GitHub API 의 `zipball/{tag}` 엔드포인트는 태그가 존재하지 않아도 무조건 302 로
|
||||
// codeload 에 리다이렉트하며, 실제 다운로드 시점에 codeload 에서 404 가 반환되어
|
||||
// 다운로드 파일이 "404: Not Found" 14 byte 텍스트로 저장되는 불가시 실패가 발생한다.
|
||||
// 따라서 아카이브 URL 반환 전에 `git/refs/tags/{tag}` 로 태그 자체의 존재 여부를
|
||||
// 먼저 검증한다 (GitHub API: 존재=200, 부재=404).
|
||||
$tagCheckUrl = "https://api.github.com/repos/{$owner}/{$repo}/git/refs/tags/{$tag}";
|
||||
|
||||
try {
|
||||
$tagResponse = static::request($token, 10)->get($tagCheckUrl);
|
||||
} catch (ConnectionException $e) {
|
||||
Log::info('GitHub 태그 존재 검증 실패', ['url' => $tagCheckUrl, 'error' => $e->getMessage()]);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($tagResponse->status() !== 200) {
|
||||
continue;
|
||||
}
|
||||
|
||||
return "https://api.github.com/repos/{$owner}/{$repo}/{$archiveType}/{$tag}";
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -215,25 +288,14 @@ class GithubHelper
|
||||
foreach ($refs as $tryRef) {
|
||||
$url = "https://raw.githubusercontent.com/{$owner}/{$repo}/{$tryRef}/{$filePath}";
|
||||
|
||||
$context = stream_context_create([
|
||||
'http' => [
|
||||
'method' => 'GET',
|
||||
'header' => static::buildHeaders($token),
|
||||
'timeout' => 10,
|
||||
'ignore_errors' => true,
|
||||
],
|
||||
]);
|
||||
|
||||
$content = @file_get_contents($url, false, $context);
|
||||
|
||||
if ($content === false) {
|
||||
try {
|
||||
$response = static::request($token, 10)->get($url);
|
||||
} catch (ConnectionException $e) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$statusCode = static::extractStatusCode($http_response_header ?? []);
|
||||
|
||||
if ($statusCode === 200) {
|
||||
return $content;
|
||||
if ($response->successful()) {
|
||||
return $response->body();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -241,7 +303,10 @@ class GithubHelper
|
||||
}
|
||||
|
||||
/**
|
||||
* GitHub API 요청용 HTTP 헤더를 생성합니다.
|
||||
* GitHub API 요청용 HTTP 헤더를 생성합니다 (file_get_contents 스트림 컨텍스트 호환).
|
||||
*
|
||||
* 레거시 호출부 호환을 위해 배열 형태의 헤더를 반환합니다.
|
||||
* 신규 코드는 `request()`를 사용하세요.
|
||||
*
|
||||
* @param string $token GitHub Personal Access Token (빈 문자열이면 인증 없음)
|
||||
* @return array HTTP 헤더 배열
|
||||
@@ -261,22 +326,27 @@ class GithubHelper
|
||||
}
|
||||
|
||||
/**
|
||||
* HTTP 응답 헤더에서 상태 코드를 추출합니다.
|
||||
* GitHub API 호출을 위한 표준화된 Http 파사드 PendingRequest를 생성합니다.
|
||||
*
|
||||
* @param array $responseHeaders $http_response_header 배열
|
||||
* @return int HTTP 상태 코드
|
||||
* 모든 원격 HTTP 호출의 단일 진입점입니다. User-Agent, Accept, 토큰 인증,
|
||||
* 타임아웃을 일괄 설정합니다.
|
||||
*
|
||||
* @param string $token GitHub Personal Access Token (빈 문자열이면 인증 없음)
|
||||
* @param int $timeout 읽기 타임아웃(초)
|
||||
*/
|
||||
public static function extractStatusCode(array $responseHeaders): int
|
||||
protected static function request(string $token = '', int $timeout = 10): PendingRequest
|
||||
{
|
||||
$statusCode = 0;
|
||||
$request = Http::withHeaders([
|
||||
'User-Agent' => 'G7',
|
||||
'Accept' => 'application/vnd.github.v3+json',
|
||||
])
|
||||
->timeout($timeout)
|
||||
->connectTimeout(5);
|
||||
|
||||
foreach ($responseHeaders as $header) {
|
||||
if (preg_match('#^HTTP/\S+\s+(\d{3})#', $header, $matches)) {
|
||||
// 리다이렉트 시 마지막 상태 코드를 사용하기 위해 계속 진행
|
||||
$statusCode = (int) $matches[1];
|
||||
}
|
||||
if ($token !== '') {
|
||||
$request = $request->withToken($token);
|
||||
}
|
||||
|
||||
return $statusCode;
|
||||
return $request;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
<?php
|
||||
|
||||
namespace App\Extension\Helpers;
|
||||
|
||||
use App\Models\NotificationDefinition;
|
||||
use App\Models\NotificationTemplate;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
/**
|
||||
* 알림 정의/템플릿 동기화 헬퍼.
|
||||
*
|
||||
* 코어/확장 업그레이드 경로에서 알림 정의·템플릿을 동기화합니다.
|
||||
* ExtensionMenuSyncHelper, ExtensionRoleSyncHelper 와 동일한 Helper 패턴을
|
||||
* 따르며, 내부 upsert 는 `HasUserOverrides::syncOrCreateFromUpgrade` 에 위임하여
|
||||
* trait 공통 API 를 재활용합니다.
|
||||
*
|
||||
* Seeder 는 본 helper 를 호출하는 얇은 진입점이며, 모든 데이터 정합성 로직은
|
||||
* helper 에 집중됩니다.
|
||||
*/
|
||||
class NotificationSyncHelper
|
||||
{
|
||||
/**
|
||||
* 알림 정의를 동기화합니다 (user_overrides 보존 upsert).
|
||||
*
|
||||
* 신규: 생성
|
||||
* 기존: user_overrides 에 없는 필드만 업데이트
|
||||
*
|
||||
* @param array<string, mixed> $data definition 데이터 (type, hook_prefix, extension_type,
|
||||
* extension_identifier, name, description, variables,
|
||||
* channels, hooks, is_active, is_default, templates 포함 가능)
|
||||
* @return NotificationDefinition 동기화된 definition
|
||||
*/
|
||||
public function syncDefinition(array $data): NotificationDefinition
|
||||
{
|
||||
return NotificationDefinition::syncOrCreateFromUpgrade(
|
||||
['type' => $data['type']],
|
||||
[
|
||||
'hook_prefix' => $data['hook_prefix'],
|
||||
'extension_type' => $data['extension_type'],
|
||||
'extension_identifier' => $data['extension_identifier'],
|
||||
'name' => $data['name'],
|
||||
'description' => $data['description'] ?? null,
|
||||
'variables' => $data['variables'] ?? [],
|
||||
'channels' => $data['channels'] ?? ['mail'],
|
||||
'hooks' => $data['hooks'] ?? [],
|
||||
'is_active' => $data['is_active'] ?? true,
|
||||
'is_default' => $data['is_default'] ?? true,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 알림 템플릿을 동기화합니다 (user_overrides 보존 upsert).
|
||||
*
|
||||
* @param int $definitionId 연결된 definition id
|
||||
* @param array<string, mixed> $data template 데이터 (channel, subject, body,
|
||||
* click_url, recipients, is_active, is_default)
|
||||
* @return NotificationTemplate 동기화된 template
|
||||
*/
|
||||
public function syncTemplate(int $definitionId, array $data): NotificationTemplate
|
||||
{
|
||||
return NotificationTemplate::syncOrCreateFromUpgrade(
|
||||
['definition_id' => $definitionId, 'channel' => $data['channel']],
|
||||
[
|
||||
'subject' => $data['subject'] ?? null,
|
||||
'body' => $data['body'],
|
||||
'click_url' => $data['click_url'] ?? null,
|
||||
'recipients' => $data['recipients'] ?? null,
|
||||
'is_active' => $data['is_active'] ?? true,
|
||||
'is_default' => $data['is_default'] ?? true,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* seeder/정의에 없는 stale 알림 정의를 삭제합니다 (완전 동기화 원칙).
|
||||
*
|
||||
* 정책: `user_overrides` 무관 — config/seeder 에 없는 정의는 삭제.
|
||||
* FK cascade 로 연관 `notification_templates` 도 자동 정리됩니다.
|
||||
*
|
||||
* @param string $extensionType 확장 타입: 'core', 'module', 'plugin'
|
||||
* @param string $extensionIdentifier 확장 식별자
|
||||
* @param array<int, string> $currentTypes 현재 유효한 definition type 목록
|
||||
* @return int 삭제된 definition 수
|
||||
*/
|
||||
public function cleanupStaleDefinitions(
|
||||
string $extensionType,
|
||||
string $extensionIdentifier,
|
||||
array $currentTypes,
|
||||
): int {
|
||||
$query = NotificationDefinition::query()
|
||||
->where('extension_type', $extensionType)
|
||||
->where('extension_identifier', $extensionIdentifier)
|
||||
->whereNotIn('type', $currentTypes);
|
||||
|
||||
$targets = $query->get(['id', 'type']);
|
||||
foreach ($targets as $def) {
|
||||
$def->delete();
|
||||
}
|
||||
|
||||
$count = $targets->count();
|
||||
if ($count > 0) {
|
||||
Log::info('stale 알림 정의 정리 완료', [
|
||||
'extension_type' => $extensionType,
|
||||
'extension_identifier' => $extensionIdentifier,
|
||||
'deleted' => $count,
|
||||
'types' => $targets->pluck('type')->all(),
|
||||
]);
|
||||
}
|
||||
|
||||
return $count;
|
||||
}
|
||||
|
||||
/**
|
||||
* 주어진 definition 의 channel 목록 기준으로 stale template 을 삭제합니다.
|
||||
*
|
||||
* 정책: `user_overrides` 무관 — seeder 에 없는 (definition_id, channel)
|
||||
* 조합은 삭제. definition 삭제 시 FK cascade 로 자동 정리되는 경로와 별개로,
|
||||
* definition 은 유지되지만 channel 이 재구성된 경우에 사용됩니다.
|
||||
*
|
||||
* @param int $definitionId
|
||||
* @param array<int, string> $currentChannels 현재 유효한 channel 목록
|
||||
* @return int 삭제된 template 수
|
||||
*/
|
||||
public function cleanupStaleTemplates(int $definitionId, array $currentChannels): int
|
||||
{
|
||||
$query = NotificationTemplate::query()
|
||||
->where('definition_id', $definitionId)
|
||||
->whereNotIn('channel', $currentChannels);
|
||||
|
||||
$targets = $query->get(['id', 'channel']);
|
||||
foreach ($targets as $template) {
|
||||
$template->delete();
|
||||
}
|
||||
|
||||
$count = $targets->count();
|
||||
if ($count > 0) {
|
||||
Log::info('stale 알림 템플릿 정리 완료', [
|
||||
'definition_id' => $definitionId,
|
||||
'deleted' => $count,
|
||||
'channels' => $targets->pluck('channel')->all(),
|
||||
]);
|
||||
}
|
||||
|
||||
return $count;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user