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,116 @@
|
||||
<?php
|
||||
|
||||
namespace App\Seo\Editor;
|
||||
|
||||
use App\Contracts\Extension\ModuleManagerInterface;
|
||||
use App\Contracts\Extension\PluginManagerInterface;
|
||||
|
||||
/**
|
||||
* 웹소켓 채널/이벤트 카탈로그 수집 서비스 — 데이터소스 websocket 후보.
|
||||
*
|
||||
* 데이터소스 종류=websocket 편집 시 채널을 "구독 가능한 목록 기준 검색 드롭다운"으로
|
||||
* 제시하기 위해, "지금 이 설치본에서 구독 가능한 채널"을 런타임 수집한다. 코어/확장이
|
||||
* `getChannels()` 오버라이드로 등록한 채널명을 출처(core/module/plugin)와 함께 모은다
|
||||
* (CLAUDE.md 채널 프리픽스 규약 — 코어 `core.*`, 모듈 `module.{id}.*`, 플러그인
|
||||
* `plugin.{id}.*`).
|
||||
*
|
||||
* 이벤트는 `HookManager::broadcast($channel, $eventName, $payload)` 호출 시점에 이름이
|
||||
* 정해지는 동적 값이라 정적 레지스트리가 없다. 따라서 이벤트 카탈로그는 비우고
|
||||
* 편집기가 자유 텍스트로 폴백하게 한다(허위 이벤트 목록 생성 금지). 채널은 확실하므로
|
||||
* 검색 드롭다운으로 제공한다.
|
||||
*
|
||||
* Controller 가 가드(`core.templates.layouts.edit`)·응답을 담당하고 본 서비스는 수집만.
|
||||
*
|
||||
* @since 7.0.0-beta.?
|
||||
*/
|
||||
class BroadcastCatalogService
|
||||
{
|
||||
/**
|
||||
* 코어가 `routes/channels.php` 에 등록한 채널 (편집기 후보용 화이트리스트).
|
||||
*
|
||||
* `App.Models.User.{id}` 같은 Laravel 내부 채널은 데이터소스 구독 대상이 아니라 제외.
|
||||
* 코어 공개 실시간 채널만 노출한다.
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
private const CORE_CHANNELS = [
|
||||
'core.admin.dashboard',
|
||||
'core.user.notifications.{uuid}',
|
||||
];
|
||||
|
||||
public function __construct(
|
||||
private readonly ModuleManagerInterface $moduleManager,
|
||||
private readonly PluginManagerInterface $pluginManager,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 채널/이벤트 카탈로그를 수집합니다.
|
||||
*
|
||||
* @return array{channels: array<int, array{name: string, source: array}>, events: array}
|
||||
*/
|
||||
public function collect(): array
|
||||
{
|
||||
$channels = [];
|
||||
|
||||
// 코어 채널.
|
||||
foreach (self::CORE_CHANNELS as $name) {
|
||||
$channels[] = ['name' => $name, 'source' => ['kind' => 'core']];
|
||||
}
|
||||
|
||||
// 모듈 채널.
|
||||
foreach ($this->moduleManager->getActiveModules() as $module) {
|
||||
foreach ($this->extractChannels($module) as $name) {
|
||||
$channels[] = [
|
||||
'name' => $name,
|
||||
'source' => ['kind' => 'module', 'identifier' => $module->getIdentifier()],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
// 플러그인 채널.
|
||||
foreach ($this->pluginManager->getActivePlugins() as $plugin) {
|
||||
foreach ($this->extractChannels($plugin) as $name) {
|
||||
$channels[] = [
|
||||
'name' => $name,
|
||||
'source' => ['kind' => 'plugin', 'identifier' => $plugin->getIdentifier()],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
'channels' => $channels,
|
||||
// 이벤트는 동적 발행이라 정적 카탈로그 없음 — 편집기 자유 텍스트 폴백.
|
||||
'events' => [],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 확장의 `getChannels()` 에서 채널명 목록을 추출합니다(격리 호출).
|
||||
*
|
||||
* @param object $extension 확장 인스턴스
|
||||
* @return array<int, string> 채널명 목록
|
||||
*/
|
||||
private function extractChannels(object $extension): array
|
||||
{
|
||||
if (! method_exists($extension, 'getChannels')) {
|
||||
return [];
|
||||
}
|
||||
try {
|
||||
$channels = $extension->getChannels();
|
||||
} catch (\Throwable) {
|
||||
return [];
|
||||
}
|
||||
if (! is_array($channels)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$names = [];
|
||||
foreach (array_keys($channels) as $name) {
|
||||
if (is_string($name) && $name !== '') {
|
||||
$names[] = $name;
|
||||
}
|
||||
}
|
||||
|
||||
return $names;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
<?php
|
||||
|
||||
namespace App\Seo\Editor;
|
||||
|
||||
use App\Seo\Contracts\SeoRendererInterface;
|
||||
|
||||
/**
|
||||
* 봇 HTML 미리보기 서비스 — 편집기 [검색엔진] 탭 봇 미리보기.
|
||||
*
|
||||
* 운영 SeoRenderer 와 **동일 메타 해석 경로**(`renderFromResolved`)로 dirty 레이아웃 + 편집기
|
||||
* 샘플 데이터를 처리하되, **`seoOnly=true`** 로 호출해 검색엔진 탭·레이아웃·모듈/코어 SEO 설정이
|
||||
* **산출한 데이터만**(title/description/keywords/canonical/hreflang/og/twitter/JSON-LD/소유권
|
||||
* 확인 메타) 담긴 미리보기 HTML 을 받는다(body 컴포넌트 마크업·CSS·시스템 기본
|
||||
* 메타는 SEO 설정 산출물이 아니므로 미포함). 종전 `extractSeoMarkup` 후처리(완성 HTML 을 태그/
|
||||
* 속성 휴리스틱으로 가지치기)는 폐기 — 위치(head/body)나 태그명으로 넘겨짚지 않고 렌더 파이프라인이
|
||||
* 산출한 데이터의 정체성으로 식별한다. SEO 캐시 우회. 실 API fetch 없이 샘플(`seedContext`) 주입.
|
||||
*
|
||||
* `meta.seo.enabled=false` 면 render null 과 일치하게 null 을 반환한다(편집기가 "검색엔진
|
||||
* 미노출" 안내). Controller 가 가드(`core.templates.layouts.edit`)·응답을 담당.
|
||||
*
|
||||
* @since 7.0.0-beta.?
|
||||
*/
|
||||
class SeoBotPreviewService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly SeoRendererInterface $renderer,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* dirty 레이아웃 + 샘플로 봇 HTML 미리보기를 렌더합니다.
|
||||
*
|
||||
* @param array $layout 편집 중(dirty) 병합 레이아웃 JSON (meta.seo 포함)
|
||||
* @param array $routeParams 샘플 라우트 파라미터
|
||||
* @param string $url 미리보기 URL 경로(canonical/hreflang 생성)
|
||||
* @param string $locale 렌더 로케일
|
||||
* @param string $templateIdentifier 편집 대상 템플릿 식별자
|
||||
* @param string|null $moduleId 소속 모듈 식별자
|
||||
* @param string|null $pluginId 소속 플러그인 식별자
|
||||
* @param array $seedContext 편집기 샘플 컨텍스트(sampleData/sampleGlobal._local 등)
|
||||
* @return string|null 완성 HTML, SEO 비활성 시 null
|
||||
*/
|
||||
public function render(
|
||||
array $layout,
|
||||
array $routeParams,
|
||||
string $url,
|
||||
string $locale,
|
||||
string $templateIdentifier,
|
||||
?string $moduleId,
|
||||
?string $pluginId,
|
||||
array $seedContext,
|
||||
): ?string {
|
||||
$layoutName = $layout['layout_name'] ?? ($layout['name'] ?? '');
|
||||
|
||||
// 컨텍스트 시드 — 편집기 샘플 풀 + route/query 보강(운영 render() 의 컨텍스트 구성 대응).
|
||||
$context = $this->buildSeedContext($seedContext, $routeParams, $url);
|
||||
|
||||
// seoOnly=true — 검색엔진 탭/레이아웃/모듈/코어 SEO 설정의 산출물(title/description/
|
||||
// keywords/canonical/hreflang/og/twitter/JSON-LD/소유권 확인 메타)만 담긴 미리보기 HTML.
|
||||
// 렌더 파이프라인이 분리해 둔 산출물 부분을 SEO 전용 블레이드로 조립하므로, 완성 HTML 을
|
||||
// 태그/속성 휴리스틱으로 후처리하지 않는다(body/CSS/시스템 메타는 SEO 산출물 아님).
|
||||
return $this->renderer->renderFromResolved(
|
||||
$layout,
|
||||
$routeParams,
|
||||
$url,
|
||||
$locale,
|
||||
$templateIdentifier,
|
||||
$layoutName,
|
||||
$moduleId,
|
||||
$pluginId,
|
||||
$context,
|
||||
null,
|
||||
true,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 편집기 샘플 풀에 route/query 를 보강해 렌더 컨텍스트를 만듭니다.
|
||||
*
|
||||
* 운영 render() 가 data_sources fetch 결과 + route + query + _global + _local 로 컨텍스트를
|
||||
* 구성하는 것과 대응 — 미리보기는 실 fetch 대신 편집기 샘플(`seedContext`)을 그대로 쓴다.
|
||||
*
|
||||
* @param array $seedContext 편집기 샘플 컨텍스트
|
||||
* @param array $routeParams 샘플 라우트 파라미터
|
||||
* @param string $url 현재 URL 경로
|
||||
* @return array 렌더 컨텍스트
|
||||
*/
|
||||
private function buildSeedContext(array $seedContext, array $routeParams, string $url): array
|
||||
{
|
||||
$context = $seedContext;
|
||||
|
||||
// route 보강(샘플에 명시 안 됐으면 routeParams + path).
|
||||
$context['route'] = array_merge($routeParams, ['path' => $url], (array) ($seedContext['route'] ?? []));
|
||||
$context['query'] = (array) ($seedContext['query'] ?? []);
|
||||
// _global/_local 은 샘플에 있으면 그대로, 없으면 빈 객체(엔진 평가 안전).
|
||||
$context['_global'] = (array) ($seedContext['_global'] ?? []);
|
||||
$context['_local'] = (array) ($seedContext['_local'] ?? []);
|
||||
|
||||
return $context;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,350 @@
|
||||
<?php
|
||||
|
||||
namespace App\Seo\Editor;
|
||||
|
||||
use App\Contracts\Extension\ModuleManagerInterface;
|
||||
use App\Contracts\Extension\PluginManagerInterface;
|
||||
|
||||
/**
|
||||
* SEO 후보 수집 서비스 — 레이아웃 편집기 [검색엔진] 탭 후보 공급.
|
||||
*
|
||||
* page_type 은 코어 고정 enum 이 아니라 확장이 `seoVariables()` 키로 자유 정의하는 열린
|
||||
* 문자열이므로, 편집기 드롭다운 후보를 **활성 모듈/플러그인에서 런타임 수집**한다.
|
||||
* 세 가지 후보를 한 번에 공급:
|
||||
*
|
||||
* 1. page_type 후보 — 활성 확장 `seoVariables()` 키(`_common` 제외) + 각 page_type 별
|
||||
* `seoStructuredData($pageType)` 의 `@type`(구조화 "모듈 제공" 표시 근거).
|
||||
* 2. toggle_setting 후보 — 활성 확장 `config/settings/defaults.json` `defaults.seo.*`
|
||||
* boolean 키 + 친화 라벨(lang).
|
||||
* 3. 유효 vars 후보 — 선언 확장들의 `seoVariables()[_common] + [page_type]` 키 합집합.
|
||||
*
|
||||
* Controller 가 검증/가드(`core.templates.layouts.edit`)를 담당하고, 본 서비스는 순수
|
||||
* 수집만 한다(Service-Repository 정합 — 도메인 수집 로직 분리). 확장 declaration throw 는
|
||||
* 격리(한 확장 오류가 전체 후보 수집을 망치지 않음).
|
||||
*
|
||||
* @since 7.0.0-beta.?
|
||||
*/
|
||||
class SeoCandidateService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly ModuleManagerInterface $moduleManager,
|
||||
private readonly PluginManagerInterface $pluginManager,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 편집기 SEO 탭 후보를 수집합니다.
|
||||
*
|
||||
* @param array $declaredExtensions 현재 레이아웃 meta.seo.extensions (`[{type,id}]`)
|
||||
* @param string|null $pageType 현재 선택된 page_type (유효 vars 게이팅용)
|
||||
* @param string $locale 라벨 해석 로케일
|
||||
* @return array{page_types: array, toggle_settings: array, vars: array}
|
||||
*/
|
||||
public function collect(array $declaredExtensions, ?string $pageType, string $locale): array
|
||||
{
|
||||
$activeExtensions = $this->resolveActiveExtensions();
|
||||
|
||||
return [
|
||||
'page_types' => $this->collectPageTypes($activeExtensions, $declaredExtensions),
|
||||
'toggle_settings' => $this->collectToggleSettings($activeExtensions, $locale),
|
||||
'vars' => $this->collectVars($activeExtensions, $declaredExtensions, $pageType),
|
||||
'extensions' => $this->collectExtensions($activeExtensions, $locale),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 확장 후보 — 확장 SEO 연동 칩(`g7le-seo-extensions`)의 활성 모듈/플러그인 목록.
|
||||
*
|
||||
* 레이아웃 `meta.seo.extensions[]` 에 `{type,id}` 로 저장될 후보를 공급한다. 각 항목은
|
||||
* 친화 라벨(`getName()` 로케일 해석값, 폴백 = id)을 달아 칩 선택지 표시에 쓴다. SEO 별도
|
||||
* 엔드포인트 신설 없이 본 후보 응답에 합류(세션 D 결선 — "활성 모듈/플러그인 후보").
|
||||
*
|
||||
* @param array $activeExtensions resolveActiveExtensions() 결과
|
||||
* @param string $locale 라벨 해석 로케일
|
||||
* @return array<int, array{type: string, id: string, label: string}>
|
||||
*/
|
||||
private function collectExtensions(array $activeExtensions, string $locale): array
|
||||
{
|
||||
$out = [];
|
||||
foreach ($activeExtensions as $ext) {
|
||||
$name = $this->safeCall($ext['instance'], 'getName', $ext['id']);
|
||||
$out[] = [
|
||||
'type' => $ext['type'],
|
||||
'id' => $ext['id'],
|
||||
'label' => $this->localizeName($name, $locale, $ext['id']),
|
||||
];
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* 확장 `getName()` 반환(string|array 다국어)을 로케일 라벨로 해석합니다.
|
||||
*
|
||||
* 배열이면 locale → app.locale → 첫 값 순으로 폴백, 끝내 비면 식별자 폴백.
|
||||
*
|
||||
* @param mixed $name getName() 반환 (string|array<string,string>)
|
||||
* @param string $locale 목표 로케일
|
||||
* @param string $fallbackId 최종 폴백 식별자
|
||||
* @return string 친화 라벨
|
||||
*/
|
||||
private function localizeName(mixed $name, string $locale, string $fallbackId): string
|
||||
{
|
||||
if (is_string($name) && $name !== '') {
|
||||
return $name;
|
||||
}
|
||||
if (is_array($name)) {
|
||||
foreach ([$locale, config('app.locale')] as $loc) {
|
||||
if (is_string($loc) && isset($name[$loc]) && is_string($name[$loc]) && $name[$loc] !== '') {
|
||||
return $name[$loc];
|
||||
}
|
||||
}
|
||||
foreach ($name as $value) {
|
||||
if (is_string($value) && $value !== '') {
|
||||
return $value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $fallbackId;
|
||||
}
|
||||
|
||||
/**
|
||||
* 활성 모듈/플러그인 인스턴스를 `{type, id, instance}` 목록으로 반환합니다.
|
||||
*
|
||||
* @return array<int, array{type: string, id: string, instance: object}>
|
||||
*/
|
||||
private function resolveActiveExtensions(): array
|
||||
{
|
||||
$out = [];
|
||||
foreach ($this->moduleManager->getActiveModules() as $module) {
|
||||
$out[] = ['type' => 'module', 'id' => $module->getIdentifier(), 'instance' => $module];
|
||||
}
|
||||
foreach ($this->pluginManager->getActivePlugins() as $plugin) {
|
||||
$out[] = ['type' => 'plugin', 'id' => $plugin->getIdentifier(), 'instance' => $plugin];
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* page_type 후보 — 활성 확장 seoVariables() 키(_common 제외) + owned @type.
|
||||
*
|
||||
* 선언 확장(declaredExtensions)을 우선 정렬하되, 전체 활성 확장을 fallback 으로 포함한다.
|
||||
* 같은 page_type 을 여러 확장이 선언하면 첫 소유 확장 기준으로 1건만 노출(중복 제거).
|
||||
*
|
||||
* @param array $activeExtensions resolveActiveExtensions() 결과
|
||||
* @param array $declaredExtensions 레이아웃 선언 확장
|
||||
* @return array<int, array{value: string, owner: array, og_type?: string}>
|
||||
*/
|
||||
private function collectPageTypes(array $activeExtensions, array $declaredExtensions): array
|
||||
{
|
||||
$declaredIds = $this->declaredIdSet($declaredExtensions);
|
||||
// 선언 확장 우선 정렬.
|
||||
usort($activeExtensions, function ($a, $b) use ($declaredIds) {
|
||||
$aw = isset($declaredIds[$a['type'].':'.$a['id']]) ? 0 : 1;
|
||||
$bw = isset($declaredIds[$b['type'].':'.$b['id']]) ? 0 : 1;
|
||||
|
||||
return $aw <=> $bw;
|
||||
});
|
||||
|
||||
$seen = [];
|
||||
$out = [];
|
||||
foreach ($activeExtensions as $ext) {
|
||||
$vars = $this->safeCall($ext['instance'], 'seoVariables', []);
|
||||
if (! is_array($vars)) {
|
||||
continue;
|
||||
}
|
||||
foreach (array_keys($vars) as $key) {
|
||||
if ($key === '_common' || ! is_string($key) || $key === '') {
|
||||
continue;
|
||||
}
|
||||
if (isset($seen[$key])) {
|
||||
continue;
|
||||
}
|
||||
$seen[$key] = true;
|
||||
$entry = [
|
||||
'value' => $key,
|
||||
'owner' => ['type' => $ext['type'], 'id' => $ext['id']],
|
||||
];
|
||||
// owned @type — page_type 별 seoStructuredData 의 @type (구조화 "모듈 제공" 표시).
|
||||
$structured = $this->safeCall($ext['instance'], 'seoStructuredData', [], [$key, [], []]);
|
||||
if (is_array($structured) && isset($structured['@type']) && is_string($structured['@type'])) {
|
||||
$entry['og_type'] = $structured['@type'];
|
||||
}
|
||||
$out[] = $entry;
|
||||
}
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* toggle_setting 후보 — 활성 확장 defaults.seo.* boolean 키 + 친화 라벨.
|
||||
*
|
||||
* @param array $activeExtensions resolveActiveExtensions() 결과
|
||||
* @param string $locale 라벨 로케일
|
||||
* @return array<int, array{ref: string, key: string, label: string, owner: array}>
|
||||
*/
|
||||
private function collectToggleSettings(array $activeExtensions, string $locale): array
|
||||
{
|
||||
$out = [];
|
||||
foreach ($activeExtensions as $ext) {
|
||||
$defaults = $this->readSeoDefaults($ext['type'], $ext['id']);
|
||||
foreach ($defaults as $key => $value) {
|
||||
if (! is_bool($value)) {
|
||||
continue;
|
||||
}
|
||||
$out[] = [
|
||||
'ref' => '$'.$ext['type'].'_settings:'.$ext['id'].':seo.'.$key,
|
||||
'key' => $key,
|
||||
'label' => $this->resolveToggleLabel($ext['type'], $ext['id'], $key, $locale),
|
||||
'owner' => ['type' => $ext['type'], 'id' => $ext['id']],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* 유효 vars 후보 — 선언 확장들의 seoVariables()[_common]+[pageType] 키 합집합.
|
||||
*
|
||||
* page_type 미선택 시 _common 만. extensions 변경 시 갱신(편집기 게이팅 ④).
|
||||
*
|
||||
* @param array $activeExtensions resolveActiveExtensions() 결과
|
||||
* @param array $declaredExtensions 레이아웃 선언 확장(게이팅 — 미선언 확장 vars 무효)
|
||||
* @param string|null $pageType 선택된 page_type
|
||||
* @return array<int, array{name: string, source: string, owner: array, required?: bool}>
|
||||
*/
|
||||
private function collectVars(array $activeExtensions, array $declaredExtensions, ?string $pageType): array
|
||||
{
|
||||
$declaredIds = $this->declaredIdSet($declaredExtensions);
|
||||
$seen = [];
|
||||
$out = [];
|
||||
foreach ($activeExtensions as $ext) {
|
||||
// 게이팅 — 선언 확장만 vars 유효(SeoRenderer.php:941-943 정합).
|
||||
if (! isset($declaredIds[$ext['type'].':'.$ext['id']])) {
|
||||
continue;
|
||||
}
|
||||
$vars = $this->safeCall($ext['instance'], 'seoVariables', []);
|
||||
if (! is_array($vars)) {
|
||||
continue;
|
||||
}
|
||||
$groups = [];
|
||||
if (isset($vars['_common']) && is_array($vars['_common'])) {
|
||||
$groups[] = $vars['_common'];
|
||||
}
|
||||
if ($pageType !== null && isset($vars[$pageType]) && is_array($vars[$pageType])) {
|
||||
$groups[] = $vars[$pageType];
|
||||
}
|
||||
foreach ($groups as $group) {
|
||||
foreach ($group as $name => $meta) {
|
||||
if (! is_string($name) || isset($seen[$name])) {
|
||||
continue;
|
||||
}
|
||||
$seen[$name] = true;
|
||||
$entry = [
|
||||
'name' => $name,
|
||||
'source' => is_array($meta) ? (string) ($meta['source'] ?? 'data') : 'data',
|
||||
'owner' => ['type' => $ext['type'], 'id' => $ext['id']],
|
||||
];
|
||||
if (is_array($meta) && ! empty($meta['required'])) {
|
||||
$entry['required'] = true;
|
||||
}
|
||||
$out[] = $entry;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* 선언 확장 식별자 집합(`'type:id' => true`)을 만듭니다.
|
||||
*
|
||||
* @param array $declaredExtensions `[{type,id}]`
|
||||
* @return array<string, bool>
|
||||
*/
|
||||
private function declaredIdSet(array $declaredExtensions): array
|
||||
{
|
||||
$set = [];
|
||||
foreach ($declaredExtensions as $ext) {
|
||||
$type = is_array($ext) ? ($ext['type'] ?? null) : null;
|
||||
$id = is_array($ext) ? ($ext['id'] ?? null) : null;
|
||||
if (is_string($type) && is_string($id)) {
|
||||
$set[$type.':'.$id] = true;
|
||||
}
|
||||
}
|
||||
|
||||
return $set;
|
||||
}
|
||||
|
||||
/**
|
||||
* 확장의 `config/settings/defaults.json` `defaults.seo` 배열을 읽습니다.
|
||||
*
|
||||
* @param string $type module|plugin
|
||||
* @param string $id 확장 식별자
|
||||
* @return array<string, mixed> seo 기본값 맵 (없으면 빈 배열)
|
||||
*/
|
||||
private function readSeoDefaults(string $type, string $id): array
|
||||
{
|
||||
$base = $type === 'module' ? 'modules' : 'plugins';
|
||||
foreach ([base_path("{$base}/{$id}/config/settings/defaults.json"), base_path("{$base}/_bundled/{$id}/config/settings/defaults.json")] as $path) {
|
||||
if (! is_file($path)) {
|
||||
continue;
|
||||
}
|
||||
$decoded = json_decode((string) file_get_contents($path), true);
|
||||
$seo = $decoded['defaults']['seo'] ?? null;
|
||||
|
||||
return is_array($seo) ? $seo : [];
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* toggle_setting 친화 라벨을 해석합니다 — lang 키 `{ext}::settings.seo.{key}` 우선, 폴백 = 키.
|
||||
*
|
||||
* @param string $type module|plugin
|
||||
* @param string $id 확장 식별자
|
||||
* @param string $key seo boolean 키
|
||||
* @param string $locale 로케일
|
||||
* @return string 친화 라벨
|
||||
*/
|
||||
private function resolveToggleLabel(string $type, string $id, string $key, string $locale): string
|
||||
{
|
||||
$candidates = [
|
||||
"{$id}::settings.seo.{$key}",
|
||||
"{$id}::seo.{$key}",
|
||||
];
|
||||
foreach ($candidates as $transKey) {
|
||||
$translated = __($transKey, [], $locale);
|
||||
if (is_string($translated) && $translated !== $transKey) {
|
||||
return $translated;
|
||||
}
|
||||
}
|
||||
|
||||
return $key;
|
||||
}
|
||||
|
||||
/**
|
||||
* 확장 메서드를 격리 호출합니다 — throw 시 fallback 반환(한 확장 오류 격리).
|
||||
*
|
||||
* @param object $instance 확장 인스턴스
|
||||
* @param string $method 메서드명
|
||||
* @param mixed $fallback 실패 시 반환값
|
||||
* @param array $args 인자
|
||||
* @return mixed 결과 또는 fallback
|
||||
*/
|
||||
private function safeCall(object $instance, string $method, mixed $fallback, array $args = []): mixed
|
||||
{
|
||||
if (! method_exists($instance, $method)) {
|
||||
return $fallback;
|
||||
}
|
||||
try {
|
||||
return $instance->{$method}(...$args);
|
||||
} catch (\Throwable) {
|
||||
return $fallback;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,348 @@
|
||||
<?php
|
||||
|
||||
namespace App\Seo\Editor;
|
||||
|
||||
use App\Contracts\Extension\ModuleManagerInterface;
|
||||
use App\Contracts\Extension\PluginManagerInterface;
|
||||
use App\Extension\HookManager;
|
||||
use App\Seo\SeoMetaResolver;
|
||||
|
||||
/**
|
||||
* OG/Twitter/구조화 미리보기 서비스 — 편집기 [검색엔진] 탭.
|
||||
*
|
||||
* og 각 란의 **기본값·출처·필터잠김**은 편집기가 정적 추정할 수 없고, 현재 데이터·
|
||||
* 설정·활성 확장 조합으로 서버가 실제 계산해야만 안다. 본 서비스가 운영 SeoRenderer 와
|
||||
* 동일한 cascade(`resolveOgData` → 모듈 `seoOgDefaults` fillEmptyKeys → 필터)를 실행하고,
|
||||
* **필터 적용 전/후 2회 계산해 diff** 한다:
|
||||
*
|
||||
* - og/twitter: 키별 `{key, effectiveValue, source, overriddenByLayout, lockedByFilter}`.
|
||||
* `source` ∈ core/module:{id}/layout/filter. 코어 기본값이 슬롯 선점하면 `core` 로 정확히
|
||||
* 표기(메커니즘). 필터 전/후 값이 달라진 키만 `lockedByFilter=true`.
|
||||
* - structured: 통 덮어쓰기 모델 — autoBlock(모듈 자동)/hasLayoutBlock/lockedByFilter
|
||||
* +filteredBlock.
|
||||
*
|
||||
* 기본값은 extensions ∧ page_type 둘 다에 종속(SeoRenderer.php:941-943) — 둘 다 있을 때만
|
||||
* 모듈 declaration 을 수집한다(`defaultsAvailable`/`missing`). 편집기 캐시 우회.
|
||||
*
|
||||
* @since 7.0.0-beta.?
|
||||
*/
|
||||
class SeoOgPreviewService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly SeoMetaResolver $metaResolver,
|
||||
private readonly ModuleManagerInterface $moduleManager,
|
||||
private readonly PluginManagerInterface $pluginManager,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* og/twitter/structured 미리보기를 계산합니다.
|
||||
*
|
||||
* @param array $seoConfig 현재 편집 중 meta.seo (병합본 — base 상속분 포함, dirty)
|
||||
* @param array $context 편집기 샘플 컨텍스트
|
||||
* @param array $routeParams 샘플 라우트 파라미터
|
||||
* @param array|null $ownSeo 이 레이아웃이 직접 선언한 meta.seo(base 병합 전, `__editor.original`).
|
||||
* 병합본에는 있으나 own 에는 없는 og/twitter 키 = base 상속(SEO-B).
|
||||
* 미전달 시 종전 동작(상속/자체 구분 없이 모두 layout 출처).
|
||||
* @param string|null $locale 자동값 연결 칩 라벨(seoOgDefaultMeta) 해석 로케일. null 이면 app locale.
|
||||
* @return array{defaultsAvailable: bool, missing: array, og: array, twitter: array, structured: array}
|
||||
*/
|
||||
public function preview(array $seoConfig, array $context, array $routeParams, ?array $ownSeo = null, ?string $locale = null): array
|
||||
{
|
||||
$pageType = $seoConfig['page_type'] ?? null;
|
||||
$extensions = $seoConfig['extensions'] ?? [];
|
||||
$locale ??= app()->getLocale();
|
||||
|
||||
$missing = [];
|
||||
if (empty($extensions)) {
|
||||
$missing[] = 'extensions';
|
||||
}
|
||||
if ($pageType === null || $pageType === '') {
|
||||
$missing[] = 'page_type';
|
||||
}
|
||||
$defaultsAvailable = empty($missing);
|
||||
|
||||
// 1. 레이아웃 + 코어 cascade(모듈 declaration 전).
|
||||
$fallbackTitle = (string) ($seoConfig['title'] ?? '');
|
||||
$fallbackDescription = (string) ($seoConfig['description'] ?? '');
|
||||
$layoutOg = $this->metaResolver->resolveOgData($seoConfig, $context, $fallbackTitle, $fallbackDescription);
|
||||
$layoutTwitter = $this->metaResolver->resolveTwitterData($seoConfig, $context, $layoutOg);
|
||||
$layoutDeclaredOg = $seoConfig['og'] ?? [];
|
||||
$layoutDeclaredTwitter = $seoConfig['twitter'] ?? [];
|
||||
|
||||
// 2. 모듈/플러그인 declaration (extensions ∧ page_type 둘 다 충족 시만).
|
||||
$extOg = [];
|
||||
$extTwitter = [];
|
||||
$extStructured = null;
|
||||
$extOgOwner = []; // key => 'module:{id}' (어느 확장이 그 키를 채웠나)
|
||||
$extOgMeta = []; // key => {expr, label} (연결 칩)
|
||||
$extTwitterMeta = [];
|
||||
$extStructuredMeta = []; // 점 경로 key => {expr, label}
|
||||
if ($defaultsAvailable) {
|
||||
foreach ($extensions as $extDef) {
|
||||
$instance = $this->resolveInstance($extDef['type'] ?? null, $extDef['id'] ?? null);
|
||||
if (! $instance) {
|
||||
continue;
|
||||
}
|
||||
$ownerTag = ($extDef['type']).':'.($extDef['id']);
|
||||
$declOg = $this->safeCall($instance, 'seoOgDefaults', [$pageType, $context, $routeParams]);
|
||||
$declOgMeta = $this->normalizeMeta($this->safeCall($instance, 'seoOgDefaultMeta', [$pageType]), $locale);
|
||||
foreach ((array) $declOg as $k => $v) {
|
||||
if ($k === 'extra') {
|
||||
continue;
|
||||
}
|
||||
if (($v !== null && $v !== '') && ! isset($extOg[$k])) {
|
||||
$extOg[$k] = $v;
|
||||
$extOgOwner[$k] = $ownerTag;
|
||||
if (isset($declOgMeta[$k]) && ! isset($extOgMeta[$k])) {
|
||||
$extOgMeta[$k] = $declOgMeta[$k];
|
||||
}
|
||||
}
|
||||
}
|
||||
$declTwitter = $this->safeCall($instance, 'seoTwitterDefaults', [$pageType, $context, $routeParams]);
|
||||
$declTwitterMeta = $this->normalizeMeta($this->safeCall($instance, 'seoTwitterDefaultMeta', [$pageType]), $locale);
|
||||
foreach ((array) $declTwitter as $k => $v) {
|
||||
if ($k !== 'extra' && ($v !== null && $v !== '') && ! isset($extTwitter[$k])) {
|
||||
$extTwitter[$k] = $v;
|
||||
if (isset($declTwitterMeta[$k]) && ! isset($extTwitterMeta[$k])) {
|
||||
$extTwitterMeta[$k] = $declTwitterMeta[$k];
|
||||
}
|
||||
}
|
||||
}
|
||||
$declStructured = $this->safeCall($instance, 'seoStructuredData', [$pageType, $context, $routeParams]);
|
||||
if (! empty($declStructured)) {
|
||||
$extStructured = $declStructured; // 마지막 확장 우선.
|
||||
// 메타도 같은 확장(마지막 우선) 기준으로 — 통 덮어쓰기 모델과 정합.
|
||||
$extStructuredMeta = $this->normalizeMeta($this->safeCall($instance, 'seoStructuredDataMeta', [$pageType]), $locale);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. effective og — 레이아웃 값(채워졌으면) ?? 모듈 declaration. 출처 계산.
|
||||
// own(자체 선언)분을 함께 넘겨 병합본 키가 base 상속인지 자체 override 인지 구분(SEO-B).
|
||||
$ownDeclaredOg = is_array($ownSeo) ? ($ownSeo['og'] ?? []) : null;
|
||||
$ownDeclaredTwitter = is_array($ownSeo) ? ($ownSeo['twitter'] ?? []) : null;
|
||||
$og = $this->buildKeyCascade($layoutOg, $layoutDeclaredOg, $extOg, $extOgOwner, 'core.seo.filter_og_data', $context, $seoConfig, $ownDeclaredOg, $extOgMeta);
|
||||
$twitter = $this->buildKeyCascade($layoutTwitter, $layoutDeclaredTwitter, $extTwitter, [], 'core.seo.filter_twitter_data', $context, $seoConfig, $ownDeclaredTwitter, $extTwitterMeta);
|
||||
|
||||
// 4. structured — 통 덮어쓰기 모델.
|
||||
$structured = $this->buildStructuredPreview($seoConfig, $extStructured, $context, $extStructuredMeta);
|
||||
|
||||
return [
|
||||
'defaultsAvailable' => $defaultsAvailable,
|
||||
'missing' => $missing,
|
||||
'og' => $og,
|
||||
'twitter' => $twitter,
|
||||
'structured' => $structured,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* og/twitter 키별 cascade + 필터 전/후 diff 로 출처·잠김을 계산합니다.
|
||||
*
|
||||
* @param array $base resolveOgData/resolveTwitterData 결과(레이아웃+코어)
|
||||
* @param array $layoutDeclared 레이아웃이 직접 선언한 og/twitter 키(override 표시)
|
||||
* @param array $extDefaults 모듈 declaration (빈 키 채움)
|
||||
* @param array $extOwner key => 'type:id' (모듈 출처)
|
||||
* @param string $filterHook 필터 훅명
|
||||
* @param array $context 컨텍스트
|
||||
* @param array $seoConfig meta.seo
|
||||
* @param array|null $ownDeclared 이 레이아웃이 직접 선언한 키(base 병합 전). 병합본에는
|
||||
* 있으나 own 에 없는 키 = base 상속(source='inherited').
|
||||
* null 이면 상속/자체 구분 안 함(종전 동작).
|
||||
* @param array $extMeta key => {expr, label} — 모듈 자동값의 데이터 경로 메타(연결 칩).
|
||||
* 출처가 module 인 키에만 sourceExpr/label 동반.
|
||||
* @return array<int, array{key, effectiveValue, source, overriddenByLayout, inheritedFromBase, lockedByFilter, sourceExpr?, label?}>
|
||||
*/
|
||||
private function buildKeyCascade(array $base, array $layoutDeclared, array $extDefaults, array $extOwner, string $filterHook, array $context, array $seoConfig, ?array $ownDeclared = null, array $extMeta = []): array
|
||||
{
|
||||
// fillEmptyKeys 정합 — base 의 빈 키를 모듈 declaration 으로 채움.
|
||||
$filled = $base;
|
||||
foreach ($extDefaults as $k => $v) {
|
||||
if ($this->isEmpty($filled[$k] ?? null) && ! $this->isEmpty($v)) {
|
||||
$filled[$k] = $v;
|
||||
}
|
||||
}
|
||||
|
||||
// 필터 전/후 diff 로 잠긴 키 식별.
|
||||
$hookCtx = ['context' => $context, 'pageType' => $seoConfig['page_type'] ?? null];
|
||||
$afterFilter = HookManager::applyFilters($filterHook, $filled, $hookCtx);
|
||||
|
||||
$out = [];
|
||||
foreach ($filled as $key => $value) {
|
||||
if ($key === 'extra') {
|
||||
continue;
|
||||
}
|
||||
$overriddenByLayout = array_key_exists($key, $layoutDeclared) && ! $this->isEmpty($layoutDeclared[$key]);
|
||||
// base 상속 = 병합본(layoutDeclared)엔 있으나 이 레이아웃 own 엔 없는 키.
|
||||
// own 미전달($ownDeclared === null) 이면 상속/자체 구분 안 함(종전 동작).
|
||||
$inheritedFromBase = $overriddenByLayout
|
||||
&& $ownDeclared !== null
|
||||
&& ! (array_key_exists($key, $ownDeclared) && ! $this->isEmpty($ownDeclared[$key]));
|
||||
$locked = is_array($afterFilter) && array_key_exists($key, $afterFilter) && $afterFilter[$key] !== $value;
|
||||
|
||||
// 출처 — filter 잠김 > base 상속 > layout override > module declaration > core(base 선점).
|
||||
if ($locked) {
|
||||
$source = 'filter';
|
||||
} elseif ($inheritedFromBase) {
|
||||
$source = 'inherited';
|
||||
} elseif ($overriddenByLayout) {
|
||||
$source = 'layout';
|
||||
} elseif (isset($extOwner[$key]) && ($filled[$key] ?? null) === ($extDefaults[$key] ?? null)) {
|
||||
$source = 'module:'.explode(':', $extOwner[$key])[1];
|
||||
} else {
|
||||
$source = 'core';
|
||||
}
|
||||
|
||||
$row = [
|
||||
'key' => $key,
|
||||
'effectiveValue' => $locked ? ($afterFilter[$key] ?? $value) : $value,
|
||||
'source' => $source,
|
||||
// overriddenByLayout = 이 레이아웃이 직접 덮었는가(상속은 false). 프론트의
|
||||
// "값 채우면 출처칩 사라짐" 판정이 이 플래그(+inherited 출처)에 종속.
|
||||
'overriddenByLayout' => $overriddenByLayout && ! $inheritedFromBase,
|
||||
'inheritedFromBase' => $inheritedFromBase,
|
||||
'lockedByFilter' => $locked,
|
||||
];
|
||||
|
||||
// 출처가 module 이고 그 키에 데이터 경로 메타가 있으면 연결 칩 정보 동반.
|
||||
// 편집기는 effectiveValue(평문) 대신 sourceExpr 칩 + label 로 "어느 데이터인지" 표시하고
|
||||
// 그 자리에서 다른 데이터로 교체할 수 있게 한다. 레이아웃 override/잠김 키엔 미동반.
|
||||
if (str_starts_with($source, 'module:') && isset($extMeta[$key])) {
|
||||
$row['sourceExpr'] = $extMeta[$key]['expr'];
|
||||
$row['label'] = $extMeta[$key]['label'];
|
||||
}
|
||||
|
||||
$out[] = $row;
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* structured_data 미리보기 — 통 덮어쓰기 모델.
|
||||
*
|
||||
* @param array $seoConfig meta.seo
|
||||
* @param array|null $extStructured 모듈 declaration(마지막 확장 우선)
|
||||
* @param array $context 컨텍스트
|
||||
* @param array $autoMeta 점 경로 key => {expr, label} — 자동 블록의 데이터 경로 메타(연결 칩)
|
||||
* @return array{autoBlock: array|null, autoMeta: array, hasLayoutBlock: bool, lockedByFilter: bool, filteredBlock: array|null}
|
||||
*/
|
||||
private function buildStructuredPreview(array $seoConfig, ?array $extStructured, array $context, array $autoMeta = []): array
|
||||
{
|
||||
$layoutBlock = $seoConfig['structured_data'] ?? null;
|
||||
$hasLayoutBlock = ! empty($layoutBlock);
|
||||
|
||||
// 통 덮어쓰기: 레이아웃 선언 있으면 그것, 없으면 모듈 declaration.
|
||||
$effective = $hasLayoutBlock ? $layoutBlock : $extStructured;
|
||||
|
||||
// 필터 전/후 전체 블록 diff(통 override — 등록=전체 lock).
|
||||
$hookCtx = ['context' => $context, 'pageType' => $seoConfig['page_type'] ?? null];
|
||||
$afterFilter = HookManager::applyFilters('core.seo.filter_structured_data', $effective, $hookCtx);
|
||||
$locked = $afterFilter !== $effective && ! empty($afterFilter);
|
||||
|
||||
return [
|
||||
// 토글 OFF 시 보여줄 모듈 자동 블록(읽기전용 미리보기).
|
||||
'autoBlock' => $extStructured,
|
||||
// 자동 블록 점 경로 키별 데이터 경로 메타(연결 칩) — 모듈 자동값일 때만 비지 않음.
|
||||
'autoMeta' => $autoMeta,
|
||||
'hasLayoutBlock' => $hasLayoutBlock,
|
||||
'lockedByFilter' => $locked,
|
||||
'filteredBlock' => $locked ? $afterFilter : null,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 모듈 *Meta 선언을 정규화합니다 — label 을 현재 로케일 평문으로 해석.
|
||||
*
|
||||
* label 은 두 형태를 허용한다(권장 순):
|
||||
* 1. **번역 키 문자열**(`'sirsoft-ecommerce::seo.product_name'`) — `__()` 로 해석한다.
|
||||
* 모듈 lang 파일(+번들 언어팩)이 그 키를 번역하므로 **추가 언어(ja 등)에 자동 대응**한다(권장).
|
||||
* 2. 인라인 다국어 맵(`['ko' => '상품 이름', 'en' => '...']`) — 맵에서 로케일 픽(하위호환).
|
||||
* ko/en 만 담기면 그 외 로케일은 en 폴백(언어팩 미대응 — 권장하지 않음).
|
||||
*
|
||||
* `['image' => ['expr' => '{{...}}', 'label' => 'pkg::seo.image']]`
|
||||
* → `['image' => ['expr' => '{{...}}', 'label' => '상품 이미지'(해석값)]]`. expr 누락/비문자열 키는 버림.
|
||||
*
|
||||
* @param mixed $meta 모듈 *Meta 반환값(키 => {expr, label})
|
||||
* @param string $locale 라벨 해석 로케일
|
||||
* @return array<string, array{expr: string, label: string}> 정규화된 메타
|
||||
*/
|
||||
private function normalizeMeta(mixed $meta, string $locale): array
|
||||
{
|
||||
if (! is_array($meta)) {
|
||||
return [];
|
||||
}
|
||||
$out = [];
|
||||
foreach ($meta as $key => $def) {
|
||||
if (! is_array($def) || ! is_string($def['expr'] ?? null) || $def['expr'] === '') {
|
||||
continue;
|
||||
}
|
||||
$label = $def['label'] ?? '';
|
||||
if (is_string($label) && $label !== '') {
|
||||
// 번역 키 — 요청 로케일로 __() 해석(언어팩 대응). 미등록 키면 Laravel 폴백
|
||||
// (fallback_locale) 후에도 못 찾으면 키 원문을 반환하므로, 그 경우만 빈 문자열로 둔다.
|
||||
$resolved = __($label, [], $locale);
|
||||
$label = (is_string($resolved) && $resolved !== $label) ? $resolved : '';
|
||||
} elseif (is_array($label)) {
|
||||
// 하위호환 — 인라인 다국어 맵.
|
||||
$label = $label[$locale] ?? $label['en'] ?? reset($label) ?: '';
|
||||
}
|
||||
$out[$key] = ['expr' => $def['expr'], 'label' => (string) $label];
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* 확장 인스턴스를 조회합니다.
|
||||
*
|
||||
* @param string|null $type module|plugin
|
||||
* @param string|null $id 식별자
|
||||
* @return object|null 인스턴스 또는 null
|
||||
*/
|
||||
private function resolveInstance(?string $type, ?string $id): ?object
|
||||
{
|
||||
if (! is_string($type) || ! is_string($id)) {
|
||||
return null;
|
||||
}
|
||||
if ($type === 'module') {
|
||||
return $this->moduleManager->getModule($id);
|
||||
}
|
||||
if ($type === 'plugin') {
|
||||
return $this->pluginManager->getPlugin($id);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 확장 메서드를 격리 호출합니다.
|
||||
*
|
||||
* @param object $instance 확장 인스턴스
|
||||
* @param string $method 메서드명
|
||||
* @param array $args 인자
|
||||
* @return mixed 결과 또는 빈 배열
|
||||
*/
|
||||
private function safeCall(object $instance, string $method, array $args): mixed
|
||||
{
|
||||
if (! method_exists($instance, $method)) {
|
||||
return [];
|
||||
}
|
||||
try {
|
||||
return $instance->{$method}(...$args);
|
||||
} catch (\Throwable) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 값이 비었는지(null/빈 문자열/빈 배열) 판정합니다.
|
||||
*
|
||||
* @param mixed $value 값
|
||||
* @return bool 비었으면 true
|
||||
*/
|
||||
private function isEmpty(mixed $value): bool
|
||||
{
|
||||
return $value === null || $value === '' || $value === [];
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user