v7.0.0 release
This commit is contained in:
1 parent
0e7fa04b03
commit
c4ea9a6cd1
3582 files changed
+626189
-160151
No files matched your search
@@ -0,0 +1,78 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Seo;
|
||||
|
||||
use App\Seo\Concerns\LocalizesSeoValues;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* LocalizesSeoValues 트레이트 테스트 (공개#49).
|
||||
*
|
||||
* site_name 등 다국어 JSON array 설정값을 현재/폴백 로케일 string 으로 정규화하는
|
||||
* SSoT. SeoRenderer::buildGlobalContext()의 _global.site_name(F4) 및 OG 경로가
|
||||
* 공유하며, array → string 캐스팅 회귀를 차단한다.
|
||||
*/
|
||||
class LocalizesSeoValuesTest extends TestCase
|
||||
{
|
||||
private object $subject;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->subject = new class
|
||||
{
|
||||
use LocalizesSeoValues;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 문자열은 그대로 반환됩니다.
|
||||
*/
|
||||
public function test_string_returned_as_is(): void
|
||||
{
|
||||
$this->assertSame('그누보드7', $this->subject->resolveLocalizedValue('그누보드7'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 다국어 array 는 현재 로케일 string 으로 추출됩니다.
|
||||
*/
|
||||
public function test_localized_array_extracts_current_locale(): void
|
||||
{
|
||||
Config::set('app.locale', 'ko');
|
||||
|
||||
$this->assertSame(
|
||||
'한글몰',
|
||||
$this->subject->resolveLocalizedValue(['ko' => '한글몰', 'en' => 'EngMall']),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 현재 로케일 키 부재 시 폴백 로케일로 추출됩니다.
|
||||
*/
|
||||
public function test_localized_array_falls_back(): void
|
||||
{
|
||||
Config::set('app.locale', 'ja');
|
||||
Config::set('app.fallback_locale', 'en');
|
||||
|
||||
$this->assertSame(
|
||||
'EngMall',
|
||||
$this->subject->resolveLocalizedValue(['en' => 'EngMall']),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 정규화 결과는 항상 string 이라 Blade e()/htmlspecialchars 에서 TypeError 가 없습니다.
|
||||
*/
|
||||
public function test_result_is_always_string_for_safe_html_escaping(): void
|
||||
{
|
||||
Config::set('app.locale', 'ko');
|
||||
|
||||
$result = $this->subject->resolveLocalizedValue(['ko' => '한글몰', 'en' => 'EngMall']);
|
||||
|
||||
$this->assertIsString($result);
|
||||
// htmlspecialchars 가 TypeError 없이 동작
|
||||
$this->assertSame('한글몰', e($result));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Seo;
|
||||
|
||||
use App\Seo\Contracts\SeoRendererInterface;
|
||||
use App\Seo\Editor\SeoBotPreviewService;
|
||||
use Illuminate\Http\Request;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
/**
|
||||
* SeoBotPreviewService 단위 테스트.
|
||||
*
|
||||
* 봇 미리보기는 검색엔진 탭·레이아웃·모듈/코어 SEO 설정이 **산출한 데이터만** 보여준다.
|
||||
* 종전 `extractSeoMarkup`(완성 HTML 을 태그/속성 휴리스틱으로 가지치기)은 폐기 — 대신 렌더 파이프
|
||||
* 라인을 `seoOnly=true` 로 호출해 SEO 산출물 전용 블레이드(seo-preview)로 조립한 HTML 을 그대로
|
||||
* 돌려준다. 본 단위 테스트는 서비스가 ① seoOnly=true 로 호출하는지 ② 결과를 가공 없이 통과시키는지
|
||||
* ③ null 분기를 검증한다. SEO 산출물만 담기는지는 seo-preview 블레이드 Feature 테스트가 SSoT.
|
||||
*/
|
||||
class SeoBotPreviewServiceTest extends TestCase
|
||||
{
|
||||
/** renderer mock — 호출 인자를 캡처하고 주어진 HTML 을 반환한다. */
|
||||
private function recordingRenderer(?string $html): object
|
||||
{
|
||||
return new class($html) implements SeoRendererInterface
|
||||
{
|
||||
public ?bool $lastSeoOnly = null;
|
||||
|
||||
public int $calls = 0;
|
||||
|
||||
public function __construct(private readonly ?string $html) {}
|
||||
|
||||
public function render(Request $request): ?string
|
||||
{
|
||||
return $this->html;
|
||||
}
|
||||
|
||||
public function renderFromResolved(
|
||||
array $mergedLayout,
|
||||
array $routeParams,
|
||||
string $url,
|
||||
string $locale,
|
||||
string $templateIdentifier,
|
||||
string $layoutName,
|
||||
?string $moduleId,
|
||||
?string $pluginId,
|
||||
array $context,
|
||||
?string $defaultLocale = null,
|
||||
bool $seoOnly = false,
|
||||
): ?string {
|
||||
$this->calls++;
|
||||
$this->lastSeoOnly = $seoOnly;
|
||||
|
||||
return $this->html;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private function render(SeoBotPreviewService $svc): ?string
|
||||
{
|
||||
return $svc->render([], [], '/x', 'ko', 'sirsoft-admin_basic', null, null, []);
|
||||
}
|
||||
|
||||
public function test_seo_only_true_로_렌더_파이프라인을_호출한다(): void
|
||||
{
|
||||
// 봇 미리보기는 SEO 설정 산출물만 받아야 하므로 seoOnly=true 로 호출한다.
|
||||
$renderer = $this->recordingRenderer('<head><title>T</title></head>');
|
||||
$svc = new SeoBotPreviewService($renderer);
|
||||
|
||||
$this->render($svc);
|
||||
|
||||
$this->assertSame(1, $renderer->calls);
|
||||
$this->assertTrue($renderer->lastSeoOnly, '봇 미리보기는 seoOnly=true 로 호출');
|
||||
}
|
||||
|
||||
public function test_렌더_결과를_가공_없이_그대로_통과시킨다(): void
|
||||
{
|
||||
// 종전 extractSeoMarkup 후처리 폐기 — 파이프라인이 돌려준 SEO 전용 HTML 을 그대로 반환.
|
||||
$html = '<head><title>봇 제목</title><meta property="og:title" content="봇"></head>';
|
||||
$renderer = $this->recordingRenderer($html);
|
||||
$svc = new SeoBotPreviewService($renderer);
|
||||
|
||||
$this->assertSame($html, $this->render($svc));
|
||||
}
|
||||
|
||||
public function test_seo_비활성_render_null_은_null_로_전달된다(): void
|
||||
{
|
||||
// seoOnly 경로에서도 meta.seo.enabled=false → renderFromResolved 가 null → null 통과.
|
||||
$renderer = $this->recordingRenderer(null);
|
||||
$svc = new SeoBotPreviewService($renderer);
|
||||
|
||||
$this->assertNull($this->render($svc));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Seo;
|
||||
|
||||
use App\Seo\Editor\SeoCandidateService;
|
||||
use ReflectionMethod;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* SeoCandidateService — 확장 후보 라벨 해석 단위.
|
||||
*
|
||||
* extensions 후보의 친화 라벨(localizeName)은 확장 getName()(string|array 다국어)을 로케일로
|
||||
* 해석한다. Endpoint 테스트는 RefreshDatabase 환경에서 활성 확장이 0건이라 폴백 경로를 직접
|
||||
* 보증하기 어려우므로(빈 배열 허용), 라벨 해석 규칙은 본 단위 테스트가 SSoT.
|
||||
*/
|
||||
class SeoCandidateServiceTest extends TestCase
|
||||
{
|
||||
private SeoCandidateService $service;
|
||||
|
||||
private ReflectionMethod $localize;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->service = app(SeoCandidateService::class);
|
||||
$this->localize = new ReflectionMethod(SeoCandidateService::class, 'localizeName');
|
||||
$this->localize->setAccessible(true);
|
||||
}
|
||||
|
||||
private function localize(mixed $name, string $locale, string $fallbackId): string
|
||||
{
|
||||
return $this->localize->invoke($this->service, $name, $locale, $fallbackId);
|
||||
}
|
||||
|
||||
public function test_string_name_returned_as_is(): void
|
||||
{
|
||||
$this->assertSame('이커머스', $this->localize('이커머스', 'ko', 'sirsoft-ecommerce'));
|
||||
}
|
||||
|
||||
public function test_array_name_resolves_requested_locale(): void
|
||||
{
|
||||
$name = ['ko' => '이커머스', 'en' => 'Ecommerce'];
|
||||
$this->assertSame('이커머스', $this->localize($name, 'ko', 'sirsoft-ecommerce'));
|
||||
$this->assertSame('Ecommerce', $this->localize($name, 'en', 'sirsoft-ecommerce'));
|
||||
}
|
||||
|
||||
public function test_array_name_falls_back_to_app_locale_then_first_value(): void
|
||||
{
|
||||
config(['app.locale' => 'en']);
|
||||
// 요청 로케일(ja) 부재 → app.locale(en) 폴백.
|
||||
$name = ['ko' => '이커머스', 'en' => 'Ecommerce'];
|
||||
$this->assertSame('Ecommerce', $this->localize($name, 'ja', 'sirsoft-ecommerce'));
|
||||
|
||||
// 요청·app.locale 둘 다 부재 → 첫 값 폴백.
|
||||
config(['app.locale' => 'fr']);
|
||||
$this->assertSame('이커머스', $this->localize($name, 'ja', 'sirsoft-ecommerce'));
|
||||
}
|
||||
|
||||
public function test_empty_or_invalid_name_falls_back_to_identifier(): void
|
||||
{
|
||||
$this->assertSame('sirsoft-ecommerce', $this->localize('', 'ko', 'sirsoft-ecommerce'));
|
||||
$this->assertSame('sirsoft-ecommerce', $this->localize([], 'ko', 'sirsoft-ecommerce'));
|
||||
$this->assertSame('sirsoft-ecommerce', $this->localize(null, 'ko', 'sirsoft-ecommerce'));
|
||||
// 비문자열 값만 든 배열 → 폴백.
|
||||
$this->assertSame('sirsoft-ecommerce', $this->localize(['ko' => 123], 'ko', 'sirsoft-ecommerce'));
|
||||
}
|
||||
|
||||
/**
|
||||
* collectVars 를 stub 확장으로 직접 호출(reflection). 게이팅 SSoT 검증 —
|
||||
* 선언 확장(declaredExtensions)에 있는 확장의 seoVariables()[_common]+[pageType] 만 수집.
|
||||
*
|
||||
* @param array $activeExtensions [{type,id,instance}]
|
||||
* @param array $declaredExtensions [{type,id}]
|
||||
*/
|
||||
private function collectVars(array $activeExtensions, array $declaredExtensions, ?string $pageType): array
|
||||
{
|
||||
$m = new ReflectionMethod(SeoCandidateService::class, 'collectVars');
|
||||
$m->setAccessible(true);
|
||||
|
||||
return $m->invoke($this->service, $activeExtensions, $declaredExtensions, $pageType);
|
||||
}
|
||||
|
||||
private function stubExtensionWithVars(): object
|
||||
{
|
||||
// seoVariables() 가 _common + product 그룹을 반환하는 stub 확장.
|
||||
return new class
|
||||
{
|
||||
public function seoVariables(): array
|
||||
{
|
||||
return [
|
||||
'_common' => ['commerce_name' => ['source' => 'setting', 'description' => '상점명']],
|
||||
'product' => [
|
||||
'product_name' => ['source' => 'data', 'required' => true, 'description' => '상품명'],
|
||||
'product_description' => ['source' => 'data', 'description' => '상품 설명'],
|
||||
],
|
||||
];
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public function test_collect_vars_gated_by_declared_extensions(): void
|
||||
{
|
||||
$active = [['type' => 'module', 'id' => 'sirsoft-ecommerce', 'instance' => $this->stubExtensionWithVars()]];
|
||||
|
||||
// 선언 확장에 ecommerce 가 있으면 _common + product 그룹 vars 수집.
|
||||
$declared = [['type' => 'module', 'id' => 'sirsoft-ecommerce']];
|
||||
$vars = $this->collectVars($active, $declared, 'product');
|
||||
$names = array_column($vars, 'name');
|
||||
$this->assertContains('commerce_name', $names, '_common vars 수집');
|
||||
$this->assertContains('product_name', $names, 'pageType(product) vars 수집');
|
||||
$this->assertContains('product_description', $names);
|
||||
|
||||
// source/required 메타 보존.
|
||||
$byName = [];
|
||||
foreach ($vars as $v) {
|
||||
$byName[$v['name']] = $v;
|
||||
}
|
||||
$this->assertSame('setting', $byName['commerce_name']['source']);
|
||||
$this->assertSame('data', $byName['product_name']['source']);
|
||||
$this->assertTrue($byName['product_name']['required'] ?? false);
|
||||
}
|
||||
|
||||
public function test_collect_vars_empty_when_extension_not_declared(): void
|
||||
{
|
||||
// 같은 active 확장이라도 declaredExtensions 에 없으면 게이팅으로 0건(프론트가 extensions 미전송 시 재현).
|
||||
$active = [['type' => 'module', 'id' => 'sirsoft-ecommerce', 'instance' => $this->stubExtensionWithVars()]];
|
||||
$vars = $this->collectVars($active, [], 'product');
|
||||
$this->assertSame([], $vars, '선언 확장 0 → vars 게이팅 전량 제외');
|
||||
}
|
||||
|
||||
public function test_collect_vars_common_only_when_page_type_null(): void
|
||||
{
|
||||
$active = [['type' => 'module', 'id' => 'sirsoft-ecommerce', 'instance' => $this->stubExtensionWithVars()]];
|
||||
$declared = [['type' => 'module', 'id' => 'sirsoft-ecommerce']];
|
||||
$vars = $this->collectVars($active, $declared, null);
|
||||
$names = array_column($vars, 'name');
|
||||
$this->assertContains('commerce_name', $names, 'page_type 미선택 → _common 만');
|
||||
$this->assertNotContains('product_name', $names);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,295 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Unit\Seo;
|
||||
|
||||
use App\Contracts\Extension\ModuleManagerInterface;
|
||||
use App\Contracts\Extension\PluginManagerInterface;
|
||||
use App\Seo\ComponentHtmlMapper;
|
||||
use App\Seo\DataSourceResolver;
|
||||
use App\Seo\ExpressionEvaluator;
|
||||
use App\Seo\PipeRegistry;
|
||||
use App\Seo\SeoConfigMerger;
|
||||
use App\Seo\SeoMetaResolver;
|
||||
use App\Seo\SeoRenderer;
|
||||
use App\Seo\TemplateRouteResolver;
|
||||
use App\Services\LayoutService;
|
||||
use App\Services\PluginSettingsService;
|
||||
use App\Services\SettingsService;
|
||||
use App\Services\TemplateService;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\View;
|
||||
use Mockery;
|
||||
use Mockery\MockInterface;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* SeoRenderer::renderFromResolved 추출 회귀 가드.
|
||||
*
|
||||
* render(Request) 는 URL 매핑·data_sources fetch·_global/_local/computed 해석까지 마친 뒤
|
||||
* 공통 파이프라인(renderFromResolved)에 위임하는 얇은 래퍼다. 본 테스트는 그 추출 계약을
|
||||
* 잠근다 — ① render() 가 해석한 컨텍스트로 renderFromResolved 를 호출, ② renderFromResolved
|
||||
* 가 이미 해석된 컨텍스트로 동일 HTML 을 생성, ③ enabled 게이트 일관(편집기 봇 미리보기가
|
||||
* 직접 호출해도 enabled=false → null), ④ defaultLocale 파라미터 폴백. render() 운영 경로의
|
||||
* byte 동등성은 SeoRendererTest(70+) + SEO 전체 스위트가 별도로 잠근다.
|
||||
*/
|
||||
class SeoRendererRenderFromResolvedTest extends TestCase
|
||||
{
|
||||
private TemplateRouteResolver|MockInterface $routeResolver;
|
||||
|
||||
private LayoutService|MockInterface $layoutService;
|
||||
|
||||
private DataSourceResolver|MockInterface $dataSourceResolver;
|
||||
|
||||
private SeoMetaResolver|MockInterface $metaResolver;
|
||||
|
||||
private ComponentHtmlMapper|MockInterface $htmlMapper;
|
||||
|
||||
private ExpressionEvaluator|MockInterface $evaluator;
|
||||
|
||||
private SeoConfigMerger|MockInterface $seoConfigMerger;
|
||||
|
||||
private SeoRenderer $renderer;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->routeResolver = Mockery::mock(TemplateRouteResolver::class);
|
||||
$this->layoutService = Mockery::mock(LayoutService::class);
|
||||
$this->dataSourceResolver = Mockery::mock(DataSourceResolver::class);
|
||||
$this->metaResolver = Mockery::mock(SeoMetaResolver::class);
|
||||
$this->htmlMapper = Mockery::mock(ComponentHtmlMapper::class);
|
||||
$this->evaluator = Mockery::mock(ExpressionEvaluator::class);
|
||||
$this->seoConfigMerger = Mockery::mock(SeoConfigMerger::class);
|
||||
|
||||
$settingsService = Mockery::mock(SettingsService::class);
|
||||
$settingsService->shouldReceive('getFrontendSettings')->andReturn([])->byDefault();
|
||||
$pluginSettingsService = Mockery::mock(PluginSettingsService::class);
|
||||
$pluginSettingsService->shouldReceive('getAllActiveSettings')->andReturn([])->byDefault();
|
||||
$templateService = Mockery::mock(TemplateService::class);
|
||||
$templateService->shouldReceive('getLanguageDataWithModules')
|
||||
->andReturn(['success' => true, 'data' => [], 'error' => null])->byDefault();
|
||||
$moduleManager = Mockery::mock(ModuleManagerInterface::class);
|
||||
$pluginManager = Mockery::mock(PluginManagerInterface::class);
|
||||
|
||||
// 공통 파이프라인이 건드리는 의존성 mock
|
||||
$this->seoConfigMerger->shouldReceive('getMergedConfig')->andReturn([])->byDefault();
|
||||
$pipeRegistry = Mockery::mock(PipeRegistry::class);
|
||||
$pipeRegistry->shouldReceive('setLocale')->byDefault();
|
||||
$this->evaluator->shouldReceive('setTranslations')->byDefault();
|
||||
$this->evaluator->shouldReceive('getPipeRegistry')->andReturn($pipeRegistry)->byDefault();
|
||||
$this->evaluator->shouldReceive('setSeoOverrides')->byDefault();
|
||||
foreach (['setComponentMap', 'setRenderModes', 'setSelfClosing', 'setTextProps', 'setAttrMap', 'setAllowedAttrs', 'setGlobalResolver', 'setSeoVars'] as $m) {
|
||||
$this->htmlMapper->shouldReceive($m)->byDefault();
|
||||
}
|
||||
$this->metaResolver->shouldReceive('resolveLocalizedValue')
|
||||
->andReturnUsing(fn ($v) => is_string($v) ? $v : (string) ($v ?? ''))->byDefault();
|
||||
|
||||
$this->renderer = new SeoRenderer(
|
||||
$this->routeResolver,
|
||||
$this->layoutService,
|
||||
$templateService,
|
||||
$this->dataSourceResolver,
|
||||
$this->metaResolver,
|
||||
$this->htmlMapper,
|
||||
$this->evaluator,
|
||||
$this->seoConfigMerger,
|
||||
$settingsService,
|
||||
$pluginSettingsService,
|
||||
$moduleManager,
|
||||
$pluginManager,
|
||||
);
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
Mockery::close();
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/** 최소 meta 결과 — SeoMetaResolver::resolve 흉내 */
|
||||
private function metaResult(string $title): array
|
||||
{
|
||||
return [
|
||||
'title' => $title,
|
||||
'titleSuffix' => '',
|
||||
'description' => '',
|
||||
'keywords' => '',
|
||||
'og' => [],
|
||||
'twitter' => [],
|
||||
'structured_data' => null,
|
||||
'ogTags' => '',
|
||||
'twitterTags' => '',
|
||||
'jsonLd' => '',
|
||||
'googleAnalyticsId' => '',
|
||||
'googleVerification' => '',
|
||||
'naverVerification' => '',
|
||||
];
|
||||
}
|
||||
|
||||
private function enabledLayout(): array
|
||||
{
|
||||
return [
|
||||
'meta' => ['seo' => ['enabled' => true]],
|
||||
'components' => [['component' => 'Div', 'props' => ['text' => '본문']]],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* renderFromResolved 는 이미 해석된 컨텍스트로 완성 HTML 을 생성한다(편집기 봇 미리보기 경로).
|
||||
*/
|
||||
public function test_render_from_resolved_produces_html_from_seed_context(): void
|
||||
{
|
||||
$this->metaResolver->shouldReceive('resolve')->once()->andReturn($this->metaResult('봇 제목'));
|
||||
$this->htmlMapper->shouldReceive('render')->once()->andReturn('<div>본문</div>');
|
||||
|
||||
$expected = '<!DOCTYPE html><html lang="ko"><head><title>봇 제목</title></head><body><div>본문</div></body></html>';
|
||||
$viewMock = Mockery::mock(\Illuminate\View\View::class);
|
||||
$viewMock->shouldReceive('render')->once()->andReturn($expected);
|
||||
View::shouldReceive('make')
|
||||
->with('seo', Mockery::on(fn ($d) => $d['title'] === '봇 제목' && $d['bodyHtml'] === '<div>본문</div>'))
|
||||
->once()
|
||||
->andReturn($viewMock);
|
||||
|
||||
$result = $this->renderer->renderFromResolved(
|
||||
$this->enabledLayout(),
|
||||
['id' => '1'],
|
||||
'/preview/test',
|
||||
'ko',
|
||||
'sirsoft-basic',
|
||||
'preview/test',
|
||||
null,
|
||||
null,
|
||||
['route' => ['path' => '/preview/test'], 'query' => [], '_global' => [], '_local' => []],
|
||||
null,
|
||||
);
|
||||
|
||||
$this->assertSame($expected, $result);
|
||||
}
|
||||
|
||||
/**
|
||||
* enabled=false 면 renderFromResolved 도 render() 단계3 게이트와 동일하게 null 을 반환한다.
|
||||
* (편집기 봇 미리보기가 render() 를 거치지 않고 직접 호출해도 "검색엔진 미노출"과 일치.)
|
||||
*/
|
||||
public function test_render_from_resolved_returns_null_when_disabled(): void
|
||||
{
|
||||
// resolve/render/View 는 호출되면 안 됨 — enabled 게이트에서 조기 반환.
|
||||
$this->metaResolver->shouldReceive('resolve')->never();
|
||||
$this->htmlMapper->shouldReceive('render')->never();
|
||||
|
||||
$result = $this->renderer->renderFromResolved(
|
||||
['meta' => ['seo' => ['enabled' => false]], 'components' => []],
|
||||
[],
|
||||
'/preview/test',
|
||||
'ko',
|
||||
'sirsoft-basic',
|
||||
'preview/test',
|
||||
null,
|
||||
null,
|
||||
['route' => [], 'query' => [], '_global' => [], '_local' => []],
|
||||
null,
|
||||
);
|
||||
|
||||
$this->assertNull($result);
|
||||
}
|
||||
|
||||
/**
|
||||
* meta.seo 자체가 없으면 null (render() 단계3 `! $seoConfig` 와 동일).
|
||||
*/
|
||||
public function test_render_from_resolved_returns_null_when_no_seo_config(): void
|
||||
{
|
||||
$this->metaResolver->shouldReceive('resolve')->never();
|
||||
|
||||
$result = $this->renderer->renderFromResolved(
|
||||
['meta' => [], 'components' => []],
|
||||
[],
|
||||
'/x',
|
||||
'ko',
|
||||
'sirsoft-basic',
|
||||
'x',
|
||||
null,
|
||||
null,
|
||||
[],
|
||||
null,
|
||||
);
|
||||
|
||||
$this->assertNull($result);
|
||||
}
|
||||
|
||||
/**
|
||||
* defaultLocale=null 이면 config('app.locale') 폴백으로 canonical 을 구성한다(render() 가
|
||||
* seo_default_locale request attribute 에서 추출해 넘기는 값의 폴백).
|
||||
*/
|
||||
public function test_render_from_resolved_default_locale_falls_back_to_config(): void
|
||||
{
|
||||
config()->set('app.locale', 'ko');
|
||||
|
||||
$this->metaResolver->shouldReceive('resolve')->once()->andReturn($this->metaResult('제목'));
|
||||
$this->htmlMapper->shouldReceive('render')->once()->andReturn('');
|
||||
|
||||
// locale=ko == defaultLocale(config ko) → canonical 에 ?locale= 없음.
|
||||
View::shouldReceive('make')
|
||||
->with('seo', Mockery::on(fn ($d) => ! str_contains($d['canonicalUrl'], '?locale=')))
|
||||
->once()
|
||||
->andReturn(tap(Mockery::mock(\Illuminate\View\View::class), fn ($m) => $m->shouldReceive('render')->andReturn('ok')));
|
||||
|
||||
$result = $this->renderer->renderFromResolved(
|
||||
$this->enabledLayout(),
|
||||
[],
|
||||
'/page',
|
||||
'ko',
|
||||
'sirsoft-basic',
|
||||
'page',
|
||||
null,
|
||||
null,
|
||||
['route' => [], 'query' => [], '_global' => [], '_local' => []],
|
||||
null,
|
||||
);
|
||||
|
||||
$this->assertSame('ok', $result);
|
||||
}
|
||||
|
||||
/**
|
||||
* render(Request) 는 컨텍스트 해석 후 같은 입력에 대해 renderFromResolved 와 동일한 최종
|
||||
* HTML 을 만든다 — 추출 위임 동등성(부분 목으로 renderFromResolved 호출을 검증).
|
||||
*/
|
||||
public function test_render_delegates_to_render_from_resolved_with_resolved_context(): void
|
||||
{
|
||||
$request = Request::create('/products/9');
|
||||
$request->attributes->set('seo_default_locale', 'ko');
|
||||
|
||||
$this->routeResolver->shouldReceive('resolve')->with('/products/9')->once()->andReturn([
|
||||
'templateIdentifier' => 'sirsoft-basic',
|
||||
'layoutName' => 'shop/show',
|
||||
'routeParams' => ['id' => '9'],
|
||||
'moduleIdentifier' => null,
|
||||
'pluginIdentifier' => null,
|
||||
]);
|
||||
$this->layoutService->shouldReceive('getLayout')->with('sirsoft-basic', 'shop/show')->once()
|
||||
->andReturn($this->enabledLayout());
|
||||
|
||||
// render() 본문이 renderFromResolved 에 위임 → 부분 목으로 인자 검증.
|
||||
$partial = Mockery::mock(SeoRenderer::class, [
|
||||
$this->routeResolver, $this->layoutService, Mockery::mock(TemplateService::class),
|
||||
$this->dataSourceResolver, $this->metaResolver, $this->htmlMapper, $this->evaluator,
|
||||
$this->seoConfigMerger, Mockery::mock(SettingsService::class), Mockery::mock(PluginSettingsService::class),
|
||||
Mockery::mock(ModuleManagerInterface::class), Mockery::mock(PluginManagerInterface::class),
|
||||
])->makePartial();
|
||||
|
||||
$partial->shouldReceive('renderFromResolved')
|
||||
->once()
|
||||
->withArgs(function ($layout, $routeParams, $url, $locale, $tpl, $layoutName, $mod, $plug, $ctx, $default) {
|
||||
return $url === '/products/9'
|
||||
&& $routeParams === ['id' => '9']
|
||||
&& $tpl === 'sirsoft-basic'
|
||||
&& $layoutName === 'shop/show'
|
||||
&& $default === 'ko'
|
||||
&& ($ctx['route']['path'] ?? null) === '/products/9';
|
||||
})
|
||||
->andReturn('<delegated/>');
|
||||
|
||||
$result = $partial->render($request);
|
||||
|
||||
$this->assertSame('<delegated/>', $result);
|
||||
}
|
||||
}
|
||||
@@ -497,4 +497,110 @@ class TemplateRouteResolverTest extends TestCase
|
||||
$this->assertNull($result['moduleIdentifier']);
|
||||
$this->assertNull($result['pluginIdentifier']);
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// routeExists() — 미등록 경로 404 판별 (공개#47)
|
||||
// ========================================================================
|
||||
|
||||
/**
|
||||
* 지정한 템플릿 타입으로 routes 를 반환하는 resolver 를 생성합니다.
|
||||
*
|
||||
* @param string $type 템플릿 타입 ('user' | 'admin')
|
||||
* @param array|null $activeTemplate 활성 템플릿 (null 이면 미설치)
|
||||
* @param array $routes 라우트 배열
|
||||
* @param bool $routesSuccess 라우트 조회 성공 여부
|
||||
* @return TemplateRouteResolver 설정된 resolver
|
||||
*/
|
||||
private function createResolverForType(string $type, ?array $activeTemplate, array $routes = [], bool $routesSuccess = true): TemplateRouteResolver
|
||||
{
|
||||
/** @var TemplateManagerInterface|MockInterface $templateManager */
|
||||
$templateManager = Mockery::mock(TemplateManagerInterface::class);
|
||||
$templateManager->shouldReceive('getActiveTemplate')->with($type)->andReturn($activeTemplate);
|
||||
|
||||
/** @var TemplateService|MockInterface $templateService */
|
||||
$templateService = Mockery::mock(TemplateService::class);
|
||||
$templateService->shouldReceive('getRoutesDataWithModules')->withAnyArgs()->andReturn([
|
||||
'success' => $routesSuccess,
|
||||
'data' => ['routes' => $routes],
|
||||
]);
|
||||
|
||||
$moduleManager = Mockery::mock(ModuleManagerInterface::class);
|
||||
$moduleManager->shouldReceive('getModule')->andReturn(null);
|
||||
$pluginManager = Mockery::mock(PluginManagerInterface::class);
|
||||
$pluginManager->shouldReceive('getPlugin')->andReturn(null);
|
||||
|
||||
return new TemplateRouteResolver($templateService, $templateManager, $moduleManager, $pluginManager);
|
||||
}
|
||||
|
||||
/**
|
||||
* 등록된 정적/동적/auth_required/guest_only 라우트는 모두 routeExists=true 입니다.
|
||||
*/
|
||||
public function test_route_exists_true_for_registered_routes(): void
|
||||
{
|
||||
$routes = array_merge($this->getDefaultRoutes(), [
|
||||
['path' => '/mypage', 'layout' => 'mypage/index', 'auth_required' => true, 'guest_only' => false, 'meta' => []],
|
||||
['path' => '/login', 'layout' => 'auth/login', 'auth_required' => false, 'guest_only' => true, 'meta' => []],
|
||||
]);
|
||||
|
||||
$resolver = $this->createResolver(['identifier' => 'sirsoft-user_basic'], $routes);
|
||||
|
||||
$this->assertTrue($resolver->routeExists('/', 'user'), '정적 라우트');
|
||||
$this->assertTrue($resolver->routeExists('/about', 'user'), '정적 라우트 about');
|
||||
$this->assertTrue($resolver->routeExists('/shop/products/123', 'user'), '동적 라우트');
|
||||
$this->assertTrue($resolver->routeExists('/mypage', 'user'), 'auth_required 도 존재로 인정 — 회귀 방지 핵심');
|
||||
$this->assertTrue($resolver->routeExists('/login', 'user'), 'guest_only 도 존재로 인정');
|
||||
}
|
||||
|
||||
/**
|
||||
* 미등록 경로 / 초과 세그먼트는 routeExists=false 입니다.
|
||||
*/
|
||||
public function test_route_exists_false_for_unregistered_routes(): void
|
||||
{
|
||||
$resolver = $this->createResolver(['identifier' => 'sirsoft-user_basic'], $this->getDefaultRoutes());
|
||||
|
||||
$this->assertFalse($resolver->routeExists('/this/does/not/exist', 'user'));
|
||||
$this->assertFalse($resolver->routeExists('/shop/products/123/extra', 'user'), '초과 세그먼트는 ^...$ 전체 매칭 실패');
|
||||
}
|
||||
|
||||
/**
|
||||
* resolve()는 auth 라우트에서 null 이지만 routeExists()는 true — 차이 명시 검증.
|
||||
*/
|
||||
public function test_route_exists_differs_from_resolve_for_auth_routes(): void
|
||||
{
|
||||
$routes = [
|
||||
['path' => '/mypage', 'layout' => 'mypage/index', 'auth_required' => true, 'guest_only' => false, 'meta' => []],
|
||||
];
|
||||
|
||||
$resolver = $this->createResolver(['identifier' => 'sirsoft-user_basic'], $routes);
|
||||
|
||||
$this->assertNull($resolver->resolve('/mypage'), 'resolve()는 auth_required 를 SEO 비대상으로 스킵');
|
||||
$this->assertTrue($resolver->routeExists('/mypage', 'user'), 'routeExists()는 존재로 인정');
|
||||
}
|
||||
|
||||
/**
|
||||
* 활성 템플릿 미설치 / routes 로드 실패 시 routeExists=true (404 억제, 안전측 폴백).
|
||||
*/
|
||||
public function test_route_exists_true_fallback_when_template_missing(): void
|
||||
{
|
||||
$noTemplate = $this->createResolverForType('user', null);
|
||||
$this->assertTrue($noTemplate->routeExists('/anything', 'user'), '템플릿 미설치 시 404 억제');
|
||||
|
||||
$loadFailure = $this->createResolverForType('user', ['identifier' => 'sirsoft-user_basic'], [], routesSuccess: false);
|
||||
$this->assertTrue($loadFailure->routeExists('/anything', 'user'), 'routes 로드 실패 시 404 억제');
|
||||
}
|
||||
|
||||
/**
|
||||
* admin 타입 라우트도 routeExists 로 판별됩니다 (admin 와일드카드 prefix → /admin/... 정규화).
|
||||
*/
|
||||
public function test_route_exists_for_admin_type(): void
|
||||
{
|
||||
$routes = [
|
||||
['path' => '*/admin/users', 'layout' => 'admin_user_list', 'auth_required' => true, 'guest_only' => false, 'meta' => []],
|
||||
];
|
||||
|
||||
$resolver = $this->createResolverForType('admin', ['identifier' => 'sirsoft-admin_basic'], $routes);
|
||||
|
||||
$this->assertTrue($resolver->routeExists('/admin/users', 'admin'), '*/admin/users → /admin/users 정규화 매칭');
|
||||
$this->assertFalse($resolver->routeExists('/admin/nonexistent', 'admin'));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user