feat(core,ecommerce,ckeditor5,board,admin_basic): 공개 자산 직접 URL(CDN) 서빙 옵트인
StorageInterface::url 의 public 하드코딩을 완화하고 core.storage.filter_url 훅을 신설해, 완전 공개 자산(상품·카테고리·리뷰·에디터 이미지)의 직접 URL 서빙을 옵트인으로 열었다. 미설정 시 기존 스트리밍 100% 보존. 디스크 결정은 확장 개별 설정 > 코어 전역 > 미설정 순이며, 서빙·삭제·이동은 행에 기록된 disk 를 따라 전환 전후 자산이 혼재해도 각자 실제 저장 위치를 향한다. 고아 disk(공급 플러그인 비활성화)는 스트리밍으로 폴백해 500 이 되지 않는다. 공개 이슈 (@lyg-kaban 건의) 대응.
This commit is contained in:
1 parent
37fad55333
commit
057e002ad1
125 files changed
+5913
-203
No files matched your search
@@ -9,6 +9,11 @@
|
||||
### Added
|
||||
|
||||
- 에디터 이미지 업로드에 파일 가공 필터 훅 제공 — 확장에서 업로드 이미지를 저장 전에 변환할 수 있습니다.
|
||||
- 에디터에 올린 이미지를 코어의 공개 자산 스토리지(S3+CDN 등) 디스크에 저장하고 본문에는 CDN 직접 주소로 서빙할 수 있습니다. 에디터 설정의 「공개 자산 디스크」에서 이 플러그인만 다른 디스크를 쓰도록 개별 설정할 수도 있습니다(비우면 코어 설정 따름). 디스크를 바꿔도 기존 이미지는 원래 위치에서 계속 정상 표시됩니다. (#100 @lyg-kaban 님께서 건의해주셨습니다.)
|
||||
|
||||
### Changed
|
||||
|
||||
- 코어 최소 요구 버전을 7.0.7 로 상향했습니다.
|
||||
|
||||
## [1.0.1] - 2026-08-10
|
||||
|
||||
|
||||
@@ -7,12 +7,14 @@
|
||||
"imageUpload": true,
|
||||
"imageMaxSizeMb": 2,
|
||||
"editorHeight": 400,
|
||||
"toolbar": "standard"
|
||||
"toolbar": "standard",
|
||||
"public_asset_disk": ""
|
||||
},
|
||||
"frontend_schema": {
|
||||
"imageUpload": { "expose": true },
|
||||
"imageMaxSizeMb": { "expose": true },
|
||||
"editorHeight": { "expose": true },
|
||||
"toolbar": { "expose": true }
|
||||
"toolbar": { "expose": true },
|
||||
"public_asset_disk": { "expose": false }
|
||||
}
|
||||
}
|
||||
@@ -52,7 +52,7 @@ _이 엔드포인트는 표준 envelope(`success`/`message`/`data`)를 사용하
|
||||
|
||||
| 필드 | 타입 | 실측 예시값 | 용도/설명 |
|
||||
| --- | --- | --- | --- |
|
||||
| url | string | `/api/plugins/sirsoft-ckeditor5/images/a1b2c3d4e5f6` | 업로드된 이미지의 서빙 URL. 모델 접근자 `download_url` 이 생성하며 `/api/plugins/sirsoft-ckeditor5/images/{hash}` (hash = 12자리 hex) 형식이다. CKEditor 가 이 값을 그대로 `<img src>` 에 삽입한다. |
|
||||
| url | string | `/api/plugins/sirsoft-ckeditor5/images/a1b2c3d4e5f6` | 업로드된 이미지의 서빙 URL. 모델 접근자 `download_url` 이 생성한다. 기본(스트리밍)은 `/api/plugins/sirsoft-ckeditor5/images/{hash}` (hash = 12자리 hex) 형식이고, 공개 자산 디스크(플러그인 설정 `public_asset_disk` 또는 코어 전역 설정)가 URL 지원 디스크로 설정되어 있으면 그 디스크의 직접 URL(예: `https://cdn.example.com/sirsoft-ckeditor5/images/...`)이 반환된다. CKEditor 가 이 값을 그대로 `<img src>` 에 삽입한다. |
|
||||
|
||||
실패 시에는 최상위 `error.message` 만 반환합니다 (아래 에러 응답 표 참조).
|
||||
|
||||
@@ -87,7 +87,7 @@ CKEditor5 의 SimpleUploadAdapter 가 에디터에 드롭/붙여넣은 이미지
|
||||
이 규격은 우리 코드가 정한 것이 아니다 — 응답을 파싱하는 주체가 CDN 으로 로드되는 CKEditor5 43.3.1 의 `SimpleUploadAdapter`(`resources/js/handlers/initEditor.ts` 의 `editorConfig.simpleUpload`)이므로 파싱 규약을 바꿀 수 없다. 컨트롤러의 각 응답 지점에는 이 사유로 `audit:allow response-helper-bypass` 를 명시해 두었으니, envelope 로 감싸는 "수정" 을 하면 에디터의 이미지 업로드가 조용히 실패한다.
|
||||
- **요청 파라미터**: multipart body 의 `upload` 필드(이미지 파일 1개). 허용 MIME 은 `jpeg,jpg,png,gif,webp`, 최대 크기는 플러그인 설정 `imageMaxSizeMb`(기본 2MB) 로 동적 결정된다. 검증 실패도 CKEditor 규격(`{"error":{"message":...}}`, HTTP 422)으로 응답한다.
|
||||
- **선택 권한 게이트**: query 파라미터 `permission` 이 주어지면, 현재 사용자가 해당 권한을 갖지 못한 경우 403 `{"error":{"message":...}}`. 에디터를 임베드하는 화면이 업로드 권한을 세분화할 때 사용한다.
|
||||
- 업로드 성공 시 반환하는 `url` 은 공개 서빙 엔드포인트(`GET /images/{hash}`)의 절대 URL 이다.
|
||||
- 업로드 성공 시 반환하는 `url` 은 기본적으로 공개 서빙 엔드포인트(`GET /images/{hash}`)의 절대 URL 이다. 단, 공개 자산 디스크(플러그인 설정 `public_asset_disk` > 코어 전역 `drivers.public_asset_disk`)가 직접 URL 을 지원하는 디스크(public / URL 이 설정된 s3 등)로 지정되어 있으면 스트리밍 경로 대신 그 디스크의 직접 URL(CDN)이 반환된다. 디스크 미설정('none' 포함)·URL 미지원 디스크·`core.storage.filter_url` 훅 차단 시에는 기존 스트리밍 경로로 폴백한다.
|
||||
|
||||
**응답 예시** (성공 — CKEditor 규격, envelope 아님)
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
"ko": "CKEditor 5를 이용한 WYSIWYG 에디터 플러그인입니다. 플러그인 설치만으로 기존 HtmlEditor가 교체됩니다.",
|
||||
"en": "WYSIWYG editor plugin using CKEditor 5. Installing this plugin replaces the default HtmlEditor."
|
||||
},
|
||||
"g7_version": ">=7.0.6",
|
||||
"g7_version": ">=7.0.7",
|
||||
"dependencies": {
|
||||
"modules": {},
|
||||
"plugins": {}
|
||||
|
||||
@@ -73,9 +73,62 @@ class Plugin extends AbstractPlugin
|
||||
],
|
||||
'required' => false,
|
||||
],
|
||||
// 선택지가 코어 카탈로그 + 플러그인 훅 등록 디스크로 동적이라 enum 불가 — string.
|
||||
// 존재하지 않는 디스크 값은 resolvePublicAssetDisk() 가 스트리밍으로 안전 폴백한다.
|
||||
'public_asset_disk' => [
|
||||
'type' => 'string',
|
||||
'max' => 100,
|
||||
'default' => '',
|
||||
'label' => [
|
||||
'ko' => '공개 자산 디스크',
|
||||
'en' => 'Public Asset Disk',
|
||||
],
|
||||
'hint' => [
|
||||
'ko' => '이 플러그인만 다른 디스크를 쓰려면 선택합니다. 비우면 코어 공개 자산 디스크 설정을 따릅니다.',
|
||||
'en' => 'Select to use a different disk for this plugin only. Leave empty to follow the core public asset disk setting.',
|
||||
],
|
||||
'required' => false,
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 완전 공개 자산 스토리지 카테고리 목록
|
||||
*
|
||||
* 이 카테고리들만 공개 자산 디스크 설정을 따른다. 권한 검사가 걸린 자산은
|
||||
* 직접 URL 이 권한을 우회하므로 포함하지 않는다. 에디터가 이미지 외의
|
||||
* 공개 자산 업로드를 지원하게 되면 여기에만 카테고리를 추가하면 된다.
|
||||
*
|
||||
* @var list<string>
|
||||
*/
|
||||
private const PUBLIC_ASSET_CATEGORIES = ['images'];
|
||||
|
||||
/**
|
||||
* 카테고리별 스토리지 디스크 이름 반환
|
||||
*
|
||||
* 완전 공개 자산 카테고리만 공개 자산 디스크(플러그인 설정 public_asset_disk >
|
||||
* 코어 전역 core.storage.public_asset_disk)를 따르고, 설정 등 나머지 카테고리는
|
||||
* 기본 디스크를 유지합니다. 미설정/고아 디스크는 기본 디스크로 폴백해 기존
|
||||
* 스트리밍 동작을 보존합니다.
|
||||
*
|
||||
* 플러그인 설정 조회는 공개 자산 카테고리에서만 수행합니다 — 'settings' 카테고리에서
|
||||
* 조회하면 설정 로드와 재귀 고리가 생깁니다 (AbstractPlugin 주석 참조).
|
||||
*
|
||||
* @param string $category 카테고리
|
||||
* @return string 디스크 이름
|
||||
*/
|
||||
public function getStorageDiskFor(string $category): string
|
||||
{
|
||||
if (! in_array($category, self::PUBLIC_ASSET_CATEGORIES, true)) {
|
||||
return $this->getStorageDisk();
|
||||
}
|
||||
|
||||
$override = plugin_setting('sirsoft-ckeditor5', 'public_asset_disk', '');
|
||||
|
||||
return $this->resolvePublicAssetDisk(is_string($override) ? $override : '')
|
||||
?? $this->getStorageDisk();
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인이 관리하는 동적 테이블 목록 반환
|
||||
*
|
||||
|
||||
+248
@@ -0,0 +1,248 @@
|
||||
/**
|
||||
* CKEditor5 설정 화면 — 공개 자산 디스크 필드 테스트 (공개#100)
|
||||
*
|
||||
* @description
|
||||
* 플러그인 오버라이드 필드는 저장 키(public_asset_disk)와 **플러그인 설정 응답에
|
||||
* 서버 부착되는** 카탈로그(available_public_asset_disks)를 바인딩해야 한다.
|
||||
* 별도 코어 설정 API(/api/admin/settings, core.settings.read)를 교차 조회하면
|
||||
* 화면 권한(core.plugins.read)과 표면이 갈려 커스텀 역할에서 카탈로그가 조용히
|
||||
* 빈다 — 단일 표면 계약을 고정한다. 설정 스키마(getSettingsSchema)에 같은 키가
|
||||
* 없으면 저장 검증이 규칙을 만들지 않아 값이 조용히 버려진다 — 세 지점을 대조한다.
|
||||
*
|
||||
* 계약 단언에 더해, 실제 필드 서브트리를 createLayoutTest 로 렌더링해
|
||||
* 옵션 계산식($t 선두 + $localized 매핑)까지 검증한다.
|
||||
*
|
||||
* @effects settings_catalog_includes_plugin_registered_disks
|
||||
*/
|
||||
|
||||
import React from 'react';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { describe, expect, it, beforeEach, afterEach } from 'vitest';
|
||||
import { createLayoutTest } from '@core/template-engine/__tests__/utils/layoutTestUtils';
|
||||
import { ComponentRegistry } from '@core/template-engine/ComponentRegistry';
|
||||
|
||||
import pluginSettings from '../../../layouts/admin/plugin_settings.json';
|
||||
|
||||
// ─── 테스트용 컴포넌트 ───
|
||||
|
||||
const TestDiv: React.FC<{ className?: string; children?: React.ReactNode; 'data-testid'?: string }> =
|
||||
({ className, children, 'data-testid': testId }) => (
|
||||
<div className={className} data-testid={testId}>{children}</div>
|
||||
);
|
||||
|
||||
const TestLabel: React.FC<{ className?: string; children?: React.ReactNode; text?: string }> =
|
||||
({ className, children, text }) => <label className={className}>{children || text}</label>;
|
||||
|
||||
const TestP: React.FC<{ className?: string; children?: React.ReactNode; text?: string }> =
|
||||
({ className, children, text }) => <p className={className}>{children || text}</p>;
|
||||
|
||||
const TestSelect: React.FC<{
|
||||
name?: string; value?: string; className?: string; options?: any[];
|
||||
onChange?: (e: React.ChangeEvent<HTMLSelectElement>) => void;
|
||||
}> = ({ name, value, className, options, onChange }) => (
|
||||
<select data-name={name} value={value} className={className} onChange={onChange}>
|
||||
{options?.map((o) => <option key={String(o.value)} value={o.value}>{o.label}</option>)}
|
||||
</select>
|
||||
);
|
||||
|
||||
// 렌더러가 컴포넌트 목록을 Fragment 로 감싸므로 반드시 등록해야 한다.
|
||||
const TestFragment: React.FC<{ children?: React.ReactNode }> = ({ children }) => <>{children}</>;
|
||||
|
||||
function setupTestRegistry(): ComponentRegistry {
|
||||
const registry = ComponentRegistry.getInstance();
|
||||
(registry as any).registry = {
|
||||
Div: { component: TestDiv, metadata: { name: 'Div', type: 'basic' } },
|
||||
Label: { component: TestLabel, metadata: { name: 'Label', type: 'basic' } },
|
||||
P: { component: TestP, metadata: { name: 'P', type: 'basic' } },
|
||||
Select: { component: TestSelect, metadata: { name: 'Select', type: 'composite' } },
|
||||
Fragment: { component: TestFragment, metadata: { name: 'Fragment', type: 'layout' } },
|
||||
};
|
||||
return registry;
|
||||
}
|
||||
|
||||
// ─── 다국어 (공개 자산 디스크 필드가 쓰는 키) ───
|
||||
|
||||
const translations = {
|
||||
'sirsoft-ckeditor5': {
|
||||
settings: {
|
||||
fields: {
|
||||
public_asset_disk: {
|
||||
label: '공개 자산 디스크',
|
||||
hint: '에디터 이미지 서빙 디스크를 오버라이드합니다.',
|
||||
follow_core: '코어 설정 따름',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* 플러그인 루트(plugin.json 기준)를 위로 훑어 찾는다.
|
||||
*
|
||||
* @returns 플러그인 루트 절대경로
|
||||
*/
|
||||
function pluginRoot(): string {
|
||||
let current = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
for (let depth = 0; depth < 10; depth++) {
|
||||
if (fs.existsSync(path.join(current, 'plugin.json'))) {
|
||||
return current;
|
||||
}
|
||||
current = path.dirname(current);
|
||||
}
|
||||
|
||||
throw new Error('plugin.json 을 가진 플러그인 루트를 찾지 못했습니다.');
|
||||
}
|
||||
|
||||
/**
|
||||
* 레이아웃 트리에서 조건을 만족하는 첫 노드를 찾는다 (slots 포함).
|
||||
*
|
||||
* @param node 탐색 시작 노드
|
||||
* @param predicate 노드 판정 함수
|
||||
* @returns 찾은 노드 또는 null
|
||||
*/
|
||||
function findNode(node: any, predicate: (n: any) => boolean): any {
|
||||
if (!node || typeof node !== 'object') return null;
|
||||
if (predicate(node)) return node;
|
||||
|
||||
const childGroups = [node.children ?? [], ...(node.slots ? Object.values(node.slots) : [])];
|
||||
for (const group of childGroups) {
|
||||
for (const child of group as any[]) {
|
||||
const found = findNode(child, predicate);
|
||||
if (found) return found;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
// 실제 필드 서브트리를 그대로 렌더 대상으로 쓴다 — 사본 표현식이 아닌 배포 JSON 자체가 SSoT.
|
||||
const publicAssetField = findNode(
|
||||
pluginSettings,
|
||||
(n) => n.id === 'field_public_asset_disk',
|
||||
);
|
||||
|
||||
const CATALOG = [
|
||||
{ id: 'none', label: { ko: '사용 안 함 (스트리밍)', en: 'None (streaming)' } },
|
||||
{ id: 'fake_cdn', label: { ko: '가짜 CDN', en: 'Fake CDN' } },
|
||||
];
|
||||
|
||||
describe('CKEditor5 공개 자산 디스크 필드 — 계약', () => {
|
||||
it('코어 설정 API 교차 조회 데이터소스가 없다 (권한 표면 단일화)', () => {
|
||||
const dataSources = (pluginSettings as any).data_sources;
|
||||
|
||||
// 존재 앵커 먼저 — data_sources 가 비어 있으면 아래 부재 단언이 공허하게 통과한다
|
||||
expect(dataSources.find((d: any) => d.id === 'settings')).toBeDefined();
|
||||
|
||||
// 카탈로그는 플러그인 설정 응답에 서버 부착 — 화면 권한(core.plugins.read)과
|
||||
// 다른 권한(core.settings.read)을 요구하는 교차 조회가 남아 있으면 안 된다
|
||||
expect(dataSources.find((d: any) => d.endpoint === '/api/admin/settings')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('Select 가 저장 키와 설정 응답 부착 카탈로그를 바인딩한다', () => {
|
||||
const select = findNode(
|
||||
publicAssetField,
|
||||
(n) => n.name === 'Select' && n.props?.name === 'public_asset_disk',
|
||||
);
|
||||
|
||||
expect(select).not.toBeNull();
|
||||
expect(select.props.options).toContain('_local.form?.available_public_asset_disks');
|
||||
expect(select.props.options).toContain('follow_core');
|
||||
});
|
||||
|
||||
it('설정 스키마(getSettingsSchema)가 같은 키를 선언한다 (저장 whitelist)', () => {
|
||||
const pluginSource = fs.readFileSync(path.join(pluginRoot(), 'plugin.php'), 'utf-8');
|
||||
const defaults = JSON.parse(
|
||||
fs.readFileSync(path.join(pluginRoot(), 'config/settings/defaults.json'), 'utf-8'),
|
||||
);
|
||||
|
||||
expect(pluginSource).toContain("'public_asset_disk' => [");
|
||||
expect(defaults.defaults).toHaveProperty('public_asset_disk');
|
||||
});
|
||||
});
|
||||
|
||||
describe('CKEditor5 공개 자산 디스크 필드 — 렌더링', () => {
|
||||
let registry: ComponentRegistry;
|
||||
let testUtils: ReturnType<typeof createLayoutTest> | null = null;
|
||||
|
||||
beforeEach(() => {
|
||||
registry = setupTestRegistry();
|
||||
// 표현식 내 $t() 는 컨텍스트에 $templateId 가 없으면 __templateApp.getConfig()
|
||||
// 로 회수한다(engine-v1.38.2 폴백). layoutTestUtils 는 이를 세팅하지 않으므로
|
||||
// 테스트에서 동일 폴백 경로를 제공해야 옵션 계산식의 $t() 가 해석된다.
|
||||
(window as any).__templateApp = {
|
||||
getConfig: () => ({ templateId: 'test-template', locale: 'ko' }),
|
||||
};
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
testUtils?.cleanup();
|
||||
testUtils = null;
|
||||
(registry as any).registry = {};
|
||||
delete (window as any).__templateApp;
|
||||
});
|
||||
|
||||
/**
|
||||
* 필드 렌더링용 테스트 유틸을 생성한다.
|
||||
*
|
||||
* @returns createLayoutTest 유틸
|
||||
*/
|
||||
function makeUtils() {
|
||||
return createLayoutTest(
|
||||
{
|
||||
version: '1.0.0',
|
||||
layout_name: 'test_ckeditor5_public_asset_field',
|
||||
components: [publicAssetField],
|
||||
} as any,
|
||||
{
|
||||
auth: {
|
||||
isAuthenticated: true,
|
||||
user: { id: 1, name: 'Admin', role: 'super_admin' },
|
||||
authType: 'admin',
|
||||
},
|
||||
translations,
|
||||
locale: 'ko',
|
||||
initialState: {
|
||||
_local: {
|
||||
// 플러그인 설정 GET 응답(initLocal: form)에 서버 부착되는 형태
|
||||
form: {
|
||||
public_asset_disk: '',
|
||||
available_public_asset_disks: CATALOG,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
it('라벨/힌트가 다국어 해석되어 렌더된다', async () => {
|
||||
testUtils = makeUtils();
|
||||
const { container } = await testUtils.render();
|
||||
|
||||
expect(container.querySelector('label.form-label')?.textContent ?? '').toContain(
|
||||
'공개 자산 디스크',
|
||||
);
|
||||
expect(container.querySelector('p.form-hint')?.textContent ?? '').toContain(
|
||||
'에디터 이미지 서빙 디스크를 오버라이드합니다.',
|
||||
);
|
||||
expect(() => testUtils!.assertNoValidationErrors()).not.toThrow();
|
||||
});
|
||||
|
||||
it('설정 응답 부착 카탈로그가 옵션으로 계산된다 (코어 따름 선두 + $localized 매핑)', async () => {
|
||||
testUtils = makeUtils();
|
||||
const { container } = await testUtils.render();
|
||||
|
||||
const select = container.querySelector('select[data-name="public_asset_disk"]');
|
||||
expect(select).not.toBeNull();
|
||||
|
||||
const options = Array.from(select!.querySelectorAll('option'));
|
||||
expect(options.map((o) => o.getAttribute('value'))).toEqual(['', 'none', 'fake_cdn']);
|
||||
expect(options.map((o) => o.textContent)).toEqual([
|
||||
'코어 설정 따름',
|
||||
'사용 안 함 (스트리밍)',
|
||||
'가짜 CDN',
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -29,6 +29,11 @@
|
||||
"label": "Max Image Size (MB)",
|
||||
"hint": "Maximum allowed size for uploaded images. (1 ~ 10 MB)"
|
||||
},
|
||||
"public_asset_disk": {
|
||||
"label": "Public Asset Disk",
|
||||
"hint": "Select to use a different disk for this plugin only. Leave empty to follow the core public asset disk setting.",
|
||||
"follow_core": "Follow core setting"
|
||||
},
|
||||
"editor_height": {
|
||||
"label": "Editor Height (px)",
|
||||
"hint": "Set the minimum height of the editor in pixels. (200 ~ 2000 px)"
|
||||
|
||||
@@ -29,6 +29,11 @@
|
||||
"label": "최대 이미지 크기 (MB)",
|
||||
"hint": "업로드 가능한 이미지의 최대 크기입니다. (1 ~ 10 MB)"
|
||||
},
|
||||
"public_asset_disk": {
|
||||
"label": "공개 자산 디스크",
|
||||
"hint": "이 플러그인만 다른 디스크를 쓰려면 선택합니다. 비우면 코어 공개 자산 디스크 설정을 따릅니다.",
|
||||
"follow_core": "코어 설정 따름"
|
||||
},
|
||||
"editor_height": {
|
||||
"label": "에디터 높이 (px)",
|
||||
"hint": "에디터의 최소 높이를 픽셀 단위로 설정합니다. (200 ~ 2000 px)"
|
||||
|
||||
@@ -380,6 +380,49 @@
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "field_public_asset_disk",
|
||||
"type": "basic",
|
||||
"name": "Div",
|
||||
"props": { "className": "section-heading-md" },
|
||||
"children": [
|
||||
{
|
||||
"type": "basic",
|
||||
"name": "Div",
|
||||
"props": { "className": "lg:col-span-1" },
|
||||
"children": [
|
||||
{
|
||||
"type": "basic",
|
||||
"name": "Label",
|
||||
"props": { "className": "form-label" },
|
||||
"text": "$t:sirsoft-ckeditor5.settings.fields.public_asset_disk.label"
|
||||
},
|
||||
{
|
||||
"type": "basic",
|
||||
"name": "P",
|
||||
"props": { "className": "form-hint" },
|
||||
"text": "$t:sirsoft-ckeditor5.settings.fields.public_asset_disk.hint"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "basic",
|
||||
"name": "Div",
|
||||
"props": { "className": "lg:col-span-2" },
|
||||
"children": [
|
||||
{
|
||||
"type": "composite",
|
||||
"name": "Select",
|
||||
"props": {
|
||||
"name": "public_asset_disk",
|
||||
"className": "w-full",
|
||||
"options": "{{[{value: '', label: $t('sirsoft-ckeditor5.settings.fields.public_asset_disk.follow_core')}].concat((_local.form?.available_public_asset_disks ?? []).map(d => ({value: d.id, label: $localized(d.label)})))}}"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -2,9 +2,12 @@
|
||||
|
||||
namespace Plugins\Sirsoft\Ckeditor5\Models;
|
||||
|
||||
use App\Contracts\Extension\StorageInterface;
|
||||
use App\Extension\Storage\PluginStorageDriver;
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Carbon;
|
||||
|
||||
/**
|
||||
* CKEditor5 이미지 업로드 기록 모델
|
||||
@@ -17,8 +20,8 @@ use App\Models\User;
|
||||
* @property int $file_size 파일 크기 (bytes)
|
||||
* @property string $mime_type MIME 타입
|
||||
* @property int|null $uploaded_by 업로드 사용자 ID
|
||||
* @property \Illuminate\Support\Carbon $created_at
|
||||
* @property \Illuminate\Support\Carbon $updated_at
|
||||
* @property Carbon $created_at
|
||||
* @property Carbon $updated_at
|
||||
* @property-read string $download_url 이미지 서빙 URL
|
||||
*/
|
||||
class Ckeditor5ImageUpload extends Model
|
||||
@@ -74,13 +77,59 @@ class Ckeditor5ImageUpload extends Model
|
||||
}
|
||||
|
||||
/**
|
||||
* 이미지 서빙 URL 반환 (API 라우트 경유)
|
||||
* 행 disk 별 스토리지 드라이버 캐시 (직렬화 루프 대응 memoize)
|
||||
*
|
||||
* @return string 이미지 서빙 URL
|
||||
* @var array<string, StorageInterface>
|
||||
*/
|
||||
private static array $storageByDisk = [];
|
||||
|
||||
/**
|
||||
* 이미지 서빙 URL 반환 — 직접 URL(CDN) 우선, 불가 시 API 라우트 폴백
|
||||
*
|
||||
* 행에 기록된 storage_disk 로 직접 URL 생성을 시도하고, 불가하면(로컬 디스크,
|
||||
* url 미설정 디스크, 훅 차단 등) 기존 API 서빙 경로로 폴백합니다.
|
||||
*
|
||||
* @return string 이미지 URL
|
||||
*/
|
||||
public function getDownloadUrlAttribute(): string
|
||||
{
|
||||
return '/api/plugins/sirsoft-ckeditor5/images/'.$this->hash;
|
||||
return $this->resolveDirectUrl() ?? '/api/plugins/sirsoft-ckeditor5/images/'.$this->hash;
|
||||
}
|
||||
|
||||
/**
|
||||
* 행 storage_disk 기준 직접 URL 해석을 시도합니다.
|
||||
*
|
||||
* file_path 는 카테고리 prefix 를 포함하므로("images/..." 또는 "ckeditor5/..." 등
|
||||
* 외부 생성 행 포함) 첫 세그먼트를 카테고리로 분해하는 일반형으로 처리합니다.
|
||||
*
|
||||
* @return string|null 직접 URL (불가하면 null)
|
||||
*/
|
||||
protected function resolveDirectUrl(): ?string
|
||||
{
|
||||
$disk = (string) ($this->storage_disk ?? '');
|
||||
$filePath = (string) ($this->file_path ?? '');
|
||||
|
||||
if ($disk === '' || $filePath === '' || ! str_contains($filePath, '/')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
[$category, $relativePath] = explode('/', $filePath, 2);
|
||||
|
||||
if ($category === '' || $relativePath === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
$storage = self::$storageByDisk[$disk] ??= new PluginStorageDriver('sirsoft-ckeditor5', $disk);
|
||||
|
||||
return $storage->url($category, $relativePath);
|
||||
}
|
||||
|
||||
/**
|
||||
* 행 disk 드라이버 memoize 캐시를 비웁니다 (테스트 격리용).
|
||||
*/
|
||||
public static function flushStorageCache(): void
|
||||
{
|
||||
self::$storageByDisk = [];
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -23,7 +23,19 @@ class Ckeditor5ServiceProvider extends BasePluginServiceProvider
|
||||
];
|
||||
|
||||
protected array $storageServices = [
|
||||
ImageUploadService::class,
|
||||
ImageServeService::class,
|
||||
];
|
||||
|
||||
/**
|
||||
* 카테고리별 StorageInterface가 필요한 서비스 매핑 (클래스 ⇒ 카테고리)
|
||||
*
|
||||
* 업로드 서비스는 getStorageDiskFor('images') 가 결정한 디스크(공개 자산 디스크
|
||||
* 설정 반영)를 주입받아, put/getDisk() 행 기록이 자동으로 카테고리 디스크를 따릅니다.
|
||||
* 서빙 서비스는 행 storage_disk 기준 withDisk() 를 쓰므로 기본 주입을 유지합니다.
|
||||
*
|
||||
* @var array<class-string, string>
|
||||
*/
|
||||
protected array $storageCategoryServices = [
|
||||
ImageUploadService::class => 'images',
|
||||
];
|
||||
}
|
||||
@@ -43,27 +43,41 @@ class ImageServeService
|
||||
*/
|
||||
public function serve(Ckeditor5ImageUpload $image): ?StreamedResponse
|
||||
{
|
||||
// file_path 형태: "images/2026/04/06/{uuid}.jpg"
|
||||
// PluginStorageDriver::response(category, path) 에서 category = 'images'
|
||||
$category = 'images';
|
||||
$relativePath = substr($image->file_path, strlen($category) + 1);
|
||||
// file_path 형태: "images/2026/04/06/{uuid}.jpg" (외부 생성 행은 "ckeditor5/..." 등)
|
||||
// 첫 세그먼트 = 카테고리 일반형으로 분해 — PluginStorageDriver::response(category, path)
|
||||
[$category, $relativePath] = array_pad(explode('/', $image->file_path, 2), 2, '');
|
||||
|
||||
$response = $this->storage->response(
|
||||
if ($category === '' || $relativePath === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
// 행에 기록된 disk 기준 서빙 — 디스크 전환 이전 행도 실제 저장 위치를 향한다.
|
||||
// 단 고아 disk(디스크를 제공하던 플러그인 비활성화로 config 에서 사라진 경우)는
|
||||
// 미등록 disk 로 withDisk 를 만들면 response 가 InvalidArgumentException 을 던져
|
||||
// 서빙이 500 이 되므로, 존재 검증 후 주입 스토리지로 폴백한다.
|
||||
$rowDisk = (string) ($image->storage_disk ?? '');
|
||||
$useRowDisk = $rowDisk !== ''
|
||||
&& $rowDisk !== $this->storage->getDisk()
|
||||
&& config("filesystems.disks.{$rowDisk}") !== null;
|
||||
|
||||
$storage = $useRowDisk ? $this->storage->withDisk($rowDisk) : $this->storage;
|
||||
|
||||
$response = $storage->response(
|
||||
$category,
|
||||
$relativePath,
|
||||
$image->original_name,
|
||||
[
|
||||
'Content-Type' => $image->mime_type,
|
||||
'Content-Type' => $image->mime_type,
|
||||
'Cache-Control' => 'public, max-age=31536000',
|
||||
]
|
||||
);
|
||||
|
||||
if (! $response) {
|
||||
Log::error('CKEditor5 이미지 스토리지에 없음', [
|
||||
'image_id' => $image->id,
|
||||
'hash' => $image->hash,
|
||||
'image_id' => $image->id,
|
||||
'hash' => $image->hash,
|
||||
'file_path' => $image->file_path,
|
||||
'disk' => $image->storage_disk,
|
||||
'disk' => $image->storage_disk,
|
||||
]);
|
||||
|
||||
return null;
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
<?php
|
||||
|
||||
namespace Plugins\Sirsoft\Ckeditor5\Tests\Unit;
|
||||
|
||||
use App\Extension\HookManager;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use Plugins\Sirsoft\Ckeditor5\Models\Ckeditor5ImageUpload;
|
||||
use Plugins\Sirsoft\Ckeditor5\Tests\PluginTestCase;
|
||||
|
||||
/**
|
||||
* Ckeditor5ImageUpload download_url(직접 URL/폴백) 단위 테스트
|
||||
*
|
||||
* file_path 의 첫 세그먼트=카테고리 일반형 분해와 행 storage_disk 기준
|
||||
* 직접 URL/스트리밍 폴백을 검증합니다.
|
||||
*/
|
||||
class Ckeditor5ImageUploadUrlTest extends PluginTestCase
|
||||
{
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
Config::set('filesystems.disks.fake_cdn', [
|
||||
'driver' => 'local',
|
||||
'root' => storage_path('framework/testing/disks/fake_cdn'),
|
||||
'url' => 'https://cdn.test/assets',
|
||||
]);
|
||||
Ckeditor5ImageUpload::flushStorageCache();
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
Ckeditor5ImageUpload::flushStorageCache();
|
||||
HookManager::resetAll();
|
||||
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/**
|
||||
* @scenario consumer=editor, disk_setting=public, e2e=ecommerce_settings_field, hook=unregistered, override=follow_core, row_state=legacy_local_row
|
||||
*
|
||||
* @effects download_url_falls_back_to_api_path_when_direct_unavailable
|
||||
*/
|
||||
#[Test]
|
||||
public function it_falls_back_to_api_url_for_plugins_disk_row(): void
|
||||
{
|
||||
$image = new Ckeditor5ImageUpload([
|
||||
'hash' => 'aaaabbbbcccc',
|
||||
'file_path' => 'images/2026/01/01/a.jpg',
|
||||
'storage_disk' => 'plugins',
|
||||
]);
|
||||
|
||||
$this->assertSame(
|
||||
'/api/plugins/sirsoft-ckeditor5/images/aaaabbbbcccc',
|
||||
$image->download_url
|
||||
);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_returns_direct_url_for_cdn_disk_row(): void
|
||||
{
|
||||
$image = new Ckeditor5ImageUpload([
|
||||
'hash' => 'aaaabbbbcccc',
|
||||
'file_path' => 'images/2026/01/01/a.jpg',
|
||||
'storage_disk' => 'fake_cdn',
|
||||
]);
|
||||
|
||||
$this->assertSame(
|
||||
'https://cdn.test/assets/sirsoft-ckeditor5/images/2026/01/01/a.jpg',
|
||||
$image->download_url
|
||||
);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_decomposes_non_images_prefix_generically(): void
|
||||
{
|
||||
// ApiDocSampleService 등 외부 생성 행 — 첫 세그먼트=카테고리 일반형
|
||||
$image = new Ckeditor5ImageUpload([
|
||||
'hash' => 'aaaabbbbcccc',
|
||||
'file_path' => 'ckeditor5/apidoc-sample.png',
|
||||
'storage_disk' => 'fake_cdn',
|
||||
]);
|
||||
|
||||
$this->assertSame(
|
||||
'https://cdn.test/assets/sirsoft-ckeditor5/ckeditor5/apidoc-sample.png',
|
||||
$image->download_url
|
||||
);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function it_falls_back_when_file_path_has_no_prefix(): void
|
||||
{
|
||||
$image = new Ckeditor5ImageUpload([
|
||||
'hash' => 'aaaabbbbcccc',
|
||||
'file_path' => 'orphan.png',
|
||||
'storage_disk' => 'fake_cdn',
|
||||
]);
|
||||
|
||||
$this->assertSame(
|
||||
'/api/plugins/sirsoft-ckeditor5/images/aaaabbbbcccc',
|
||||
$image->download_url
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @scenario consumer=editor, disk_setting=fake_cdn, e2e=drivers_tab_card, hook=block, override=module_override, row_state=legacy_local_row
|
||||
*
|
||||
* @effects hook_supply_modify_block_respected
|
||||
*/
|
||||
#[Test]
|
||||
public function hook_block_falls_back_to_api_url(): void
|
||||
{
|
||||
HookManager::addFilter('core.storage.filter_url', fn ($url) => '');
|
||||
|
||||
$image = new Ckeditor5ImageUpload([
|
||||
'hash' => 'aaaabbbbcccc',
|
||||
'file_path' => 'images/2026/01/01/a.jpg',
|
||||
'storage_disk' => 'fake_cdn',
|
||||
]);
|
||||
|
||||
$this->assertSame(
|
||||
'/api/plugins/sirsoft-ckeditor5/images/aaaabbbbcccc',
|
||||
$image->download_url
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
<?php
|
||||
|
||||
namespace Plugins\Sirsoft\Ckeditor5\Tests\Unit;
|
||||
|
||||
use App\Extension\PluginManager;
|
||||
use App\Extension\Storage\PluginStorageDriver;
|
||||
use App\Services\PluginSettingsService;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use Plugins\Sirsoft\Ckeditor5\Models\Ckeditor5ImageUpload;
|
||||
use Plugins\Sirsoft\Ckeditor5\Plugin;
|
||||
use Plugins\Sirsoft\Ckeditor5\Repositories\Contracts\ImageUploadRepositoryInterface;
|
||||
use Plugins\Sirsoft\Ckeditor5\Services\ImageServeService;
|
||||
use Plugins\Sirsoft\Ckeditor5\Services\ImageUploadService;
|
||||
use Plugins\Sirsoft\Ckeditor5\Tests\PluginTestCase;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
|
||||
/**
|
||||
* ImageServeService 행 disk 기준 서빙 테스트
|
||||
*
|
||||
* 공개 자산 디스크 전환 이후에도 전환 이전 행(구 disk)의 서빙이 404 가 되지 않고,
|
||||
* CDN 디스크로 기록된 행의 스트리밍 요청도 그 행의 실제 저장 위치를 향하는지
|
||||
* (혼재 운용 정합) 검증합니다.
|
||||
*
|
||||
* ImageServeControllerTest 는 모든 행이 주입 디스크('plugins')라서
|
||||
* withDisk 분기가 실행되지 않으므로 별도 파일로 둡니다.
|
||||
*/
|
||||
class ImageServeServiceRowDiskTest extends PluginTestCase
|
||||
{
|
||||
private ImageServeService $service;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
Config::set('filesystems.disks.fake_cdn', [
|
||||
'driver' => 'local',
|
||||
'root' => storage_path('framework/testing/disks/fake_cdn'),
|
||||
'url' => 'https://cdn.test/assets',
|
||||
]);
|
||||
Ckeditor5ImageUpload::flushStorageCache();
|
||||
|
||||
$this->service = app(ImageServeService::class);
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
Ckeditor5ImageUpload::flushStorageCache();
|
||||
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/**
|
||||
* 지정 disk 에 파일과 업로드 행을 함께 생성합니다.
|
||||
*
|
||||
* @param string $disk 행 storage_disk
|
||||
* @param string $filePath "카테고리/상대경로" 형태의 file_path
|
||||
* @return Ckeditor5ImageUpload 생성된 행
|
||||
*/
|
||||
private function makeRowOnDisk(string $disk, string $filePath): Ckeditor5ImageUpload
|
||||
{
|
||||
[$category, $relativePath] = explode('/', $filePath, 2);
|
||||
|
||||
(new PluginStorageDriver('sirsoft-ckeditor5', $disk))->put($category, $relativePath, 'image-bytes');
|
||||
|
||||
return Ckeditor5ImageUpload::create([
|
||||
'original_name' => basename($filePath),
|
||||
'file_path' => $filePath,
|
||||
'storage_disk' => $disk,
|
||||
'file_size' => 11,
|
||||
'mime_type' => 'image/jpeg',
|
||||
'uploaded_by' => null,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @effects serve_and_delete_follow_row_disk, mixed_rows_resolve_per_row_disk
|
||||
*/
|
||||
#[Test]
|
||||
public function serve_streams_row_from_its_recorded_disk(): void
|
||||
{
|
||||
// 혼재 운용 — 주입 스토리지 disk('plugins')와 다른 disk 의 행도 서빙 가능해야 한다
|
||||
$cdnRow = $this->makeRowOnDisk('fake_cdn', 'images/row-disk-test/cdn.jpg');
|
||||
$localRow = $this->makeRowOnDisk('plugins', 'images/row-disk-test/local.jpg');
|
||||
|
||||
$this->assertInstanceOf(StreamedResponse::class, $this->service->serve($cdnRow));
|
||||
$this->assertInstanceOf(StreamedResponse::class, $this->service->serve($localRow));
|
||||
}
|
||||
|
||||
/**
|
||||
* 외부 생성 행(첫 세그먼트가 'images' 가 아닌 경우)도 카테고리 일반형 분해로
|
||||
* 행 disk 에서 서빙된다 — ApiDoc 샘플(`ckeditor5/apidoc-sample.png`) 형태.
|
||||
*
|
||||
* @effects serve_and_delete_follow_row_disk
|
||||
*/
|
||||
#[Test]
|
||||
public function serve_resolves_non_images_prefix_on_row_disk(): void
|
||||
{
|
||||
$row = $this->makeRowOnDisk('fake_cdn', 'ckeditor5/row-disk-sample.png');
|
||||
|
||||
$this->assertInstanceOf(StreamedResponse::class, $this->service->serve($row));
|
||||
}
|
||||
|
||||
/**
|
||||
* 행 disk 에 파일이 없으면 주입 디스크로 몰래 폴백하지 않고 null 을 반환한다
|
||||
* (다른 디스크의 동명 파일을 잘못 서빙하는 회귀 차단).
|
||||
*
|
||||
* @effects serve_and_delete_follow_row_disk
|
||||
*/
|
||||
#[Test]
|
||||
public function serve_returns_null_when_file_absent_on_row_disk(): void
|
||||
{
|
||||
// 파일은 주입 디스크에만 두고, 행은 CDN 디스크로 기록
|
||||
(new PluginStorageDriver('sirsoft-ckeditor5', 'plugins'))
|
||||
->put('images', 'row-disk-test/only-local.jpg', 'image-bytes');
|
||||
|
||||
$row = Ckeditor5ImageUpload::create([
|
||||
'original_name' => 'only-local.jpg',
|
||||
'file_path' => 'images/row-disk-test/only-local.jpg',
|
||||
'storage_disk' => 'fake_cdn',
|
||||
'file_size' => 11,
|
||||
'mime_type' => 'image/jpeg',
|
||||
'uploaded_by' => null,
|
||||
]);
|
||||
|
||||
$this->assertNull($this->service->serve($row));
|
||||
}
|
||||
|
||||
/**
|
||||
* 고아 disk 행의 서빙은 500 이 아니라 스트리밍 폴백이어야 한다.
|
||||
*
|
||||
* 디스크를 제공하던 플러그인이 비활성화되면 행 storage_disk 가 config 에서 사라진다.
|
||||
* 이때 미등록 disk 로 withDisk 를 만들면 response 가 InvalidArgumentException 을
|
||||
* 던져 에디터 이미지 서빙이 500 이 된다.
|
||||
*
|
||||
* @effects orphan_disk_falls_back_to_streaming
|
||||
*/
|
||||
#[Test]
|
||||
public function serve_falls_back_when_row_disk_is_orphaned(): void
|
||||
{
|
||||
$row = $this->makeRowOnDisk('fake_cdn', 'images/row-disk-test/orphan.jpg');
|
||||
|
||||
Config::set('filesystems.disks.fake_cdn', null);
|
||||
Storage::forgetDisk('fake_cdn');
|
||||
Ckeditor5ImageUpload::flushStorageCache();
|
||||
|
||||
// 예외 없이 폴백 — 파일은 도달 불가이므로 null(404) 이 정상 degradation
|
||||
$this->assertNull($this->service->serve($row));
|
||||
}
|
||||
|
||||
/**
|
||||
* SP 배선(`$storageCategoryServices`)이 주입하는 것과 동일한 스토리지로 서비스를 만듭니다.
|
||||
*
|
||||
* PluginTestCase 는 ImageUploadService 의 StorageInterface 를 'plugins' 고정으로
|
||||
* 하드바인딩하므로, 컨테이너 해석으로는 카테고리 디스크 배선을 검증할 수 없습니다.
|
||||
* 여기서는 실제 플러그인 인스턴스의 getStorageFor('images') 를 직접 주입해
|
||||
* 배선이 주는 것과 같은 조건을 재현합니다.
|
||||
*/
|
||||
private function makeUploadServiceWithCategoryStorage(): ImageUploadService
|
||||
{
|
||||
$plugin = app(PluginManager::class)->getPlugin('sirsoft-ckeditor5')
|
||||
?? new Plugin(base_path('plugins/sirsoft-ckeditor5'));
|
||||
|
||||
return new ImageUploadService(
|
||||
app(ImageUploadRepositoryInterface::class),
|
||||
$plugin->getStorageFor('images')
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 플러그인 개별 오버라이드를 지정 값으로 고정합니다.
|
||||
*
|
||||
* PluginTestCase 는 플러그인 설정을 격리하지 않아, 고정하지 않으면
|
||||
* `plugin_setting()` 이 개발 머신의 실제 저장값(storage/app/plugins/…)을 읽는다.
|
||||
* 오버라이드는 코어 전역보다 우선하므로 그 값이 남아 있으면 전역 설정을 세우는
|
||||
* 이 테스트가 개발자 환경에 따라 통과/실패한다 — 두 입력을 모두 통제한다.
|
||||
*
|
||||
* @param string $override 플러그인 설정 public_asset_disk 값 ('' = 코어 따름)
|
||||
*/
|
||||
private function fixPluginOverride(string $override): void
|
||||
{
|
||||
$stub = new class($override) extends PluginSettingsService
|
||||
{
|
||||
public function __construct(private string $override) {}
|
||||
|
||||
public function get(string $identifier, ?string $key = null, mixed $default = null): mixed
|
||||
{
|
||||
if ($key === 'public_asset_disk') {
|
||||
return $this->override;
|
||||
}
|
||||
|
||||
return $default;
|
||||
}
|
||||
};
|
||||
|
||||
$this->app->instance(PluginSettingsService::class, $stub);
|
||||
}
|
||||
|
||||
/**
|
||||
* put 종단 — 공개 자산 디스크 설정값이 신규 행의 storage_disk 에 기록되고,
|
||||
* 그 행이 다시 자기 disk 로 서빙되는지 단언합니다(배선 회귀 검출).
|
||||
*
|
||||
* @effects mixed_rows_resolve_per_row_disk
|
||||
*/
|
||||
#[Test]
|
||||
public function upload_records_configured_public_asset_disk_on_row(): void
|
||||
{
|
||||
$this->fixPluginOverride('');
|
||||
Config::set('core.storage.public_asset_disk', 'fake_cdn');
|
||||
|
||||
$record = $this->makeUploadServiceWithCategoryStorage()
|
||||
->upload(UploadedFile::fake()->image('cdn-editor.jpg', 40, 40), null);
|
||||
|
||||
$this->assertSame('fake_cdn', $record->storage_disk);
|
||||
$this->assertInstanceOf(StreamedResponse::class, $this->service->serve($record));
|
||||
}
|
||||
|
||||
/**
|
||||
* put 종단 — 공개 자산 디스크 미설정이면 신규 행이 기본 디스크로 기록(현행 보존).
|
||||
*
|
||||
* @effects mixed_rows_resolve_per_row_disk
|
||||
*/
|
||||
#[Test]
|
||||
public function upload_records_base_disk_when_public_asset_disk_unset(): void
|
||||
{
|
||||
$this->fixPluginOverride('');
|
||||
Config::set('core.storage.public_asset_disk', '');
|
||||
|
||||
$record = $this->makeUploadServiceWithCategoryStorage()
|
||||
->upload(UploadedFile::fake()->image('local-editor.jpg', 40, 40), null);
|
||||
|
||||
$this->assertSame('plugins', $record->storage_disk);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
|
||||
namespace Plugins\Sirsoft\Ckeditor5\Tests\Unit;
|
||||
|
||||
use App\Extension\AbstractPlugin;
|
||||
use App\Extension\PluginManager;
|
||||
use App\Http\Controllers\Api\Admin\PluginSettingsController;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use Plugins\Sirsoft\Ckeditor5\Tests\PluginTestCase;
|
||||
|
||||
/**
|
||||
* 플러그인 설정 응답 공개 자산 카탈로그 부착 테스트 (공개#100)
|
||||
*
|
||||
* 설정 스키마가 public_asset_disk 를 선언한 플러그인(ckeditor5)의 설정 GET 응답에
|
||||
* available_public_asset_disks 카탈로그가 서버 부착되는지 검증합니다. 화면이 코어
|
||||
* 설정 API(core.settings.read)를 교차 조회하면 화면 권한(core.plugins.read)과
|
||||
* 표면이 갈려 커스텀 역할에서 카탈로그만 조용히 비므로, 단일 표면 계약을 고정합니다.
|
||||
*
|
||||
* @effects settings_catalog_includes_plugin_registered_disks
|
||||
*/
|
||||
class PluginSettingsCatalogAttachTest extends PluginTestCase
|
||||
{
|
||||
#[Test]
|
||||
public function settings_response_attaches_public_asset_catalog(): void
|
||||
{
|
||||
$response = app(PluginSettingsController::class)->show('sirsoft-ckeditor5');
|
||||
|
||||
$this->assertSame(200, $response->getStatusCode());
|
||||
|
||||
$data = $response->getData(true)['data'] ?? [];
|
||||
$this->assertArrayHasKey('available_public_asset_disks', $data);
|
||||
|
||||
$ids = array_column($data['available_public_asset_disks'], 'id');
|
||||
$this->assertContains('none', $ids);
|
||||
$this->assertContains('public', $ids);
|
||||
$this->assertContains('s3', $ids);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function catalog_is_not_attached_when_schema_lacks_public_asset_disk(): void
|
||||
{
|
||||
// 스키마에 public_asset_disk 가 없는 플러그인 시뮬레이션 — 게이트가 닫혀야 한다
|
||||
$plugin = $this->createMock(AbstractPlugin::class);
|
||||
$plugin->method('getSettingsSchema')->willReturn([
|
||||
'some_other_key' => ['type' => 'string'],
|
||||
]);
|
||||
|
||||
$manager = $this->createMock(PluginManager::class);
|
||||
$manager->method('getPlugin')->willReturn($plugin);
|
||||
$this->app->instance(PluginManager::class, $manager);
|
||||
|
||||
$response = app(PluginSettingsController::class)->show('sirsoft-ckeditor5');
|
||||
|
||||
$this->assertSame(200, $response->getStatusCode());
|
||||
$this->assertArrayNotHasKey(
|
||||
'available_public_asset_disks',
|
||||
$response->getData(true)['data'] ?? []
|
||||
);
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
$this->app->forgetInstance(PluginManager::class);
|
||||
|
||||
parent::tearDown();
|
||||
}
|
||||
}
|
||||
+119
@@ -0,0 +1,119 @@
|
||||
<?php
|
||||
|
||||
namespace Plugins\Sirsoft\Ckeditor5\Tests\Unit;
|
||||
|
||||
use App\Extension\AbstractPlugin;
|
||||
use App\Extension\PluginManager;
|
||||
use App\Http\Requests\Admin\UpdatePluginSettingsRequest;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use Plugins\Sirsoft\Ckeditor5\Tests\PluginTestCase;
|
||||
|
||||
/**
|
||||
* 플러그인 공개 자산 디스크 저장 검증 테스트 (공개#100)
|
||||
*
|
||||
* 코어가 카탈로그를 부착하는 게이트(스키마에 public_asset_disk 선언)와 동일한
|
||||
* 조건에서 값 검증도 걸린다. 선택지를 내려주는 표면과 값을 받는 표면의 강도가
|
||||
* 갈리면, 오타 디스크명이 200 으로 저장된 뒤 런타임 폴백만 남아 운영자에게는
|
||||
* "저장은 됐는데 CDN 이 안 붙는" 무증상 상태로만 보인다.
|
||||
*
|
||||
* 스키마 타입만으로는 검증할 수 없다 — 선택지가 코어 3종 + 플러그인 훅 등록
|
||||
* 디스크라 런타임에만 확정되기 때문이다.
|
||||
*
|
||||
* @effects invalid_disk_rejected_with_422
|
||||
*/
|
||||
class PluginSettingsPublicAssetDiskValidationTest extends PluginTestCase
|
||||
{
|
||||
/**
|
||||
* 플러그인 설정 저장 요청을 해석합니다.
|
||||
*
|
||||
* @param string $disk public_asset_disk 값
|
||||
*/
|
||||
private function resolve(string $disk): UpdatePluginSettingsRequest
|
||||
{
|
||||
$request = UpdatePluginSettingsRequest::create('/', 'PUT', [
|
||||
'public_asset_disk' => $disk,
|
||||
]);
|
||||
$request->setContainer($this->app)->setRedirector($this->app['redirect']);
|
||||
$request->setRouteResolver(fn () => new class
|
||||
{
|
||||
public function parameter(string $key, $default = null): string
|
||||
{
|
||||
return 'sirsoft-ckeditor5';
|
||||
}
|
||||
});
|
||||
$request->validateResolved();
|
||||
|
||||
return $request;
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function core_catalog_disk_is_accepted(): void
|
||||
{
|
||||
$request = $this->resolve('public');
|
||||
|
||||
$this->assertSame('public', $request->validated()['public_asset_disk']);
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function empty_value_is_accepted_as_follow_core(): void
|
||||
{
|
||||
$request = $this->resolve('');
|
||||
|
||||
$this->assertSame('', $request->validated()['public_asset_disk'] ?? '');
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function unknown_disk_is_rejected(): void
|
||||
{
|
||||
$this->expectException(ValidationException::class);
|
||||
|
||||
try {
|
||||
$this->resolve('nonexistent_disk');
|
||||
} catch (ValidationException $e) {
|
||||
$this->assertArrayHasKey(
|
||||
'public_asset_disk',
|
||||
$e->validator->errors()->toArray(),
|
||||
'카탈로그에 없는 디스크는 public_asset_disk 오류를 내야 한다'
|
||||
);
|
||||
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
|
||||
#[Test]
|
||||
public function validation_gate_is_closed_when_schema_lacks_the_key(): void
|
||||
{
|
||||
// 이 키를 선언하지 않은 플러그인에는 검증도 붙지 않아야 한다 —
|
||||
// 부착 게이트(PluginSettingsController)와 검증 게이트가 같은 조건이어야 한다.
|
||||
$plugin = $this->createMock(AbstractPlugin::class);
|
||||
$plugin->method('getSettingsSchema')->willReturn([
|
||||
'some_other_key' => ['type' => 'string'],
|
||||
]);
|
||||
|
||||
$manager = $this->createMock(PluginManager::class);
|
||||
$manager->method('getPlugin')->willReturn($plugin);
|
||||
$this->app->instance(PluginManager::class, $manager);
|
||||
|
||||
$request = UpdatePluginSettingsRequest::create('/', 'PUT', [
|
||||
'some_other_key' => 'value',
|
||||
]);
|
||||
$request->setContainer($this->app)->setRedirector($this->app['redirect']);
|
||||
$request->setRouteResolver(fn () => new class
|
||||
{
|
||||
public function parameter(string $key, $default = null): string
|
||||
{
|
||||
return 'other-plugin';
|
||||
}
|
||||
});
|
||||
|
||||
$this->assertArrayNotHasKey('public_asset_disk', $request->rules());
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
$this->app->forgetInstance(PluginManager::class);
|
||||
|
||||
parent::tearDown();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
<?php
|
||||
|
||||
namespace Plugins\Sirsoft\Ckeditor5\Tests\Unit;
|
||||
|
||||
use App\Extension\PluginManager;
|
||||
use App\Services\PluginSettingsService;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
use Plugins\Sirsoft\Ckeditor5\Plugin;
|
||||
use Plugins\Sirsoft\Ckeditor5\Tests\PluginTestCase;
|
||||
|
||||
/**
|
||||
* getStorageDiskFor 설정 로드 순환 참조 회귀 테스트 (실제 설정 로드 경로)
|
||||
*
|
||||
* 실제 플러그인 인스턴스의 getStorageDiskFor 가 plugin_setting() 을 경유할 때,
|
||||
* 설정 로드 자신이 스토리지('settings' 카테고리)를 다시 요구하는 상황을
|
||||
* 컨테이너 스파이로 재현합니다. PUBLIC_ASSET_CATEGORIES 게이트가 제거되면
|
||||
* 'settings' 해석이 설정 서비스를 재호출해 호출 횟수 단언이 깨집니다.
|
||||
*/
|
||||
class StorageDiskRecursionTest extends PluginTestCase
|
||||
{
|
||||
private Plugin $plugin;
|
||||
|
||||
/**
|
||||
* 설정 로드가 스토리지를 경유하는 경로를 재현하는 스파이
|
||||
*/
|
||||
private object $settingsSpy;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
Config::set('filesystems.disks.fake_cdn', [
|
||||
'driver' => 'local',
|
||||
'root' => storage_path('framework/testing/disks/fake_cdn'),
|
||||
'url' => 'https://cdn.test/assets',
|
||||
]);
|
||||
Config::set('core.storage.public_asset_disk', '');
|
||||
|
||||
$this->plugin = app(PluginManager::class)->getPlugin('sirsoft-ckeditor5')
|
||||
?? new Plugin(base_path('plugins/sirsoft-ckeditor5'));
|
||||
|
||||
// 실제 설정 로드처럼 get() 내부에서 플러그인 스토리지('settings')를 재요구하는 스파이.
|
||||
// 재진입(= getStorageDiskFor('settings') 가 다시 설정을 조회하는 회귀) 발생 시
|
||||
// reentered 플래그 + 호출 횟수 증가로 검출됩니다.
|
||||
$this->settingsSpy = new class extends PluginSettingsService
|
||||
{
|
||||
public ?Plugin $plugin = null;
|
||||
|
||||
public int $calls = 0;
|
||||
|
||||
public bool $reentered = false;
|
||||
|
||||
public ?string $nestedDisk = null;
|
||||
|
||||
private bool $inGet = false;
|
||||
|
||||
public function __construct() {}
|
||||
|
||||
public function get(string $identifier, ?string $key = null, mixed $default = null): mixed
|
||||
{
|
||||
$this->calls++;
|
||||
|
||||
if ($this->inGet) {
|
||||
// 설정 로드 중 설정 재조회 = 순환 고리. 무한 재귀 대신 폭로.
|
||||
$this->reentered = true;
|
||||
|
||||
return $default;
|
||||
}
|
||||
|
||||
$this->inGet = true;
|
||||
|
||||
try {
|
||||
// 설정 로드가 스토리지를 경유하는 실제 경로 재현 —
|
||||
// 이 호출이 getStorageDiskFor('settings') 를 타고 되돌아온다.
|
||||
$this->nestedDisk = $this->plugin->getStorageFor('settings')->getDisk();
|
||||
|
||||
if ($key === 'public_asset_disk') {
|
||||
return 'fake_cdn';
|
||||
}
|
||||
|
||||
return $default;
|
||||
} finally {
|
||||
$this->inGet = false;
|
||||
}
|
||||
}
|
||||
};
|
||||
$this->settingsSpy->plugin = $this->plugin;
|
||||
$this->app->instance(PluginSettingsService::class, $this->settingsSpy);
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
$this->app->forgetInstance(PluginSettingsService::class);
|
||||
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/**
|
||||
* @effects settings_load_recursion_free
|
||||
*/
|
||||
#[Test]
|
||||
public function settings_category_never_consults_plugin_settings(): void
|
||||
{
|
||||
// 'settings' 카테고리 해석은 설정 서비스를 한 번도 거치지 않아야 한다 —
|
||||
// 거치는 순간 설정 로드 ↔ 디스크 해석의 순환 고리가 열린다.
|
||||
$this->assertSame($this->plugin->getStorageDisk(), $this->plugin->getStorageDiskFor('settings'));
|
||||
$this->assertSame(0, $this->settingsSpy->calls);
|
||||
}
|
||||
|
||||
/**
|
||||
* @effects settings_load_recursion_free
|
||||
*/
|
||||
#[Test]
|
||||
public function images_resolution_survives_settings_load_that_uses_storage(): void
|
||||
{
|
||||
// 공개 자산 카테고리 해석 → 설정 조회 → (설정 로드가 'settings' 스토리지 재요구)
|
||||
// 전체 사슬이 유한 종료하고, 설정 조회는 정확히 1회만 발생해야 한다.
|
||||
$this->assertSame('fake_cdn', $this->plugin->getStorageDiskFor('images'));
|
||||
|
||||
$this->assertSame(1, $this->settingsSpy->calls);
|
||||
$this->assertFalse($this->settingsSpy->reentered, '설정 로드 중 설정 재조회(순환) 발생');
|
||||
// 설정 로드가 요구한 'settings' 스토리지는 공개 자산 디스크가 아닌 기본 디스크
|
||||
$this->assertSame($this->plugin->getStorageDisk(), $this->settingsSpy->nestedDisk);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user