From 14138e776235659346bd26f55ad44e090edf0ed7 Mon Sep 17 00:00:00 2001 From: FrankZamora Date: Wed, 3 Dec 2025 10:51:00 -0600 Subject: [PATCH] feat(exclusions): Implement component exclusion system (Plan 99.11) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- .../Services/ExclusionFieldProcessor.php | 65 +++++ .../Ui/Assets/Js/exclusion-toggle.js | 31 +++ .../Ui/ExclusionFormPartial.php | 244 ++++++++++++++++++ .../EvaluateComponentVisibilityUseCase.php | 52 ++++ .../EvaluateExclusionsUseCase.php | 44 ++++ Shared/Domain/Constants/ExclusionDefaults.php | 37 +++ .../ExclusionRepositoryInterface.php | 36 +++ .../PageContextProviderInterface.php | 33 +++ .../ServerRequestProviderInterface.php | 27 ++ .../Domain/ValueObjects/CategoryExclusion.php | 100 +++++++ Shared/Domain/ValueObjects/ExclusionRule.php | 37 +++ .../Domain/ValueObjects/ExclusionRuleSet.php | 100 +++++++ .../Domain/ValueObjects/PostIdExclusion.php | 86 ++++++ .../ValueObjects/UrlPatternExclusion.php | 146 +++++++++++ Shared/Infrastructure/Di/DIContainer.php | 80 ++++++ .../WordPressExclusionRepository.php | 147 +++++++++++ .../Services/PageVisibilityHelper.php | 34 ++- .../Services/WordPressPageContextProvider.php | 90 +++++++ .../WordPressServerRequestProvider.php | 23 ++ 19 files changed, 1407 insertions(+), 5 deletions(-) create mode 100644 Admin/Shared/Infrastructure/Services/ExclusionFieldProcessor.php create mode 100644 Admin/Shared/Infrastructure/Ui/Assets/Js/exclusion-toggle.js create mode 100644 Admin/Shared/Infrastructure/Ui/ExclusionFormPartial.php create mode 100644 Shared/Application/UseCases/EvaluateComponentVisibility/EvaluateComponentVisibilityUseCase.php create mode 100644 Shared/Application/UseCases/EvaluateExclusions/EvaluateExclusionsUseCase.php create mode 100644 Shared/Domain/Constants/ExclusionDefaults.php create mode 100644 Shared/Domain/Contracts/ExclusionRepositoryInterface.php create mode 100644 Shared/Domain/Contracts/PageContextProviderInterface.php create mode 100644 Shared/Domain/Contracts/ServerRequestProviderInterface.php create mode 100644 Shared/Domain/ValueObjects/CategoryExclusion.php create mode 100644 Shared/Domain/ValueObjects/ExclusionRule.php create mode 100644 Shared/Domain/ValueObjects/ExclusionRuleSet.php create mode 100644 Shared/Domain/ValueObjects/PostIdExclusion.php create mode 100644 Shared/Domain/ValueObjects/UrlPatternExclusion.php create mode 100644 Shared/Infrastructure/Persistence/WordPress/WordPressExclusionRepository.php create mode 100644 Shared/Infrastructure/Services/WordPressPageContextProvider.php create mode 100644 Shared/Infrastructure/Services/WordPressServerRequestProvider.php diff --git a/Admin/Shared/Infrastructure/Services/ExclusionFieldProcessor.php b/Admin/Shared/Infrastructure/Services/ExclusionFieldProcessor.php new file mode 100644 index 00000000..d01292aa --- /dev/null +++ b/Admin/Shared/Infrastructure/Services/ExclusionFieldProcessor.php @@ -0,0 +1,65 @@ + $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); + } +} diff --git a/Admin/Shared/Infrastructure/Ui/Assets/Js/exclusion-toggle.js b/Admin/Shared/Infrastructure/Ui/Assets/Js/exclusion-toggle.js new file mode 100644 index 00000000..6a1a723b --- /dev/null +++ b/Admin/Shared/Infrastructure/Ui/Assets/Js/exclusion-toggle.js @@ -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(); + } +})(); diff --git a/Admin/Shared/Infrastructure/Ui/ExclusionFormPartial.php b/Admin/Shared/Infrastructure/Ui/ExclusionFormPartial.php new file mode 100644 index 00000000..dccedc69 --- /dev/null +++ b/Admin/Shared/Infrastructure/Ui/ExclusionFormPartial.php @@ -0,0 +1,244 @@ +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 = '
'; + $html .= '

'; + $html .= ' '; + $html .= ' Reglas de exclusion avanzadas'; + $html .= '

'; + $html .= '

'; + $html .= ' Excluir este componente de categorias, posts o URLs especificos.'; + $html .= '

'; + + 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 = '
'; + $html .= '
'; + $html .= sprintf( + ' ', + esc_attr($id), + $checked ? 'checked' : '' + ); + $html .= sprintf( + ' '; + $html .= '
'; + $html .= '
'; + + 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( + '
', + esc_attr($prefix), + $display + ); + + $html .= $this->buildCategoryField($componentId, $prefix); + $html .= $this->buildPostIdsField($componentId, $prefix); + $html .= $this->buildUrlPatternsField($componentId, $prefix); + + $html .= '
'; + + 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 = '
'; + $html .= sprintf( + ' '; + $html .= sprintf( + ' ', + esc_attr($id), + esc_attr($categories) + ); + $html .= ' Slugs de categorias separados por comas'; + $html .= '
'; + + 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 = '
'; + $html .= sprintf( + ' '; + $html .= sprintf( + ' ', + esc_attr($id), + esc_attr($postIds) + ); + $html .= ' IDs de posts o paginas separados por comas'; + $html .= '
'; + + 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 = '
'; + $html .= sprintf( + ' '; + $html .= sprintf( + ' ', + esc_attr($id), + esc_textarea($patterns) + ); + $html .= ' Un patron por linea. Soporta texto simple o regex (ej: /^\/blog\/\d+$/)'; + $html .= '
'; + + 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; + } +} diff --git a/Shared/Application/UseCases/EvaluateComponentVisibility/EvaluateComponentVisibilityUseCase.php b/Shared/Application/UseCases/EvaluateComponentVisibility/EvaluateComponentVisibilityUseCase.php new file mode 100644 index 00000000..aad59f18 --- /dev/null +++ b/Shared/Application/UseCases/EvaluateComponentVisibility/EvaluateComponentVisibilityUseCase.php @@ -0,0 +1,52 @@ +pageVisibilityUseCase->execute($componentName); + + if (!$visibleByPageType) { + return false; + } + + // Paso 2: Verificar exclusiones + $isExcluded = $this->exclusionsUseCase->execute($componentName); + + // Mostrar si NO esta excluido + return !$isExcluded; + } +} diff --git a/Shared/Application/UseCases/EvaluateExclusions/EvaluateExclusionsUseCase.php b/Shared/Application/UseCases/EvaluateExclusions/EvaluateExclusionsUseCase.php new file mode 100644 index 00000000..705cdeef --- /dev/null +++ b/Shared/Application/UseCases/EvaluateExclusions/EvaluateExclusionsUseCase.php @@ -0,0 +1,44 @@ +exclusionRepository->getExclusions($componentName); + + if (!$exclusions->isEnabled()) { + return false; + } + + $context = $this->contextProvider->getCurrentContext(); + + return $exclusions->shouldExclude($context); + } +} diff --git a/Shared/Domain/Constants/ExclusionDefaults.php b/Shared/Domain/Constants/ExclusionDefaults.php new file mode 100644 index 00000000..b7daaa50 --- /dev/null +++ b/Shared/Domain/Constants/ExclusionDefaults.php @@ -0,0 +1,37 @@ + 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'; +} diff --git a/Shared/Domain/Contracts/ExclusionRepositoryInterface.php b/Shared/Domain/Contracts/ExclusionRepositoryInterface.php new file mode 100644 index 00000000..cbdaaa49 --- /dev/null +++ b/Shared/Domain/Contracts/ExclusionRepositoryInterface.php @@ -0,0 +1,36 @@ +, + * url: string, + * request_uri: string, + * post_type: string + * } + */ + public function getCurrentContext(): array; +} diff --git a/Shared/Domain/Contracts/ServerRequestProviderInterface.php b/Shared/Domain/Contracts/ServerRequestProviderInterface.php new file mode 100644 index 00000000..75dc48b2 --- /dev/null +++ b/Shared/Domain/Contracts/ServerRequestProviderInterface.php @@ -0,0 +1,27 @@ + $excludedCategories Lista de slugs o IDs de categorias + */ + public function __construct( + private readonly array $excludedCategories = [] + ) {} + + /** + * {@inheritdoc} + * + * Contexto esperado: + * - categories: array + */ + 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 + */ + 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([]); + } +} diff --git a/Shared/Domain/ValueObjects/ExclusionRule.php b/Shared/Domain/ValueObjects/ExclusionRule.php new file mode 100644 index 00000000..359f916a --- /dev/null +++ b/Shared/Domain/ValueObjects/ExclusionRule.php @@ -0,0 +1,37 @@ + $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; +} diff --git a/Shared/Domain/ValueObjects/ExclusionRuleSet.php b/Shared/Domain/ValueObjects/ExclusionRuleSet.php new file mode 100644 index 00000000..1d5cad46 --- /dev/null +++ b/Shared/Domain/ValueObjects/ExclusionRuleSet.php @@ -0,0 +1,100 @@ + $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() + ); + } +} diff --git a/Shared/Domain/ValueObjects/PostIdExclusion.php b/Shared/Domain/ValueObjects/PostIdExclusion.php new file mode 100644 index 00000000..5923238e --- /dev/null +++ b/Shared/Domain/ValueObjects/PostIdExclusion.php @@ -0,0 +1,86 @@ + $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 + */ + 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([]); + } +} diff --git a/Shared/Domain/ValueObjects/UrlPatternExclusion.php b/Shared/Domain/ValueObjects/UrlPatternExclusion.php new file mode 100644 index 00000000..c7aa9f13 --- /dev/null +++ b/Shared/Domain/ValueObjects/UrlPatternExclusion.php @@ -0,0 +1,146 @@ + $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 + */ + 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([]); + } +} diff --git a/Shared/Infrastructure/Di/DIContainer.php b/Shared/Infrastructure/Di/DIContainer.php index 77054ccb..c68c554a 100644 --- a/Shared/Infrastructure/Di/DIContainer.php +++ b/Shared/Infrastructure/Di/DIContainer.php @@ -28,6 +28,15 @@ use ROITheme\Shared\Infrastructure\Services\WordPressPageTypeDetector; use ROITheme\Shared\Infrastructure\Persistence\WordPress\WordPressPageVisibilityRepository; use ROITheme\Shared\Application\UseCases\EvaluatePageVisibility\EvaluatePageVisibilityUseCase; 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 @@ -363,4 +372,75 @@ final class DIContainer } 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']; + } } diff --git a/Shared/Infrastructure/Persistence/WordPress/WordPressExclusionRepository.php b/Shared/Infrastructure/Persistence/WordPress/WordPressExclusionRepository.php new file mode 100644 index 00000000..e70ba4b5 --- /dev/null +++ b/Shared/Infrastructure/Persistence/WordPress/WordPressExclusionRepository.php @@ -0,0 +1,147 @@ +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'), + ]); + } + } +} diff --git a/Shared/Infrastructure/Services/PageVisibilityHelper.php b/Shared/Infrastructure/Services/PageVisibilityHelper.php index ba23de84..cab954f8 100644 --- a/Shared/Infrastructure/Services/PageVisibilityHelper.php +++ b/Shared/Infrastructure/Services/PageVisibilityHelper.php @@ -6,11 +6,11 @@ namespace ROITheme\Shared\Infrastructure\Services; use ROITheme\Shared\Infrastructure\Di\DIContainer; /** - * Facade/Helper para evaluar visibilidad de componentes + * Facade/Helper para evaluar visibilidad completa de componentes * - * PROPÓSITO: - * Permite que los Renderers existentes evalĂșen visibilidad sin modificar sus constructores. - * ActĂșa como un Service Locator limitado a este Ășnico propĂłsito. + * PROPOSITO: + * Permite que los Renderers existentes evaluen visibilidad sin modificar sus constructores. + * Ahora incluye tanto visibilidad por tipo de pagina como reglas de exclusion. * * USO EN RENDERERS: * ```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 */ 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) * @return bool True si debe mostrarse */ 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(); $useCase = $container->getEvaluatePageVisibilityUseCase(); diff --git a/Shared/Infrastructure/Services/WordPressPageContextProvider.php b/Shared/Infrastructure/Services/WordPressPageContextProvider.php new file mode 100644 index 00000000..ba76db0a --- /dev/null +++ b/Shared/Infrastructure/Services/WordPressPageContextProvider.php @@ -0,0 +1,90 @@ +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 + */ + 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) ?: ''; + } +} diff --git a/Shared/Infrastructure/Services/WordPressServerRequestProvider.php b/Shared/Infrastructure/Services/WordPressServerRequestProvider.php new file mode 100644 index 00000000..0b793af1 --- /dev/null +++ b/Shared/Infrastructure/Services/WordPressServerRequestProvider.php @@ -0,0 +1,23 @@ +