feat(exclusions): Implement component exclusion system (Plan 99.11)
Adds ability to exclude components from specific: - Categories (by slug or term_id) - Post/Page IDs - URL patterns (substring or regex) Architecture: - Domain: Value Objects (CategoryExclusion, PostIdExclusion, UrlPatternExclusion, ExclusionRuleSet) + Contracts - Application: EvaluateExclusionsUseCase + EvaluateComponentVisibilityUseCase (orchestrator) - Infrastructure: WordPressExclusionRepository, WordPressPageContextProvider, WordPressServerRequestProvider - Admin: ExclusionFormPartial (reusable UI), ExclusionFieldProcessor, JS toggle The PageVisibilityHelper now uses the orchestrator UseCase that combines page-type visibility (Plan 99.10) with exclusion rules. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,65 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace ROITheme\Admin\Shared\Infrastructure\Services;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Servicio para procesar campos de exclusion antes de guardar en BD
|
||||||
|
*
|
||||||
|
* Convierte formatos de UI a JSON para almacenamiento.
|
||||||
|
*
|
||||||
|
* v1.1: Extraido de AdminAjaxHandler (SRP)
|
||||||
|
*
|
||||||
|
* @package ROITheme\Admin\Shared\Infrastructure\Services
|
||||||
|
*/
|
||||||
|
final class ExclusionFieldProcessor
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Procesa un valor de campo de exclusion segun su tipo
|
||||||
|
*
|
||||||
|
* @param string $value Valor del campo (desde UI)
|
||||||
|
* @param string $type Tipo de campo: json_array, json_array_int, json_array_lines
|
||||||
|
* @return string JSON string para almacenar en BD
|
||||||
|
*/
|
||||||
|
public function process(string $value, string $type): string
|
||||||
|
{
|
||||||
|
return match ($type) {
|
||||||
|
'json_array' => $this->processJsonArray($value),
|
||||||
|
'json_array_int' => $this->processJsonArrayInt($value),
|
||||||
|
'json_array_lines' => $this->processJsonArrayLines($value),
|
||||||
|
default => $value,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* "a, b, c" -> ["a", "b", "c"]
|
||||||
|
*/
|
||||||
|
private function processJsonArray(string $value): string
|
||||||
|
{
|
||||||
|
$items = array_map('trim', explode(',', $value));
|
||||||
|
$items = array_filter($items, fn($item) => $item !== '');
|
||||||
|
return json_encode(array_values($items), JSON_UNESCAPED_UNICODE);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* "1, 2, 3" -> [1, 2, 3]
|
||||||
|
*/
|
||||||
|
private function processJsonArrayInt(string $value): string
|
||||||
|
{
|
||||||
|
$items = array_map('trim', explode(',', $value));
|
||||||
|
$items = array_filter($items, 'is_numeric');
|
||||||
|
$items = array_map('intval', $items);
|
||||||
|
return json_encode(array_values($items));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lineas separadas -> array
|
||||||
|
*/
|
||||||
|
private function processJsonArrayLines(string $value): string
|
||||||
|
{
|
||||||
|
$items = preg_split('/\r\n|\r|\n/', $value);
|
||||||
|
$items = array_map('trim', $items);
|
||||||
|
$items = array_filter($items, fn($item) => $item !== '');
|
||||||
|
return json_encode(array_values($items), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
|
||||||
|
}
|
||||||
|
}
|
||||||
31
Admin/Shared/Infrastructure/Ui/Assets/Js/exclusion-toggle.js
Normal file
31
Admin/Shared/Infrastructure/Ui/Assets/Js/exclusion-toggle.js
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
/**
|
||||||
|
* Toggle para mostrar/ocultar reglas de exclusion en FormBuilders
|
||||||
|
*
|
||||||
|
* Escucha cambios en checkboxes con ID que termine en "ExclusionsEnabled"
|
||||||
|
* y muestra/oculta el contenedor de reglas correspondiente.
|
||||||
|
*
|
||||||
|
* @package ROITheme\Admin
|
||||||
|
*/
|
||||||
|
(function() {
|
||||||
|
'use strict';
|
||||||
|
|
||||||
|
function initExclusionToggles() {
|
||||||
|
document.querySelectorAll('[id$="ExclusionsEnabled"]').forEach(function(checkbox) {
|
||||||
|
// Handler para cambios
|
||||||
|
checkbox.addEventListener('change', function() {
|
||||||
|
const prefix = this.id.replace('ExclusionsEnabled', '');
|
||||||
|
const rulesContainer = document.getElementById(prefix + 'ExclusionRules');
|
||||||
|
if (rulesContainer) {
|
||||||
|
rulesContainer.style.display = this.checked ? 'block' : 'none';
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Inicializar cuando DOM este listo
|
||||||
|
if (document.readyState === 'loading') {
|
||||||
|
document.addEventListener('DOMContentLoaded', initExclusionToggles);
|
||||||
|
} else {
|
||||||
|
initExclusionToggles();
|
||||||
|
}
|
||||||
|
})();
|
||||||
244
Admin/Shared/Infrastructure/Ui/ExclusionFormPartial.php
Normal file
244
Admin/Shared/Infrastructure/Ui/ExclusionFormPartial.php
Normal file
@@ -0,0 +1,244 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace ROITheme\Admin\Shared\Infrastructure\Ui;
|
||||||
|
|
||||||
|
use ROITheme\Admin\Infrastructure\Ui\AdminDashboardRenderer;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Componente UI parcial reutilizable para reglas de exclusion
|
||||||
|
*
|
||||||
|
* Genera el HTML para la seccion de exclusiones en FormBuilders.
|
||||||
|
* Debe ser incluido despues de la seccion de visibilidad por tipo de pagina.
|
||||||
|
*
|
||||||
|
* Uso en FormBuilder:
|
||||||
|
* ```php
|
||||||
|
* $exclusionPartial = new ExclusionFormPartial($this->renderer);
|
||||||
|
* $html .= $exclusionPartial->render($componentId, 'prefijo');
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @package ROITheme\Admin\Shared\Infrastructure\Ui
|
||||||
|
*/
|
||||||
|
final class ExclusionFormPartial
|
||||||
|
{
|
||||||
|
private const GROUP_NAME = '_exclusions';
|
||||||
|
|
||||||
|
public function __construct(
|
||||||
|
private readonly AdminDashboardRenderer $renderer
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Renderiza la seccion de exclusiones
|
||||||
|
*
|
||||||
|
* @param string $componentId ID del componente (kebab-case)
|
||||||
|
* @param string $prefix Prefijo para IDs de campos (ej: 'cta' genera 'ctaExclusionsEnabled')
|
||||||
|
* @return string HTML de la seccion
|
||||||
|
*/
|
||||||
|
public function render(string $componentId, string $prefix): string
|
||||||
|
{
|
||||||
|
$html = '';
|
||||||
|
|
||||||
|
$html .= $this->buildExclusionHeader();
|
||||||
|
$html .= $this->buildExclusionToggle($componentId, $prefix);
|
||||||
|
$html .= $this->buildExclusionRules($componentId, $prefix);
|
||||||
|
|
||||||
|
return $html;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function buildExclusionHeader(): string
|
||||||
|
{
|
||||||
|
$html = '<hr class="my-3">';
|
||||||
|
$html .= '<p class="small fw-semibold mb-2">';
|
||||||
|
$html .= ' <i class="bi bi-funnel me-1" style="color: #FF8600;"></i>';
|
||||||
|
$html .= ' Reglas de exclusion avanzadas';
|
||||||
|
$html .= '</p>';
|
||||||
|
$html .= '<p class="small text-muted mb-2">';
|
||||||
|
$html .= ' Excluir este componente de categorias, posts o URLs especificos.';
|
||||||
|
$html .= '</p>';
|
||||||
|
|
||||||
|
return $html;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function buildExclusionToggle(string $componentId, string $prefix): string
|
||||||
|
{
|
||||||
|
$enabled = $this->renderer->getFieldValue(
|
||||||
|
$componentId,
|
||||||
|
self::GROUP_NAME,
|
||||||
|
'exclusions_enabled',
|
||||||
|
false
|
||||||
|
);
|
||||||
|
$checked = $this->toBool($enabled);
|
||||||
|
|
||||||
|
$id = $prefix . 'ExclusionsEnabled';
|
||||||
|
|
||||||
|
$html = '<div class="mb-3">';
|
||||||
|
$html .= ' <div class="form-check form-switch">';
|
||||||
|
$html .= sprintf(
|
||||||
|
' <input class="form-check-input" type="checkbox" id="%s" %s>',
|
||||||
|
esc_attr($id),
|
||||||
|
$checked ? 'checked' : ''
|
||||||
|
);
|
||||||
|
$html .= sprintf(
|
||||||
|
' <label class="form-check-label small" for="%s">',
|
||||||
|
esc_attr($id)
|
||||||
|
);
|
||||||
|
$html .= ' <i class="bi bi-filter-circle me-1" style="color: #FF8600;"></i>';
|
||||||
|
$html .= ' <strong>Activar reglas de exclusion</strong>';
|
||||||
|
$html .= ' </label>';
|
||||||
|
$html .= ' </div>';
|
||||||
|
$html .= '</div>';
|
||||||
|
|
||||||
|
return $html;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function buildExclusionRules(string $componentId, string $prefix): string
|
||||||
|
{
|
||||||
|
$enabled = $this->renderer->getFieldValue(
|
||||||
|
$componentId,
|
||||||
|
self::GROUP_NAME,
|
||||||
|
'exclusions_enabled',
|
||||||
|
false
|
||||||
|
);
|
||||||
|
$display = $this->toBool($enabled) ? 'block' : 'none';
|
||||||
|
|
||||||
|
$html = sprintf(
|
||||||
|
'<div id="%sExclusionRules" style="display: %s;">',
|
||||||
|
esc_attr($prefix),
|
||||||
|
$display
|
||||||
|
);
|
||||||
|
|
||||||
|
$html .= $this->buildCategoryField($componentId, $prefix);
|
||||||
|
$html .= $this->buildPostIdsField($componentId, $prefix);
|
||||||
|
$html .= $this->buildUrlPatternsField($componentId, $prefix);
|
||||||
|
|
||||||
|
$html .= '</div>';
|
||||||
|
|
||||||
|
return $html;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function buildCategoryField(string $componentId, string $prefix): string
|
||||||
|
{
|
||||||
|
$value = $this->renderer->getFieldValue(
|
||||||
|
$componentId,
|
||||||
|
self::GROUP_NAME,
|
||||||
|
'exclude_categories',
|
||||||
|
'[]'
|
||||||
|
);
|
||||||
|
$categories = $this->jsonToCommaList($value);
|
||||||
|
|
||||||
|
$id = $prefix . 'ExcludeCategories';
|
||||||
|
|
||||||
|
$html = '<div class="mb-3">';
|
||||||
|
$html .= sprintf(
|
||||||
|
' <label for="%s" class="form-label small mb-1 fw-semibold">',
|
||||||
|
esc_attr($id)
|
||||||
|
);
|
||||||
|
$html .= ' <i class="bi bi-folder me-1" style="color: #FF8600;"></i>';
|
||||||
|
$html .= ' Excluir en categorias';
|
||||||
|
$html .= ' </label>';
|
||||||
|
$html .= sprintf(
|
||||||
|
' <input type="text" id="%s" class="form-control form-control-sm" value="%s" placeholder="noticias, eventos, tutoriales">',
|
||||||
|
esc_attr($id),
|
||||||
|
esc_attr($categories)
|
||||||
|
);
|
||||||
|
$html .= ' <small class="text-muted">Slugs de categorias separados por comas</small>';
|
||||||
|
$html .= '</div>';
|
||||||
|
|
||||||
|
return $html;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function buildPostIdsField(string $componentId, string $prefix): string
|
||||||
|
{
|
||||||
|
$value = $this->renderer->getFieldValue(
|
||||||
|
$componentId,
|
||||||
|
self::GROUP_NAME,
|
||||||
|
'exclude_post_ids',
|
||||||
|
'[]'
|
||||||
|
);
|
||||||
|
$postIds = $this->jsonToCommaList($value);
|
||||||
|
|
||||||
|
$id = $prefix . 'ExcludePostIds';
|
||||||
|
|
||||||
|
$html = '<div class="mb-3">';
|
||||||
|
$html .= sprintf(
|
||||||
|
' <label for="%s" class="form-label small mb-1 fw-semibold">',
|
||||||
|
esc_attr($id)
|
||||||
|
);
|
||||||
|
$html .= ' <i class="bi bi-hash me-1" style="color: #FF8600;"></i>';
|
||||||
|
$html .= ' Excluir en posts/paginas';
|
||||||
|
$html .= ' </label>';
|
||||||
|
$html .= sprintf(
|
||||||
|
' <input type="text" id="%s" class="form-control form-control-sm" value="%s" placeholder="123, 456, 789">',
|
||||||
|
esc_attr($id),
|
||||||
|
esc_attr($postIds)
|
||||||
|
);
|
||||||
|
$html .= ' <small class="text-muted">IDs de posts o paginas separados por comas</small>';
|
||||||
|
$html .= '</div>';
|
||||||
|
|
||||||
|
return $html;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function buildUrlPatternsField(string $componentId, string $prefix): string
|
||||||
|
{
|
||||||
|
$value = $this->renderer->getFieldValue(
|
||||||
|
$componentId,
|
||||||
|
self::GROUP_NAME,
|
||||||
|
'exclude_url_patterns',
|
||||||
|
'[]'
|
||||||
|
);
|
||||||
|
$patterns = $this->jsonToLineList($value);
|
||||||
|
|
||||||
|
$id = $prefix . 'ExcludeUrlPatterns';
|
||||||
|
|
||||||
|
$html = '<div class="mb-0">';
|
||||||
|
$html .= sprintf(
|
||||||
|
' <label for="%s" class="form-label small mb-1 fw-semibold">',
|
||||||
|
esc_attr($id)
|
||||||
|
);
|
||||||
|
$html .= ' <i class="bi bi-link-45deg me-1" style="color: #FF8600;"></i>';
|
||||||
|
$html .= ' Excluir por patrones URL';
|
||||||
|
$html .= ' </label>';
|
||||||
|
$html .= sprintf(
|
||||||
|
' <textarea id="%s" class="form-control form-control-sm" rows="3" placeholder="/privado/ /landing-especial/ /^\/categoria\/\d+$/">%s</textarea>',
|
||||||
|
esc_attr($id),
|
||||||
|
esc_textarea($patterns)
|
||||||
|
);
|
||||||
|
$html .= ' <small class="text-muted">Un patron por linea. Soporta texto simple o regex (ej: /^\/blog\/\d+$/)</small>';
|
||||||
|
$html .= '</div>';
|
||||||
|
|
||||||
|
return $html;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convierte JSON array a lista separada por comas
|
||||||
|
*/
|
||||||
|
private function jsonToCommaList(string $json): string
|
||||||
|
{
|
||||||
|
$decoded = json_decode($json, true);
|
||||||
|
|
||||||
|
if (!is_array($decoded) || empty($decoded)) {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
return implode(', ', $decoded);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convierte JSON array a lista separada por lineas
|
||||||
|
*/
|
||||||
|
private function jsonToLineList(string $json): string
|
||||||
|
{
|
||||||
|
$decoded = json_decode($json, true);
|
||||||
|
|
||||||
|
if (!is_array($decoded) || empty($decoded)) {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
return implode("\n", $decoded);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function toBool(mixed $value): bool
|
||||||
|
{
|
||||||
|
return $value === true || $value === '1' || $value === 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace ROITheme\Shared\Application\UseCases\EvaluateComponentVisibility;
|
||||||
|
|
||||||
|
use ROITheme\Shared\Application\UseCases\EvaluatePageVisibility\EvaluatePageVisibilityUseCase;
|
||||||
|
use ROITheme\Shared\Application\UseCases\EvaluateExclusions\EvaluateExclusionsUseCase;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Caso de uso: Evaluar visibilidad completa de un componente
|
||||||
|
*
|
||||||
|
* Orquesta la evaluacion de:
|
||||||
|
* 1. Visibilidad por tipo de pagina (Plan 99.10)
|
||||||
|
* 2. Reglas de exclusion (Plan 99.11)
|
||||||
|
*
|
||||||
|
* El componente se muestra SOLO si:
|
||||||
|
* - Pasa la verificacion de tipo de pagina
|
||||||
|
* - NO esta excluido por ninguna regla
|
||||||
|
*
|
||||||
|
* PATRON: Facade/Orchestrator - combina dos UseCases
|
||||||
|
*
|
||||||
|
* @package ROITheme\Shared\Application\UseCases\EvaluateComponentVisibility
|
||||||
|
*/
|
||||||
|
final class EvaluateComponentVisibilityUseCase
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
private readonly EvaluatePageVisibilityUseCase $pageVisibilityUseCase,
|
||||||
|
private readonly EvaluateExclusionsUseCase $exclusionsUseCase
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Evalua si el componente debe mostrarse en la pagina actual
|
||||||
|
*
|
||||||
|
* @param string $componentName Nombre del componente (kebab-case)
|
||||||
|
* @return bool True si debe mostrarse
|
||||||
|
*/
|
||||||
|
public function execute(string $componentName): bool
|
||||||
|
{
|
||||||
|
// Paso 1: Verificar visibilidad por tipo de pagina
|
||||||
|
$visibleByPageType = $this->pageVisibilityUseCase->execute($componentName);
|
||||||
|
|
||||||
|
if (!$visibleByPageType) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Paso 2: Verificar exclusiones
|
||||||
|
$isExcluded = $this->exclusionsUseCase->execute($componentName);
|
||||||
|
|
||||||
|
// Mostrar si NO esta excluido
|
||||||
|
return !$isExcluded;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace ROITheme\Shared\Application\UseCases\EvaluateExclusions;
|
||||||
|
|
||||||
|
use ROITheme\Shared\Domain\Contracts\ExclusionRepositoryInterface;
|
||||||
|
use ROITheme\Shared\Domain\Contracts\PageContextProviderInterface;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Caso de uso: Evaluar si un componente debe excluirse en la pagina actual
|
||||||
|
*
|
||||||
|
* Obtiene las reglas de exclusion del repositorio y evalua si aplican
|
||||||
|
* al contexto actual (post ID, categorias, URL).
|
||||||
|
*
|
||||||
|
* DIP: Depende de interfaces, no implementaciones.
|
||||||
|
*
|
||||||
|
* @package ROITheme\Shared\Application\UseCases\EvaluateExclusions
|
||||||
|
*/
|
||||||
|
final class EvaluateExclusionsUseCase
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
private readonly ExclusionRepositoryInterface $exclusionRepository,
|
||||||
|
private readonly PageContextProviderInterface $contextProvider
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Evalua si el componente debe excluirse
|
||||||
|
*
|
||||||
|
* @param string $componentName Nombre del componente (kebab-case)
|
||||||
|
* @return bool True si debe EXCLUIRSE (NO mostrar)
|
||||||
|
*/
|
||||||
|
public function execute(string $componentName): bool
|
||||||
|
{
|
||||||
|
$exclusions = $this->exclusionRepository->getExclusions($componentName);
|
||||||
|
|
||||||
|
if (!$exclusions->isEnabled()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$context = $this->contextProvider->getCurrentContext();
|
||||||
|
|
||||||
|
return $exclusions->shouldExclude($context);
|
||||||
|
}
|
||||||
|
}
|
||||||
37
Shared/Domain/Constants/ExclusionDefaults.php
Normal file
37
Shared/Domain/Constants/ExclusionDefaults.php
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace ROITheme\Shared\Domain\Constants;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Constantes de exclusion por defecto para componentes
|
||||||
|
*
|
||||||
|
* @package ROITheme\Shared\Domain\Constants
|
||||||
|
*/
|
||||||
|
final class ExclusionDefaults
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Configuracion de exclusion por defecto (sin exclusiones)
|
||||||
|
*/
|
||||||
|
public const DEFAULT_EXCLUSIONS = [
|
||||||
|
'exclusions_enabled' => false,
|
||||||
|
'exclude_categories' => '[]',
|
||||||
|
'exclude_post_ids' => '[]',
|
||||||
|
'exclude_url_patterns' => '[]',
|
||||||
|
];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lista de campos de exclusion validos
|
||||||
|
*/
|
||||||
|
public const EXCLUSION_FIELDS = [
|
||||||
|
'exclusions_enabled',
|
||||||
|
'exclude_categories',
|
||||||
|
'exclude_post_ids',
|
||||||
|
'exclude_url_patterns',
|
||||||
|
];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Nombre del grupo en BD
|
||||||
|
*/
|
||||||
|
public const GROUP_NAME = '_exclusions';
|
||||||
|
}
|
||||||
36
Shared/Domain/Contracts/ExclusionRepositoryInterface.php
Normal file
36
Shared/Domain/Contracts/ExclusionRepositoryInterface.php
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace ROITheme\Shared\Domain\Contracts;
|
||||||
|
|
||||||
|
use ROITheme\Shared\Domain\ValueObjects\ExclusionRuleSet;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Contrato para acceder a la configuracion de exclusiones
|
||||||
|
*
|
||||||
|
* Metodos: 3 (cumple ISP < 5 metodos)
|
||||||
|
*
|
||||||
|
* @package ROITheme\Shared\Domain\Contracts
|
||||||
|
*/
|
||||||
|
interface ExclusionRepositoryInterface
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Obtiene las exclusiones configuradas para un componente
|
||||||
|
*
|
||||||
|
* @param string $componentName Nombre del componente (kebab-case)
|
||||||
|
* @return ExclusionRuleSet Configuracion de exclusiones
|
||||||
|
*/
|
||||||
|
public function getExclusions(string $componentName): ExclusionRuleSet;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Guarda la configuracion de exclusiones de un componente
|
||||||
|
*
|
||||||
|
* @param ExclusionRuleSet $exclusions Configuracion a guardar
|
||||||
|
*/
|
||||||
|
public function saveExclusions(ExclusionRuleSet $exclusions): void;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verifica si existe configuracion de exclusiones para un componente
|
||||||
|
*/
|
||||||
|
public function hasExclusions(string $componentName): bool;
|
||||||
|
}
|
||||||
33
Shared/Domain/Contracts/PageContextProviderInterface.php
Normal file
33
Shared/Domain/Contracts/PageContextProviderInterface.php
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace ROITheme\Shared\Domain\Contracts;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Contrato para obtener el contexto de la pagina actual
|
||||||
|
*
|
||||||
|
* Abstrae la obtencion de datos del contexto actual (WordPress).
|
||||||
|
* Permite testear UseCases sin dependencia de WordPress.
|
||||||
|
*
|
||||||
|
* v1.1: Renombrado de ExclusionEvaluatorInterface (nombre semantico incorrecto)
|
||||||
|
* El nombre refleja que PROVEE contexto, no que EVALUA.
|
||||||
|
*
|
||||||
|
* Metodos: 1 (cumple ISP < 5 metodos)
|
||||||
|
*
|
||||||
|
* @package ROITheme\Shared\Domain\Contracts
|
||||||
|
*/
|
||||||
|
interface PageContextProviderInterface
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Obtiene el contexto actual para evaluacion de exclusiones
|
||||||
|
*
|
||||||
|
* @return array{
|
||||||
|
* post_id: int,
|
||||||
|
* categories: array<array{term_id: int, slug: string, name: string}>,
|
||||||
|
* url: string,
|
||||||
|
* request_uri: string,
|
||||||
|
* post_type: string
|
||||||
|
* }
|
||||||
|
*/
|
||||||
|
public function getCurrentContext(): array;
|
||||||
|
}
|
||||||
27
Shared/Domain/Contracts/ServerRequestProviderInterface.php
Normal file
27
Shared/Domain/Contracts/ServerRequestProviderInterface.php
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace ROITheme\Shared\Domain\Contracts;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Contrato para obtener datos del request HTTP
|
||||||
|
*
|
||||||
|
* Encapsula el acceso a $_SERVER para:
|
||||||
|
* - Evitar acceso directo a superglobales en Infrastructure
|
||||||
|
* - Permitir testear sin dependencia de $_SERVER
|
||||||
|
*
|
||||||
|
* v1.1: Nuevo - encapsular acceso a $_SERVER
|
||||||
|
*
|
||||||
|
* Metodos: 1 (cumple ISP < 5 metodos)
|
||||||
|
*
|
||||||
|
* @package ROITheme\Shared\Domain\Contracts
|
||||||
|
*/
|
||||||
|
interface ServerRequestProviderInterface
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Obtiene el Request URI actual
|
||||||
|
*
|
||||||
|
* @return string URI del request (ej: "/blog/mi-post/")
|
||||||
|
*/
|
||||||
|
public function getRequestUri(): string;
|
||||||
|
}
|
||||||
100
Shared/Domain/ValueObjects/CategoryExclusion.php
Normal file
100
Shared/Domain/ValueObjects/CategoryExclusion.php
Normal file
@@ -0,0 +1,100 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace ROITheme\Shared\Domain\ValueObjects;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Value Object: Exclusion por categoria
|
||||||
|
*
|
||||||
|
* Evalua si un post pertenece a alguna de las categorias excluidas.
|
||||||
|
* Soporta matching por slug o term_id.
|
||||||
|
*
|
||||||
|
* @package ROITheme\Shared\Domain\ValueObjects
|
||||||
|
*/
|
||||||
|
final class CategoryExclusion extends ExclusionRule
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @param array<int|string> $excludedCategories Lista de slugs o IDs de categorias
|
||||||
|
*/
|
||||||
|
public function __construct(
|
||||||
|
private readonly array $excludedCategories = []
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@inheritdoc}
|
||||||
|
*
|
||||||
|
* Contexto esperado:
|
||||||
|
* - categories: array<array{term_id: int, slug: string, name: string}>
|
||||||
|
*/
|
||||||
|
public function matches(array $context): bool
|
||||||
|
{
|
||||||
|
if (!$this->hasValues()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$postCategories = $context['categories'] ?? [];
|
||||||
|
|
||||||
|
if (empty($postCategories)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ($postCategories as $category) {
|
||||||
|
// Buscar por slug
|
||||||
|
if (in_array($category['slug'], $this->excludedCategories, true)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Buscar por term_id
|
||||||
|
if (in_array($category['term_id'], $this->excludedCategories, true)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Buscar por term_id como string (para comparaciones flexibles)
|
||||||
|
if (in_array((string) $category['term_id'], $this->excludedCategories, true)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function hasValues(): bool
|
||||||
|
{
|
||||||
|
return !empty($this->excludedCategories);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function serialize(): string
|
||||||
|
{
|
||||||
|
return json_encode($this->excludedCategories, JSON_UNESCAPED_UNICODE);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<int|string>
|
||||||
|
*/
|
||||||
|
public function getExcludedCategories(): array
|
||||||
|
{
|
||||||
|
return $this->excludedCategories;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Crea instancia desde JSON
|
||||||
|
*/
|
||||||
|
public static function fromJson(string $json): self
|
||||||
|
{
|
||||||
|
$decoded = json_decode($json, true);
|
||||||
|
|
||||||
|
if (!is_array($decoded)) {
|
||||||
|
return self::empty();
|
||||||
|
}
|
||||||
|
|
||||||
|
return new self($decoded);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Crea instancia vacia
|
||||||
|
*/
|
||||||
|
public static function empty(): self
|
||||||
|
{
|
||||||
|
return new self([]);
|
||||||
|
}
|
||||||
|
}
|
||||||
37
Shared/Domain/ValueObjects/ExclusionRule.php
Normal file
37
Shared/Domain/ValueObjects/ExclusionRule.php
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace ROITheme\Shared\Domain\ValueObjects;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Clase base abstracta para reglas de exclusion
|
||||||
|
*
|
||||||
|
* Define el contrato comun para todos los tipos de exclusion.
|
||||||
|
* Cada implementacion concreta define su logica de matching.
|
||||||
|
*
|
||||||
|
* @package ROITheme\Shared\Domain\ValueObjects
|
||||||
|
*/
|
||||||
|
abstract class ExclusionRule
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Evalua si el contexto actual coincide con la regla
|
||||||
|
*
|
||||||
|
* @param array<string, mixed> $context Contexto de la pagina actual
|
||||||
|
* @return bool True si el contexto coincide (debe excluirse)
|
||||||
|
*/
|
||||||
|
abstract public function matches(array $context): bool;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verifica si la regla tiene valores configurados
|
||||||
|
*
|
||||||
|
* @return bool True si hay valores configurados
|
||||||
|
*/
|
||||||
|
abstract public function hasValues(): bool;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Serializa los valores para almacenamiento
|
||||||
|
*
|
||||||
|
* @return string JSON string
|
||||||
|
*/
|
||||||
|
abstract public function serialize(): string;
|
||||||
|
}
|
||||||
100
Shared/Domain/ValueObjects/ExclusionRuleSet.php
Normal file
100
Shared/Domain/ValueObjects/ExclusionRuleSet.php
Normal file
@@ -0,0 +1,100 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace ROITheme\Shared\Domain\ValueObjects;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Value Object Compuesto: Conjunto de reglas de exclusion
|
||||||
|
*
|
||||||
|
* Agrupa todas las reglas de exclusion para un componente.
|
||||||
|
* Evalua con logica OR (si cualquier regla coincide, se excluye).
|
||||||
|
*
|
||||||
|
* @package ROITheme\Shared\Domain\ValueObjects
|
||||||
|
*/
|
||||||
|
final class ExclusionRuleSet
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
private readonly string $componentName,
|
||||||
|
private readonly bool $enabled,
|
||||||
|
private readonly CategoryExclusion $categoryExclusion,
|
||||||
|
private readonly PostIdExclusion $postIdExclusion,
|
||||||
|
private readonly UrlPatternExclusion $urlPatternExclusion
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Evalua si el componente debe excluirse segun el contexto actual
|
||||||
|
*
|
||||||
|
* @param array<string, mixed> $context Contexto de la pagina actual
|
||||||
|
* @return bool True si debe excluirse (NO mostrar)
|
||||||
|
*/
|
||||||
|
public function shouldExclude(array $context): bool
|
||||||
|
{
|
||||||
|
if (!$this->enabled) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Evaluar cada tipo de exclusion (OR logico)
|
||||||
|
if ($this->categoryExclusion->matches($context)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($this->postIdExclusion->matches($context)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($this->urlPatternExclusion->matches($context)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verifica si tiene alguna regla configurada
|
||||||
|
*/
|
||||||
|
public function hasAnyRule(): bool
|
||||||
|
{
|
||||||
|
return $this->categoryExclusion->hasValues()
|
||||||
|
|| $this->postIdExclusion->hasValues()
|
||||||
|
|| $this->urlPatternExclusion->hasValues();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getComponentName(): string
|
||||||
|
{
|
||||||
|
return $this->componentName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function isEnabled(): bool
|
||||||
|
{
|
||||||
|
return $this->enabled;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getCategoryExclusion(): CategoryExclusion
|
||||||
|
{
|
||||||
|
return $this->categoryExclusion;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getPostIdExclusion(): PostIdExclusion
|
||||||
|
{
|
||||||
|
return $this->postIdExclusion;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getUrlPatternExclusion(): UrlPatternExclusion
|
||||||
|
{
|
||||||
|
return $this->urlPatternExclusion;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Crea una instancia sin exclusiones (por defecto)
|
||||||
|
*/
|
||||||
|
public static function empty(string $componentName): self
|
||||||
|
{
|
||||||
|
return new self(
|
||||||
|
$componentName,
|
||||||
|
false,
|
||||||
|
CategoryExclusion::empty(),
|
||||||
|
PostIdExclusion::empty(),
|
||||||
|
UrlPatternExclusion::empty()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
86
Shared/Domain/ValueObjects/PostIdExclusion.php
Normal file
86
Shared/Domain/ValueObjects/PostIdExclusion.php
Normal file
@@ -0,0 +1,86 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace ROITheme\Shared\Domain\ValueObjects;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Value Object: Exclusion por ID de post/pagina
|
||||||
|
*
|
||||||
|
* Evalua si el post/pagina actual esta en la lista de IDs excluidos.
|
||||||
|
*
|
||||||
|
* @package ROITheme\Shared\Domain\ValueObjects
|
||||||
|
*/
|
||||||
|
final class PostIdExclusion extends ExclusionRule
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @param array<int> $excludedPostIds Lista de IDs de posts/paginas
|
||||||
|
*/
|
||||||
|
public function __construct(
|
||||||
|
private readonly array $excludedPostIds = []
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@inheritdoc}
|
||||||
|
*
|
||||||
|
* Contexto esperado:
|
||||||
|
* - post_id: int
|
||||||
|
*/
|
||||||
|
public function matches(array $context): bool
|
||||||
|
{
|
||||||
|
if (!$this->hasValues()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$postId = $context['post_id'] ?? 0;
|
||||||
|
|
||||||
|
if ($postId === 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return in_array($postId, $this->excludedPostIds, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function hasValues(): bool
|
||||||
|
{
|
||||||
|
return !empty($this->excludedPostIds);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function serialize(): string
|
||||||
|
{
|
||||||
|
return json_encode($this->excludedPostIds);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<int>
|
||||||
|
*/
|
||||||
|
public function getExcludedPostIds(): array
|
||||||
|
{
|
||||||
|
return $this->excludedPostIds;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Crea instancia desde JSON
|
||||||
|
*/
|
||||||
|
public static function fromJson(string $json): self
|
||||||
|
{
|
||||||
|
$decoded = json_decode($json, true);
|
||||||
|
|
||||||
|
if (!is_array($decoded)) {
|
||||||
|
return self::empty();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Asegurar que son enteros
|
||||||
|
$ids = array_map('intval', $decoded);
|
||||||
|
$ids = array_filter($ids, fn(int $id): bool => $id > 0);
|
||||||
|
|
||||||
|
return new self(array_values($ids));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Crea instancia vacia
|
||||||
|
*/
|
||||||
|
public static function empty(): self
|
||||||
|
{
|
||||||
|
return new self([]);
|
||||||
|
}
|
||||||
|
}
|
||||||
146
Shared/Domain/ValueObjects/UrlPatternExclusion.php
Normal file
146
Shared/Domain/ValueObjects/UrlPatternExclusion.php
Normal file
@@ -0,0 +1,146 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace ROITheme\Shared\Domain\ValueObjects;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Value Object: Exclusion por patron URL
|
||||||
|
*
|
||||||
|
* Evalua si la URL actual coincide con alguno de los patrones configurados.
|
||||||
|
* Soporta:
|
||||||
|
* - Substring simple: "/privado/" coincide con cualquier URL que contenga ese texto
|
||||||
|
* - Regex: Patrones que empiezan y terminan con "/" son evaluados como regex
|
||||||
|
*
|
||||||
|
* @package ROITheme\Shared\Domain\ValueObjects
|
||||||
|
*/
|
||||||
|
final class UrlPatternExclusion extends ExclusionRule
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @param array<string> $urlPatterns Lista de patrones (substring o regex)
|
||||||
|
*/
|
||||||
|
public function __construct(
|
||||||
|
private readonly array $urlPatterns = []
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* {@inheritdoc}
|
||||||
|
*
|
||||||
|
* Contexto esperado:
|
||||||
|
* - request_uri: string (URI del request)
|
||||||
|
* - url: string (URL completa, opcional)
|
||||||
|
*/
|
||||||
|
public function matches(array $context): bool
|
||||||
|
{
|
||||||
|
if (!$this->hasValues()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
$requestUri = $context['request_uri'] ?? '';
|
||||||
|
$url = $context['url'] ?? '';
|
||||||
|
|
||||||
|
if ($requestUri === '' && $url === '') {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ($this->urlPatterns as $pattern) {
|
||||||
|
if ($this->matchesPattern($pattern, $requestUri, $url)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Evalua si un patron coincide con el request_uri o url
|
||||||
|
*/
|
||||||
|
private function matchesPattern(string $pattern, string $requestUri, string $url): bool
|
||||||
|
{
|
||||||
|
// Detectar si es regex (empieza con /)
|
||||||
|
if ($this->isRegex($pattern)) {
|
||||||
|
return $this->matchesRegex($pattern, $requestUri);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Substring matching
|
||||||
|
return $this->matchesSubstring($pattern, $requestUri, $url);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Detecta si el patron es una expresion regular
|
||||||
|
*/
|
||||||
|
private function isRegex(string $pattern): bool
|
||||||
|
{
|
||||||
|
// Un patron regex debe empezar con / y terminar con / (posiblemente con flags)
|
||||||
|
return preg_match('#^/.+/[gimsux]*$#', $pattern) === 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Evalua coincidencia regex
|
||||||
|
*/
|
||||||
|
private function matchesRegex(string $pattern, string $subject): bool
|
||||||
|
{
|
||||||
|
// Suprimir warnings de regex invalidos
|
||||||
|
$result = @preg_match($pattern, $subject);
|
||||||
|
|
||||||
|
return $result === 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Evalua coincidencia por substring
|
||||||
|
*/
|
||||||
|
private function matchesSubstring(string $pattern, string $requestUri, string $url): bool
|
||||||
|
{
|
||||||
|
if ($requestUri !== '' && str_contains($requestUri, $pattern)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($url !== '' && str_contains($url, $pattern)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function hasValues(): bool
|
||||||
|
{
|
||||||
|
return !empty($this->urlPatterns);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function serialize(): string
|
||||||
|
{
|
||||||
|
return json_encode($this->urlPatterns, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<string>
|
||||||
|
*/
|
||||||
|
public function getUrlPatterns(): array
|
||||||
|
{
|
||||||
|
return $this->urlPatterns;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Crea instancia desde JSON
|
||||||
|
*/
|
||||||
|
public static function fromJson(string $json): self
|
||||||
|
{
|
||||||
|
$decoded = json_decode($json, true);
|
||||||
|
|
||||||
|
if (!is_array($decoded)) {
|
||||||
|
return self::empty();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Filtrar valores vacios
|
||||||
|
$patterns = array_filter($decoded, fn($p): bool => is_string($p) && $p !== '');
|
||||||
|
|
||||||
|
return new self(array_values($patterns));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Crea instancia vacia
|
||||||
|
*/
|
||||||
|
public static function empty(): self
|
||||||
|
{
|
||||||
|
return new self([]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -28,6 +28,15 @@ use ROITheme\Shared\Infrastructure\Services\WordPressPageTypeDetector;
|
|||||||
use ROITheme\Shared\Infrastructure\Persistence\WordPress\WordPressPageVisibilityRepository;
|
use ROITheme\Shared\Infrastructure\Persistence\WordPress\WordPressPageVisibilityRepository;
|
||||||
use ROITheme\Shared\Application\UseCases\EvaluatePageVisibility\EvaluatePageVisibilityUseCase;
|
use ROITheme\Shared\Application\UseCases\EvaluatePageVisibility\EvaluatePageVisibilityUseCase;
|
||||||
use ROITheme\Shared\Infrastructure\Services\MigratePageVisibilityService;
|
use ROITheme\Shared\Infrastructure\Services\MigratePageVisibilityService;
|
||||||
|
// Exclusion System (Plan 99.11)
|
||||||
|
use ROITheme\Shared\Domain\Contracts\ExclusionRepositoryInterface;
|
||||||
|
use ROITheme\Shared\Domain\Contracts\PageContextProviderInterface;
|
||||||
|
use ROITheme\Shared\Domain\Contracts\ServerRequestProviderInterface;
|
||||||
|
use ROITheme\Shared\Infrastructure\Persistence\WordPress\WordPressExclusionRepository;
|
||||||
|
use ROITheme\Shared\Infrastructure\Services\WordPressPageContextProvider;
|
||||||
|
use ROITheme\Shared\Infrastructure\Services\WordPressServerRequestProvider;
|
||||||
|
use ROITheme\Shared\Application\UseCases\EvaluateExclusions\EvaluateExclusionsUseCase;
|
||||||
|
use ROITheme\Shared\Application\UseCases\EvaluateComponentVisibility\EvaluateComponentVisibilityUseCase;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* DIContainer - Contenedor de Inyección de Dependencias
|
* DIContainer - Contenedor de Inyección de Dependencias
|
||||||
@@ -363,4 +372,75 @@ final class DIContainer
|
|||||||
}
|
}
|
||||||
return $this->instances['migratePageVisibilityService'];
|
return $this->instances['migratePageVisibilityService'];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ===============================
|
||||||
|
// Exclusion System (Plan 99.11)
|
||||||
|
// ===============================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Obtiene el proveedor de request HTTP
|
||||||
|
*
|
||||||
|
* Encapsula acceso a $_SERVER
|
||||||
|
*/
|
||||||
|
public function getServerRequestProvider(): ServerRequestProviderInterface
|
||||||
|
{
|
||||||
|
if (!isset($this->instances['serverRequestProvider'])) {
|
||||||
|
$this->instances['serverRequestProvider'] = new WordPressServerRequestProvider();
|
||||||
|
}
|
||||||
|
return $this->instances['serverRequestProvider'];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Obtiene el repositorio de exclusiones
|
||||||
|
*/
|
||||||
|
public function getExclusionRepository(): ExclusionRepositoryInterface
|
||||||
|
{
|
||||||
|
if (!isset($this->instances['exclusionRepository'])) {
|
||||||
|
$this->instances['exclusionRepository'] = new WordPressExclusionRepository($this->wpdb);
|
||||||
|
}
|
||||||
|
return $this->instances['exclusionRepository'];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Obtiene el proveedor de contexto de página
|
||||||
|
*/
|
||||||
|
public function getPageContextProvider(): PageContextProviderInterface
|
||||||
|
{
|
||||||
|
if (!isset($this->instances['pageContextProvider'])) {
|
||||||
|
$this->instances['pageContextProvider'] = new WordPressPageContextProvider(
|
||||||
|
$this->getServerRequestProvider()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return $this->instances['pageContextProvider'];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Obtiene el caso de uso de evaluación de exclusiones
|
||||||
|
*/
|
||||||
|
public function getEvaluateExclusionsUseCase(): EvaluateExclusionsUseCase
|
||||||
|
{
|
||||||
|
if (!isset($this->instances['evaluateExclusionsUseCase'])) {
|
||||||
|
$this->instances['evaluateExclusionsUseCase'] = new EvaluateExclusionsUseCase(
|
||||||
|
$this->getExclusionRepository(),
|
||||||
|
$this->getPageContextProvider()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return $this->instances['evaluateExclusionsUseCase'];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Obtiene el caso de uso orquestador de visibilidad completa
|
||||||
|
*
|
||||||
|
* Combina visibilidad por tipo de página + exclusiones
|
||||||
|
*/
|
||||||
|
public function getEvaluateComponentVisibilityUseCase(): EvaluateComponentVisibilityUseCase
|
||||||
|
{
|
||||||
|
if (!isset($this->instances['evaluateComponentVisibilityUseCase'])) {
|
||||||
|
$this->instances['evaluateComponentVisibilityUseCase'] = new EvaluateComponentVisibilityUseCase(
|
||||||
|
$this->getEvaluatePageVisibilityUseCase(),
|
||||||
|
$this->getEvaluateExclusionsUseCase()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return $this->instances['evaluateComponentVisibilityUseCase'];
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,147 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace ROITheme\Shared\Infrastructure\Persistence\WordPress;
|
||||||
|
|
||||||
|
use ROITheme\Shared\Domain\Contracts\ExclusionRepositoryInterface;
|
||||||
|
use ROITheme\Shared\Domain\ValueObjects\ExclusionRuleSet;
|
||||||
|
use ROITheme\Shared\Domain\ValueObjects\CategoryExclusion;
|
||||||
|
use ROITheme\Shared\Domain\ValueObjects\PostIdExclusion;
|
||||||
|
use ROITheme\Shared\Domain\ValueObjects\UrlPatternExclusion;
|
||||||
|
use ROITheme\Shared\Domain\Constants\ExclusionDefaults;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Implementacion WordPress del repositorio de exclusiones
|
||||||
|
*
|
||||||
|
* Almacena exclusiones en wp_roi_theme_component_settings
|
||||||
|
* con group_name = '_exclusions'
|
||||||
|
*
|
||||||
|
* @package ROITheme\Shared\Infrastructure\Persistence\WordPress
|
||||||
|
*/
|
||||||
|
final class WordPressExclusionRepository implements ExclusionRepositoryInterface
|
||||||
|
{
|
||||||
|
private const TABLE_SUFFIX = 'roi_theme_component_settings';
|
||||||
|
|
||||||
|
public function __construct(
|
||||||
|
private readonly \wpdb $wpdb
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public function getExclusions(string $componentName): ExclusionRuleSet
|
||||||
|
{
|
||||||
|
$table = $this->wpdb->prefix . self::TABLE_SUFFIX;
|
||||||
|
$groupName = ExclusionDefaults::GROUP_NAME;
|
||||||
|
|
||||||
|
$results = $this->wpdb->get_results(
|
||||||
|
$this->wpdb->prepare(
|
||||||
|
"SELECT attribute_name, attribute_value
|
||||||
|
FROM {$table}
|
||||||
|
WHERE component_name = %s
|
||||||
|
AND group_name = %s",
|
||||||
|
$componentName,
|
||||||
|
$groupName
|
||||||
|
),
|
||||||
|
ARRAY_A
|
||||||
|
);
|
||||||
|
|
||||||
|
if (empty($results)) {
|
||||||
|
return ExclusionRuleSet::empty($componentName);
|
||||||
|
}
|
||||||
|
|
||||||
|
$data = [];
|
||||||
|
foreach ($results as $row) {
|
||||||
|
$data[$row['attribute_name']] = $row['attribute_value'];
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->hydrateExclusions($componentName, $data);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function saveExclusions(ExclusionRuleSet $exclusions): void
|
||||||
|
{
|
||||||
|
$componentName = $exclusions->getComponentName();
|
||||||
|
|
||||||
|
$data = [
|
||||||
|
'exclusions_enabled' => $exclusions->isEnabled() ? '1' : '0',
|
||||||
|
'exclude_categories' => $exclusions->getCategoryExclusion()->serialize(),
|
||||||
|
'exclude_post_ids' => $exclusions->getPostIdExclusion()->serialize(),
|
||||||
|
'exclude_url_patterns' => $exclusions->getUrlPatternExclusion()->serialize(),
|
||||||
|
];
|
||||||
|
|
||||||
|
foreach ($data as $field => $value) {
|
||||||
|
$this->upsertField($componentName, $field, $value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function hasExclusions(string $componentName): bool
|
||||||
|
{
|
||||||
|
$table = $this->wpdb->prefix . self::TABLE_SUFFIX;
|
||||||
|
$groupName = ExclusionDefaults::GROUP_NAME;
|
||||||
|
|
||||||
|
$count = $this->wpdb->get_var($this->wpdb->prepare(
|
||||||
|
"SELECT COUNT(*) FROM {$table}
|
||||||
|
WHERE component_name = %s
|
||||||
|
AND group_name = %s",
|
||||||
|
$componentName,
|
||||||
|
$groupName
|
||||||
|
));
|
||||||
|
|
||||||
|
return (int) $count > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function hydrateExclusions(string $componentName, array $data): ExclusionRuleSet
|
||||||
|
{
|
||||||
|
$enabled = ($data['exclusions_enabled'] ?? '0') === '1';
|
||||||
|
|
||||||
|
$categoryExclusion = CategoryExclusion::fromJson($data['exclude_categories'] ?? '[]');
|
||||||
|
$postIdExclusion = PostIdExclusion::fromJson($data['exclude_post_ids'] ?? '[]');
|
||||||
|
$urlPatternExclusion = UrlPatternExclusion::fromJson($data['exclude_url_patterns'] ?? '[]');
|
||||||
|
|
||||||
|
return new ExclusionRuleSet(
|
||||||
|
$componentName,
|
||||||
|
$enabled,
|
||||||
|
$categoryExclusion,
|
||||||
|
$postIdExclusion,
|
||||||
|
$urlPatternExclusion
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function upsertField(string $componentName, string $field, string $value): void
|
||||||
|
{
|
||||||
|
$table = $this->wpdb->prefix . self::TABLE_SUFFIX;
|
||||||
|
$groupName = ExclusionDefaults::GROUP_NAME;
|
||||||
|
|
||||||
|
$exists = $this->wpdb->get_var($this->wpdb->prepare(
|
||||||
|
"SELECT COUNT(*) FROM {$table}
|
||||||
|
WHERE component_name = %s
|
||||||
|
AND group_name = %s
|
||||||
|
AND attribute_name = %s",
|
||||||
|
$componentName,
|
||||||
|
$groupName,
|
||||||
|
$field
|
||||||
|
));
|
||||||
|
|
||||||
|
if ($exists) {
|
||||||
|
$this->wpdb->update(
|
||||||
|
$table,
|
||||||
|
[
|
||||||
|
'attribute_value' => $value,
|
||||||
|
'updated_at' => current_time('mysql'),
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'component_name' => $componentName,
|
||||||
|
'group_name' => $groupName,
|
||||||
|
'attribute_name' => $field,
|
||||||
|
]
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
$this->wpdb->insert($table, [
|
||||||
|
'component_name' => $componentName,
|
||||||
|
'group_name' => $groupName,
|
||||||
|
'attribute_name' => $field,
|
||||||
|
'attribute_value' => $value,
|
||||||
|
'is_editable' => 1,
|
||||||
|
'created_at' => current_time('mysql'),
|
||||||
|
'updated_at' => current_time('mysql'),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,11 +6,11 @@ namespace ROITheme\Shared\Infrastructure\Services;
|
|||||||
use ROITheme\Shared\Infrastructure\Di\DIContainer;
|
use ROITheme\Shared\Infrastructure\Di\DIContainer;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Facade/Helper para evaluar visibilidad de componentes
|
* Facade/Helper para evaluar visibilidad completa de componentes
|
||||||
*
|
*
|
||||||
* PROPÓSITO:
|
* PROPOSITO:
|
||||||
* Permite que los Renderers existentes evalúen visibilidad sin modificar sus constructores.
|
* Permite que los Renderers existentes evaluen visibilidad sin modificar sus constructores.
|
||||||
* Actúa como un Service Locator limitado a este único propósito.
|
* Ahora incluye tanto visibilidad por tipo de pagina como reglas de exclusion.
|
||||||
*
|
*
|
||||||
* USO EN RENDERERS:
|
* USO EN RENDERERS:
|
||||||
* ```php
|
* ```php
|
||||||
@@ -19,17 +19,41 @@ use ROITheme\Shared\Infrastructure\Di\DIContainer;
|
|||||||
* }
|
* }
|
||||||
* ```
|
* ```
|
||||||
*
|
*
|
||||||
|
* FLUJO:
|
||||||
|
* 1. Verifica visibilidad por tipo de pagina (home, posts, pages, etc.)
|
||||||
|
* 2. Verifica reglas de exclusion (categorias, IDs, patrones URL)
|
||||||
|
* 3. Retorna true SOLO si pasa ambas verificaciones
|
||||||
|
*
|
||||||
* @package ROITheme\Shared\Infrastructure\Services
|
* @package ROITheme\Shared\Infrastructure\Services
|
||||||
*/
|
*/
|
||||||
final class PageVisibilityHelper
|
final class PageVisibilityHelper
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
* Evalúa si un componente debe mostrarse en la página actual
|
* Evalua si un componente debe mostrarse en la pagina actual
|
||||||
|
*
|
||||||
|
* Incluye verificacion de:
|
||||||
|
* - Visibilidad por tipo de pagina (Plan 99.10)
|
||||||
|
* - Reglas de exclusion (Plan 99.11)
|
||||||
*
|
*
|
||||||
* @param string $componentName Nombre del componente (kebab-case)
|
* @param string $componentName Nombre del componente (kebab-case)
|
||||||
* @return bool True si debe mostrarse
|
* @return bool True si debe mostrarse
|
||||||
*/
|
*/
|
||||||
public static function shouldShow(string $componentName): bool
|
public static function shouldShow(string $componentName): bool
|
||||||
|
{
|
||||||
|
$container = DIContainer::getInstance();
|
||||||
|
$useCase = $container->getEvaluateComponentVisibilityUseCase();
|
||||||
|
|
||||||
|
return $useCase->execute($componentName);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Evalua SOLO visibilidad por tipo de pagina (sin exclusiones)
|
||||||
|
*
|
||||||
|
* @deprecated Usar shouldShow() que incluye exclusiones
|
||||||
|
* @param string $componentName Nombre del componente (kebab-case)
|
||||||
|
* @return bool True si debe mostrarse segun tipo de pagina
|
||||||
|
*/
|
||||||
|
public static function shouldShowByPageType(string $componentName): bool
|
||||||
{
|
{
|
||||||
$container = DIContainer::getInstance();
|
$container = DIContainer::getInstance();
|
||||||
$useCase = $container->getEvaluatePageVisibilityUseCase();
|
$useCase = $container->getEvaluatePageVisibilityUseCase();
|
||||||
|
|||||||
@@ -0,0 +1,90 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace ROITheme\Shared\Infrastructure\Services;
|
||||||
|
|
||||||
|
use ROITheme\Shared\Domain\Contracts\PageContextProviderInterface;
|
||||||
|
use ROITheme\Shared\Domain\Contracts\ServerRequestProviderInterface;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Implementacion WordPress del proveedor de contexto de pagina
|
||||||
|
*
|
||||||
|
* Obtiene informacion del post/pagina actual usando funciones de WordPress.
|
||||||
|
*
|
||||||
|
* v1.1: Renombrado de WordPressExclusionEvaluator
|
||||||
|
* Inyecta ServerRequestProviderInterface (no accede a $_SERVER directamente)
|
||||||
|
*
|
||||||
|
* @package ROITheme\Shared\Infrastructure\Services
|
||||||
|
*/
|
||||||
|
final class WordPressPageContextProvider implements PageContextProviderInterface
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
private readonly ServerRequestProviderInterface $requestProvider
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public function getCurrentContext(): array
|
||||||
|
{
|
||||||
|
$postId = $this->getCurrentPostId();
|
||||||
|
|
||||||
|
return [
|
||||||
|
'post_id' => $postId,
|
||||||
|
'categories' => $this->getPostCategories($postId),
|
||||||
|
'url' => $this->getCurrentUrl(),
|
||||||
|
'request_uri' => $this->requestProvider->getRequestUri(),
|
||||||
|
'post_type' => $this->getCurrentPostType($postId),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
private function getCurrentPostId(): int
|
||||||
|
{
|
||||||
|
if (is_singular()) {
|
||||||
|
return get_the_ID() ?: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @return array<array{term_id: int, slug: string, name: string}>
|
||||||
|
*/
|
||||||
|
private function getPostCategories(int $postId): array
|
||||||
|
{
|
||||||
|
if ($postId === 0) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
$categories = get_the_category($postId);
|
||||||
|
|
||||||
|
if (empty($categories)) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
return array_map(function (\WP_Term $term): array {
|
||||||
|
return [
|
||||||
|
'term_id' => $term->term_id,
|
||||||
|
'slug' => $term->slug,
|
||||||
|
'name' => $term->name,
|
||||||
|
];
|
||||||
|
}, $categories);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function getCurrentUrl(): string
|
||||||
|
{
|
||||||
|
global $wp;
|
||||||
|
|
||||||
|
if (isset($wp->request)) {
|
||||||
|
return home_url($wp->request);
|
||||||
|
}
|
||||||
|
|
||||||
|
return home_url(add_query_arg([], false));
|
||||||
|
}
|
||||||
|
|
||||||
|
private function getCurrentPostType(int $postId): string
|
||||||
|
{
|
||||||
|
if ($postId === 0) {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
return get_post_type($postId) ?: '';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace ROITheme\Shared\Infrastructure\Services;
|
||||||
|
|
||||||
|
use ROITheme\Shared\Domain\Contracts\ServerRequestProviderInterface;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Implementacion WordPress del proveedor de request HTTP
|
||||||
|
*
|
||||||
|
* Encapsula el acceso a $_SERVER.
|
||||||
|
*
|
||||||
|
* v1.1: Nuevo - extrae logica de acceso a superglobales
|
||||||
|
*
|
||||||
|
* @package ROITheme\Shared\Infrastructure\Services
|
||||||
|
*/
|
||||||
|
final class WordPressServerRequestProvider implements ServerRequestProviderInterface
|
||||||
|
{
|
||||||
|
public function getRequestUri(): string
|
||||||
|
{
|
||||||
|
return $_SERVER['REQUEST_URI'] ?? '';
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user