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,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\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'];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
/**
|
||||
* 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();
|
||||
|
||||
@@ -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