0) { $filterParams['id_after'] = $id_after; } } if (!empty($params['date_after']) && is_scalar($params['date_after'])) { $filterParams['date_after'] = sanitize_text_field((string) $params['date_after']); } if (!empty($params['date_before']) && is_scalar($params['date_before'])) { $filterParams['date_before'] = sanitize_text_field((string) $params['date_before']); } if (isset($params['stock_qty_min']) && is_numeric($params['stock_qty_min'])) { $filterParams['stock_qty_min'] = (int) $params['stock_qty_min']; } if (isset($params['stock_qty_max']) && is_numeric($params['stock_qty_max'])) { $filterParams['stock_qty_max'] = (int) $params['stock_qty_max']; } if (isset($params['price_min']) && is_numeric($params['price_min'])) { $filterParams['price_min'] = (float) $params['price_min']; } if (isset($params['price_max']) && is_numeric($params['price_max'])) { $filterParams['price_max'] = (float) $params['price_max']; } if (isset($params['ids_only'])) { $filterParams['idsOnly'] = filter_var($params['ids_only'], FILTER_VALIDATE_BOOLEAN); } return $filterParams; } /** * Applies the filter parameters to the ProductFilterBuilder * * @param ProductFilterBuilder $builder Filter builder instance * @param array $params Filter parameters * @return ProductFilterBuilder Builder with the parameters applied */ public static function applyToBuilder(ProductFilterBuilder $builder, $params) { if (!empty($params['filter_logic'])) { $builder->filterLogic($params['filter_logic']); } if (!empty($params['catalog_visibility'])) { $builder->catalogVisibility($params['catalog_visibility']); } if (isset($params['search']) && is_scalar($params['search']) && '' !== (string) $params['search']) { $builder->search($params['search']); } if (!empty($params['category'])) { $builder->category($params['category']); } if (!empty($params['tag'])) { $builder->tag($params['tag']); } $builder->pagination( isset($params['page']) ? $params['page'] : 1, isset($params['per_page']) ? $params['per_page'] : 10 ); $orderby = isset($params['orderby']) ? $params['orderby'] : 'date'; $order = isset($params['order']) ? strtoupper($params['order']) : 'DESC'; $builder->orderBy($orderby, $order); if (!empty($params['status'])) { $builder->status($params['status']); } if (!empty($params['stock_status'])) { $builder->stockStatus($params['stock_status']); } if (!empty($params['id_after'])) { $builder->idAfter((int) $params['id_after']); } if (!empty($params['descriptionFilters'])) { $builder->contentFilters($params['descriptionFilters']); } else { $hasDescription = isset($params['hasDescription']) ? $params['hasDescription'] : null; $hasShortDescription = isset($params['hasShortDescription']) ? $params['hasShortDescription'] : null; if ($hasDescription !== null || $hasShortDescription !== null) { $builder->descriptions($hasDescription, $hasShortDescription); } } if (isset($params['hasTags'])) { $builder->tags($params['hasTags']); } if (isset($params['has_image'])) { $builder->image($params['has_image']); } if (isset($params['has_gallery'])) { $builder->gallery($params['has_gallery']); } if (isset($params['has_sku'])) { $builder->sku($params['has_sku']); } if (!empty($params['product_type'])) { $builder->productType($params['product_type']); } if (isset($params['featured'])) { $builder->featured($params['featured']); } if (isset($params['on_sale'])) { $builder->onSale($params['on_sale']); } if (!empty($params['ai_processed'])) { $ai_processed_type = !empty($params['ai_processed_type']) ? $params['ai_processed_type'] : null; $builder->aiProcessed( $ai_processed_type, $params['ai_processed'] === 'processed' ? 'exists' : 'not_exists' ); } if (isset($params['date_after']) || isset($params['date_before'])) { $builder->dateRange( isset($params['date_after']) ? (string) $params['date_after'] : '', isset($params['date_before']) ? (string) $params['date_before'] : '' ); } if (isset($params['stock_qty_min']) || isset($params['stock_qty_max'])) { $builder->stockQuantity( isset($params['stock_qty_min']) ? (int) $params['stock_qty_min'] : null, isset($params['stock_qty_max']) ? (int) $params['stock_qty_max'] : null ); } if (isset($params['price_min']) || isset($params['price_max'])) { $builder->priceRange( isset($params['price_min']) ? (float) $params['price_min'] : null, isset($params['price_max']) ? (float) $params['price_max'] : null ); } if (!empty($params['idsOnly'])) { $builder->idsOnly()->withoutTotal(); } return $builder; } private static function isValidDescriptionFilter($descriptionFilter): bool { return in_array( $descriptionFilter, ['with_both', 'with_full', 'with_short', 'without_both', 'without_full', 'without_short', 'with_tags', 'without_tags', 'without_seo_meta', 'without_faq'], true ); } /** * Adapts ProductFilterBuilder response to match ProductListingService format * * This ensures backward compatibility when migrating from ProductListingService * to ProductFilterBuilder across different generators. * * ProductFilterBuilder returns: * ['products' => [], 'total' => int, 'total_pages' => int] * * ProductListingService returns: * ['success' => bool, 'products' => [], 'total' => int, 'totalPages' => int, 'page' => int, 'perPage' => int] * * @param array $result Result from ProductFilterBuilder::getProducts() * @param array $params Original filter params (to extract page/per_page) * @param bool $includeFilters Whether to include the filters in response * @return array Adapted response matching ProductListingService format */ public static function adaptResponse(array $result, array $params = [], bool $includeFilters = false): array { $adapted = [ 'success' => !isset($result['error']), 'products' => $result['products'] ?? [], ]; if (array_key_exists('total', $result)) { $adapted['total'] = $result['total']; $adapted['totalPages'] = $result['total_pages'] ?? 0; } $adapted['page'] = isset($params['page']) ? absint($params['page']) : 1; $adapted['perPage'] = isset($params['per_page']) ? absint($params['per_page']) : 10; if (isset($result['error'])) { $adapted['error'] = $result['error']; } if (isset($result['message'])) { $adapted['message'] = $result['message']; } if ($includeFilters) { $adapted['filters'] = $params; } return $adapted; } /** * Largest and default number of categories one call returns. */ public const CATEGORY_LIST_CAP = 100; /** * Upper bound on get_terms() batches per call, so a store whose terms are * mostly Polylang translations cannot loop without end. */ private const CATEGORY_MAX_BATCHES = 20; /** * get_terms() argument that asks addNameContainsClause() for a name match in SQL. */ private const NAME_CONTAINS_ARG = 'aipt_name_contains'; /** * Gets product categories for filter dropdowns, bounded to at most per_page entries. * * Without a search a store with at most per_page categories gets all of them, * ordered by name; a larger store gets the per_page categories with the most * products, then ordered by name for display. With a search the name matches * come back ordered by name. Categories named in `slug` are always added on * top of the cap so the labels of selected filters resolve. * * When Polylang is active, delegates language-aware term retrieval * and deduplication to PolylangTermHandler; the cap counts logical * categories, after deduplication. * * Only the plain call (no search, no slug, default per_page) is cached. * * @param array $args Optional 'search' (string), 'per_page' (int, clamped to 1..100) and 'slug' (string[]). * @return array Array of categories with id, name, slug, count */ public static function getCategories(array $args = []): array { $search = isset($args['search']) && is_string($args['search']) ? trim($args['search']) : ''; $per_page = isset($args['per_page']) ? (int) $args['per_page'] : self::CATEGORY_LIST_CAP; $per_page = max(1, min(self::CATEGORY_LIST_CAP, $per_page)); $slugs = self::normalizeSlugList($args['slug'] ?? []); $is_default = '' === $search && [] === $slugs && self::CATEGORY_LIST_CAP === $per_page; $cache_key = 'aipt_product_filter_categories'; if ($is_default) { $cached = wp_cache_get($cache_key, 'aipt_products'); if (false !== $cached && is_array($cached)) { return $cached; } } $query = [ 'taxonomy' => 'product_cat', 'hide_empty' => false, ]; if ('' !== $search) { $needle = htmlspecialchars(html_entity_decode($search, ENT_QUOTES, 'UTF-8'), ENT_NOQUOTES, 'UTF-8'); $query['orderby'] = 'name'; $query['order'] = 'ASC'; if ('0' === $needle) { $query[self::NAME_CONTAINS_ARG] = $needle; } else { $query['name__like'] = $needle; } } else { $query['orderby'] = 'count'; $query['order'] = 'DESC'; } $terms = self::fetchLogicalTerms($query, $per_page); if ([] !== $slugs) { $terms = self::addTermsBySlug($terms, $slugs); } $terms = self::orderByName($terms); $categories = []; foreach ($terms as $term) { $categories[] = [ 'id' => $term->term_id, 'name' => html_entity_decode($term->name, ENT_QUOTES, 'UTF-8'), 'slug' => $term->slug, 'count' => $term->count, ]; } if ($is_default) { wp_cache_set($cache_key, $categories, 'aipt_products', 300); } return $categories; } /** * REST argument schema shared by the two category list routes. * * per_page carries no minimum or maximum on purpose: getCategories() clamps it, so an * oversized value is served at the cap instead of refused. * * @return array */ public static function categoryRouteArgs(): array { return [ 'search' => [ 'type' => 'string', 'default' => '', 'sanitize_callback' => 'sanitize_text_field', ], 'per_page' => [ 'type' => 'integer', 'default' => self::CATEGORY_LIST_CAP, 'sanitize_callback' => 'absint', ], 'slug' => [ 'type' => 'string', 'default' => '', ], ]; } /** * Normalizes a slug list given as an array or a comma separated string. * * @param mixed $value Raw slugs. * @return string[] Sanitized, unique, non-empty slugs. */ private static function normalizeSlugList($value): array { if (is_string($value)) { $value = explode(',', $value); } if (!is_array($value)) { return []; } $slugs = []; foreach ($value as $slug) { if (!is_string($slug)) { continue; } $slug = sanitize_title(trim($slug)); if ('' !== $slug) { $slugs[$slug] = $slug; } } return array_values($slugs); } /** * Reads up to $limit logical terms in the order of $query. * * Polylang deduplication can fold several raw terms into one, so a page of * $limit raw terms may hold fewer logical ones. Reads further pages until * the limit is filled or the terms run out, then cuts after deduplication. * * hierarchical is off: on a hierarchical taxonomy WP_Term_Query otherwise reads every * term and applies number and offset in PHP. With hide_empty off it changes no result. * * A query that carries NAME_CONTAINS_ARG gets its name match from addNameContainsClause(), * registered only while these reads run. * * @param array $query get_terms() arguments without number and offset. * @param int $limit Maximum number of logical terms. * @return array WP_Term objects. */ private static function fetchLogicalTerms(array $query, int $limit): array { PolylangTermHandler::adjustTermQueryArgs($query); $query['number'] = $limit; $query['hierarchical'] = false; $raw = []; $matches_name = isset($query[self::NAME_CONTAINS_ARG]); if ($matches_name) { add_filter('terms_clauses', [self::class, 'addNameContainsClause'], 10, 3); } try { for ($batch_index = 0; $batch_index < self::CATEGORY_MAX_BATCHES; $batch_index++) { $query['offset'] = $batch_index * $limit; $batch = get_terms($query); if (!is_array($batch)) { break; } $raw = array_merge($raw, $batch); $logical = PolylangTermHandler::deduplicateTerms($raw); if (count($batch) < $limit || count($logical) >= $limit) { break; } } } finally { if ($matches_name) { remove_filter('terms_clauses', [self::class, 'addNameContainsClause'], 10); } } $logical = PolylangTermHandler::deduplicateTerms($raw); return array_slice(self::onlyTermObjects($logical), 0, $limit); } /** * terms_clauses callback: limits a term query that carries NAME_CONTAINS_ARG to names that * contain its text, with the SQL WP_Term_Query builds for name__like, which it skips for "0" * because empty() calls "0" empty. The existing condition is kept in parentheses, so an OR * that another terms_clauses filter added cannot take the match out of it. Any other term * query that runs while the callback is registered is returned unchanged. * * @param mixed $clauses Term query clauses. * @param mixed $taxonomies Taxonomies of the query. * @param mixed $args Term query arguments. * @return mixed The clauses. */ public static function addNameContainsClause($clauses, $taxonomies, $args) { if (!is_array($clauses) || !is_array($args) || !isset($args[self::NAME_CONTAINS_ARG])) { return $clauses; } global $wpdb; $match = $wpdb->prepare('t.name LIKE %s', '%' . $wpdb->esc_like((string) $args[self::NAME_CONTAINS_ARG]) . '%'); $where = isset($clauses['where']) ? trim((string) $clauses['where']) : ''; $clauses['where'] = '' === $where ? $match : '(' . $where . ') AND ' . $match; return $clauses; } /** * Adds the categories with the given slugs to $terms when they are missing. * * @param array $terms Logical WP_Term objects already selected. * @param string[] $slugs Slugs that must be present. * @return array WP_Term objects. */ private static function addTermsBySlug(array $terms, array $slugs): array { $query = [ 'taxonomy' => 'product_cat', 'hide_empty' => false, 'slug' => $slugs, ]; PolylangTermHandler::adjustTermQueryArgs($query); $extra = get_terms($query); if (!is_array($extra)) { return $terms; } $present = []; foreach ($terms as $term) { $present[(int) $term->term_id] = true; } foreach (self::onlyTermObjects(PolylangTermHandler::deduplicateTerms($extra)) as $term) { if (!isset($present[(int) $term->term_id])) { $terms[] = $term; $present[(int) $term->term_id] = true; } } return $terms; } /** * Orders terms by name the way get_terms() does, with the database collation. * * A PHP string sort would put accented names (Eclair with an accent, O with a * diaeresis) after Z; the database sorts them with their base letter, as the * list always was before it was bounded. * * @param array $terms Logical WP_Term objects. * @return array WP_Term objects ordered by name. The input order when the lookup fails. */ private static function orderByName(array $terms): array { if (count($terms) < 2) { return $terms; } $ids = []; foreach ($terms as $term) { $ids[] = (int) $term->term_id; } $query = [ 'taxonomy' => 'product_cat', 'hide_empty' => false, 'include' => $ids, 'orderby' => 'name', 'order' => 'ASC', ]; PolylangTermHandler::adjustTermQueryArgs($query); $ordered = get_terms($query); if (!is_array($ordered) || count($ordered) !== count($terms)) { return $terms; } return self::onlyTermObjects($ordered); } /** * Keeps the entries that are term objects. * * @param array $terms Mixed get_terms() result. * @return array WP_Term objects, re-indexed. */ private static function onlyTermObjects(array $terms): array { return array_values(array_filter($terms, 'is_object')); } /** * Gets all product tags for filter dropdowns * * When Polylang is active, delegates language-aware term retrieval * and deduplication to PolylangTermHandler. * * @return array Array of tags with id, name, slug, count */ public static function getTags(): array { $cache_key = 'aipt_product_filter_tags'; $cached = wp_cache_get($cache_key, 'aipt_products'); if (false !== $cached && is_array($cached)) { return $cached; } $args = [ 'taxonomy' => 'product_tag', 'hide_empty' => false, 'orderby' => 'name', 'order' => 'ASC', ]; PolylangTermHandler::adjustTermQueryArgs($args); $terms = get_terms($args); if (is_wp_error($terms)) { return []; } if (!is_array($terms)) { return []; } $terms = PolylangTermHandler::deduplicateTerms($terms); $tags = []; foreach ($terms as $term) { if (!is_object($term)) { continue; } $tags[] = [ 'id' => $term->term_id, 'name' => html_entity_decode($term->name, ENT_QUOTES, 'UTF-8'), 'slug' => $term->slug, 'count' => $term->count, ]; } wp_cache_set($cache_key, $tags, 'aipt_products', 300); return $tags; } /** * Register cache invalidation hooks for term changes. * Should be called during plugin initialization. * * @return void */ public static function registerCacheInvalidationHooks(): void { add_action( 'created_product_cat', array( __CLASS__, 'invalidateCategoriesCache' ) ); add_action( 'edited_product_cat', array( __CLASS__, 'invalidateCategoriesCache' ) ); add_action( 'delete_product_cat', array( __CLASS__, 'invalidateCategoriesCache' ) ); add_action( 'created_product_tag', array( __CLASS__, 'invalidateTagsCache' ) ); add_action( 'edited_product_tag', array( __CLASS__, 'invalidateTagsCache' ) ); add_action( 'delete_product_tag', array( __CLASS__, 'invalidateTagsCache' ) ); add_action( 'aipt_content_marked', array( __CLASS__, 'invalidateProductListCache' ) ); } /** * Invalidate categories cache. * * @return void */ public static function invalidateCategoriesCache(): void { wp_cache_delete( 'aipt_product_filter_categories', 'aipt_products' ); } /** * Invalidate tags cache. * * @return void */ public static function invalidateTagsCache(): void { wp_cache_delete( 'aipt_product_filter_tags', 'aipt_products' ); } /** * Per-request guard so a bulk/automation mark run flushes the product-list * group at most once instead of once per marked product. * * @var bool */ private static $productListCacheFlushed = false; /** * Invalidate the filtered product-list result cache after a content mark. * * ProductFilterBuilder::getProducts() caches results under per-user, * per-filter-hash keys that are not enumerable, so the whole aipt_products * group is flushed, and its last_changed version is bumped for backends * that cannot flush a group. The cat/tag dropdown caches share the group and * simply repopulate on next read. * * The aipt_content_marked hook fires once per product, so a bulk or * automation run would otherwise flush the group hundreds of times in one * request — a real cost on persistent object caches. Nothing repopulates the * group mid-run (marking never reads the filtered list), so a per-request * guard safely collapses those to a single flush. PHP statics reset per * request, keeping this correct across requests. * * @return void */ public static function invalidateProductListCache(): void { if ( self::$productListCacheFlushed ) { return; } self::$productListCacheFlushed = true; if ( function_exists( 'wp_cache_flush_group' ) ) { wp_cache_flush_group( 'aipt_products' ); } ProductFilterBuilder::flush_cache(); } /** * Reset the per-request product-list flush guard. * * PHP statics persist across cases within a single PHPUnit process, so unit * tests that assert the flush reset the guard between cases. Harmless in * production, where each request already begins with a fresh static. * * @return void */ public static function resetProductCacheFlushGuard(): void { self::$productListCacheFlushed = false; } }