assignments = $assignments ?? new AssignmentStore(); $this->resolver = $resolver ?? new AssignmentResolver(); $this->blueprints = $blueprints ?? new BlueprintStore(); $this->snapshots = $snapshots ?? new SnapshotStore(); } /** * Subjects where $blueprint_id is the resolver's CURRENT winner. * * @param string $generator Generator key. * @param int $blueprint_id Blueprint id. * @param int $limit Hard cap on returned/considered subjects (bounded further by CANDIDATE_HARD_CAP). * @param array>|null $preloaded_rows This generator's assignment rows, when the caller already fetched them (e.g. once per distinct generator across a batch of Blueprint ids), or null to fetch them here. Threaded into every `resolve()` call below exactly like {@see resolveForProducts()} already does, so resolving a candidate pool of thousands of subjects never re-queries the assignments table once per candidate. * @return array{total:int, ids:int[], sample:array, approximate:bool} */ public function productsForBlueprint( string $generator, int $blueprint_id, int $limit = 2000, ?array $preloaded_rows = null ): array { $limit = $limit > 0 ? min( $limit, self::CANDIDATE_HARD_CAP ) : 2000; $rows = $preloaded_rows ?? $this->assignments->listForGenerator( $generator ); $is_default = $this->isStoreDefault( $rows, $blueprint_id ); $own_rows = array_values( array_filter( $rows, static function ( array $row ) use ( $blueprint_id ): bool { return (int) ( $row['blueprintId'] ?? 0 ) === $blueprint_id && in_array( $row['targetType'] ?? '', array( 'product', 'category', 'term', 'taxonomy' ), true ); } ) ); if ( Generators::TAXONOMY === $generator ) { $pool = $is_default ? $this->allTermIds( $this->supportedTaxonomies(), $limit ) : $this->allTermIds( self::wholeTaxonomies( $own_rows ), $limit ); } else { $pool = $is_default ? $this->allPublishedProductIds( $limit ) : $this->candidateProductPool( $own_rows, $limit ); } $subject_type = Generators::TAXONOMY === $generator ? 'term' : 'product'; $winners = array(); foreach ( $pool['ids'] as $candidate_id ) { if ( count( $winners ) >= $limit ) { $pool['approximate'] = true; break; } $resolution = $this->resolver->resolve( $generator, array( 'type' => $subject_type, 'id' => $candidate_id ), null, null, $rows ); if ( ! is_wp_error( $resolution ) && (int) ( $resolution['blueprintId'] ?? 0 ) === $blueprint_id ) { $winners[] = array( 'id' => $candidate_id, 'label' => (string) $resolution['subject']['label'] ); } } $winner_ids = array_map( static function ( array $w ): int { return $w['id']; }, $winners ); return array( 'total' => count( $winners ), 'ids' => $winner_ids, 'sample' => array_slice( $winners, 0, 20 ), 'approximate' => (bool) $pool['approximate'], ); } /** * Resolve the effective Blueprint for many products in one generator at * once, grouped by outcome — the data behind `GenerationSummary` for a * bulk product selection. * * Like {@see productsForBlueprint()} with its preloaded rows, this method fetches the generator's * assignment rows ONCE for the whole batch and passes them into every * per-product resolve() call, so a selection of hundreds of products * costs one assignment-rows query instead of one per product. * * Each group also lists the requested `productIds` that resolved into * it, in the order $product_ids was given, so a caller can show each * row's own structure without resolving it a second time. * * @param string $generator Generator key (the caller validates it is one of Generators::all()). * @param int[] $product_ids Product ids to resolve, already filtered to positive ints by the caller. * @return array{groups: array>, total: int, truncated: bool} */ public function resolveForProducts( string $generator, array $product_ids ): array { $truncated = count( $product_ids ) > self::RESOLVE_BATCH_HARD_CAP; if ( $truncated ) { $product_ids = array_slice( $product_ids, 0, self::RESOLVE_BATCH_HARD_CAP ); } $rows = $this->assignments->listForGenerator( $generator ); $this->primeProductCaches( $product_ids ); $buckets = array(); $blueprint_lookup = array(); foreach ( $product_ids as $product_id ) { $resolution = $this->resolver->resolve( $generator, array( 'type' => 'product', 'id' => $product_id ), null, null, $rows ); if ( is_wp_error( $resolution ) ) { continue; } $blueprint_id = $resolution['blueprintId']; $has_conflict = null !== $resolution['conflict']; $key = ( null === $blueprint_id ? 'none' : (string) $blueprint_id ) . ':' . ( $has_conflict ? '1' : '0' ); if ( ! isset( $buckets[ $key ] ) ) { $buckets[ $key ] = $this->resolveBatchGroupShape( $generator, $blueprint_id, $has_conflict, $resolution, $blueprint_lookup ); } ++$buckets[ $key ]['count']; $buckets[ $key ]['productIds'][] = $product_id; } $this->fillLastWrittenRevisions( $buckets ); usort( $buckets, static function ( array $a, array $b ): int { return $b['count'] <=> $a['count']; } ); return array( 'groups' => $buckets, 'total' => count( $product_ids ), 'truncated' => $truncated, ); } /** * The zero-count shape for one resolveForProducts() group. Looks up a * real Blueprint's name/revision (cached per blueprint id within this * one call, via $blueprint_lookup) or the built-in template's name, * mirroring {@see \AIPT\Api\ContentStructure\Integration\BlueprintIntegration::responseFields()}'s * `{id,name,revision,builtin}` shape plus the conflict/templateKey/count * fields the batch response adds. `lastWrittenRevision` always starts * `null` here — {@see fillLastWrittenRevisions()} resolves every group's * real value in one batched pass once every group for this call is * known. * * @param string $generator Generator key. * @param int|null $blueprint_id Resolution's blueprintId. * @param bool $has_conflict Whether this resolution hit a priority conflict. * @param array $resolution The full Resolution, for its blueprintName fallback. * @param array $blueprint_lookup Per-call cache of BlueprintStore::get() results, passed by reference. * @return array{blueprintId:int|null,name:string,revision:int|null,builtin:bool,templateKey:string|null,conflict:bool,count:int,lastWrittenRevision:int|null,productIds:int[]} */ private function resolveBatchGroupShape( string $generator, ?int $blueprint_id, bool $has_conflict, array $resolution, array &$blueprint_lookup ): array { if ( $has_conflict ) { return array( 'blueprintId' => null, 'name' => '', 'revision' => null, 'builtin' => false, 'templateKey' => null, 'conflict' => true, 'count' => 0, 'lastWrittenRevision' => null, 'productIds' => array(), ); } if ( null === $blueprint_id ) { $template_key = TemplateCatalog::defaultKey( $generator ); $template = TemplateCatalog::get( $generator, $template_key ); return array( 'blueprintId' => null, 'name' => null !== $template ? (string) $template['name'] : (string) $resolution['blueprintName'], 'revision' => null, 'builtin' => true, 'templateKey' => $template_key, 'conflict' => false, 'count' => 0, 'lastWrittenRevision' => null, 'productIds' => array(), ); } if ( ! array_key_exists( $blueprint_id, $blueprint_lookup ) ) { $blueprint_lookup[ $blueprint_id ] = $this->blueprints->get( $blueprint_id ); } $blueprint = $blueprint_lookup[ $blueprint_id ]; return array( 'blueprintId' => $blueprint_id, 'name' => null !== $blueprint ? (string) $blueprint['name'] : (string) $resolution['blueprintName'], 'revision' => null !== $blueprint ? (int) $blueprint['revision'] : null, 'builtin' => false, 'templateKey' => null, 'conflict' => false, 'count' => 0, 'lastWrittenRevision' => null, 'productIds' => array(), ); } /** * Resolve every group's `lastWrittenRevision` in place, in one batched * {@see SnapshotStore::highestWrittenRevisions()} call covering every * real blueprint id across every group — never one query per group and * never one per product. A conflict or built-in group has no blueprint * id to look up and is left at its existing `null`. * * @param array> $buckets resolveForProducts() groups, keyed as {@see resolveForProducts()} builds them; updated in place. * @return void */ private function fillLastWrittenRevisions( array &$buckets ): void { $blueprint_ids = array(); foreach ( $buckets as $bucket ) { if ( null !== $bucket['blueprintId'] ) { $blueprint_ids[ $bucket['blueprintId'] ] = true; } } if ( empty( $blueprint_ids ) ) { return; } $revisions = $this->snapshots->highestWrittenRevisions( array_keys( $blueprint_ids ) ); foreach ( $buckets as $key => $bucket ) { if ( null === $bucket['blueprintId'] ) { continue; } $buckets[ $key ]['lastWrittenRevision'] = $revisions[ $bucket['blueprintId'] ] ?? null; } } /** * Warm the WordPress term cache and WooCommerce product cache for a * batch of product ids before resolving each one individually, so the * per-product category/label lookups inside * {@see AssignmentResolver::buildSubjectContext()} hit cache instead of * issuing their own query per product. Mirrors * {@see \AIPT\Utils\ProductFilter\ProductFilterBuilder::primeProductCaches()}'s * own defensive function_exists() guards. * * @param int[] $product_ids Product ids to prime. * @return void */ private function primeProductCaches( array $product_ids ): void { if ( empty( $product_ids ) ) { return; } if ( function_exists( 'update_object_term_cache' ) ) { update_object_term_cache( $product_ids, 'product' ); } if ( function_exists( 'wc_get_products' ) ) { wc_get_products( array( 'include' => $product_ids, 'return' => 'objects', 'limit' => -1, ) ); } } /** * @param array> $rows Store/product assignment rows (already filtered to the target blueprint, or every category/term row for a conflict scan). * @return bool Whether $rows contains a 'store' row pointing at $blueprint_id. */ private function isStoreDefault( array $rows, int $blueprint_id ): bool { foreach ( $rows as $row ) { if ( 'store' === ( $row['targetType'] ?? '' ) ) { return (int) ( $row['blueprintId'] ?? 0 ) === $blueprint_id; } } return false; } /** * @param array> $rows 'product'/'category' rows. * @param int $cap Candidate pool hard cap. * @return array{ids:int[], approximate:bool} */ private function candidateProductPool( array $rows, int $cap ): array { $ids = array(); $approximate = false; foreach ( $rows as $row ) { if ( count( $ids ) >= $cap ) { $approximate = true; break; } if ( 'product' === ( $row['targetType'] ?? '' ) ) { $ids[ (int) $row['targetId'] ] = true; continue; } $category_ids = array( (int) $row['targetId'] ); if ( ! empty( $row['includeChildren'] ) ) { $category_ids = array_merge( $category_ids, $this->descendantTermIds( (int) $row['targetId'], 'product_cat' ) ); } $fetch = $this->productIdsInCategories( $category_ids, min( self::PER_ROW_FETCH_LIMIT, $cap ) ); if ( $fetch['approximate'] ) { $approximate = true; } foreach ( $fetch['ids'] as $product_id ) { $ids[ $product_id ] = true; } } $id_list = array_keys( $ids ); if ( count( $id_list ) > $cap ) { $id_list = array_slice( $id_list, 0, $cap ); $approximate = true; } return array( 'ids' => $id_list, 'approximate' => $approximate ); } /** * Every published product id, bounded by $limit (store-default case). * * @param int $limit Hard cap. * @return array{ids:int[], approximate:bool} */ private function allPublishedProductIds( int $limit ): array { if ( ! function_exists( 'wc_get_products' ) ) { return array( 'ids' => array(), 'approximate' => false ); } $ids = array_map( 'intval', (array) wc_get_products( array( 'limit' => $limit + 1, 'return' => 'ids', 'status' => array( 'publish' ), 'orderby' => 'ID', 'order' => 'ASC', ) ) ); $approximate = count( $ids ) > $limit; if ( $approximate ) { $ids = array_slice( $ids, 0, $limit ); } return array( 'ids' => $ids, 'approximate' => $approximate ); } /** * Every term id across $taxonomies, bounded by $limit (store-default * case for the taxonomy generator). * * @param string[] $taxonomies Taxonomy names. * @param int $limit Hard cap. * @return array{ids:int[], approximate:bool} */ private function allTermIds( array $taxonomies, int $limit ): array { if ( ! function_exists( 'get_terms' ) ) { return array( 'ids' => array(), 'approximate' => false ); } $ids = array(); foreach ( $taxonomies as $taxonomy ) { if ( count( $ids ) >= $limit ) { break; } $found = get_terms( array( 'taxonomy' => $taxonomy, 'hide_empty' => false, 'fields' => 'ids', 'number' => $limit + 1 ) ); if ( is_array( $found ) ) { foreach ( $found as $term_id ) { $ids[ (int) $term_id ] = true; } } } $id_list = array_keys( $ids ); $approximate = count( $id_list ) > $limit; if ( $approximate ) { $id_list = array_slice( $id_list, 0, $limit ); } return array( 'ids' => $id_list, 'approximate' => $approximate ); } /** * Every product taxonomy the taxonomy generator may target. * * @return string[] */ private function supportedTaxonomies(): array { if ( ! function_exists( 'get_object_taxonomies' ) ) { return array(); } return array_map( static function ( array $taxonomy ): string { return (string) $taxonomy['name']; }, ( new TaxonomyDiscoveryService() )->discoverTaxonomies() ); } /** * @param array> $rows One Blueprint's own assignment rows. * @return string[] The taxonomies its whole-taxonomy rows name. */ private static function wholeTaxonomies( array $rows ): array { $taxonomies = array(); foreach ( $rows as $row ) { if ( 'taxonomy' === ( $row['targetType'] ?? '' ) && '' !== (string) ( $row['taxonomy'] ?? '' ) ) { $taxonomies[ (string) $row['taxonomy'] ] = true; } } return array_keys( $taxonomies ); } /** * @param int[] $category_ids Term ids (already expanded with descendants, when relevant). * @param int $limit Hard cap. * @return array{ids:int[], approximate:bool} */ private function productIdsInCategories( array $category_ids, int $limit ): array { if ( empty( $category_ids ) || ! function_exists( 'wc_get_products' ) || ! function_exists( 'get_term' ) ) { return array( 'ids' => array(), 'approximate' => false ); } $slugs = array(); foreach ( $category_ids as $category_id ) { $term = get_term( $category_id, 'product_cat' ); if ( $term instanceof \WP_Term ) { $slugs[] = $term->slug; } } if ( empty( $slugs ) ) { return array( 'ids' => array(), 'approximate' => false ); } $ids = array_map( 'intval', (array) wc_get_products( array( 'category' => $slugs, 'limit' => $limit + 1, 'return' => 'ids', 'status' => array( 'publish' ), ) ) ); $approximate = count( $ids ) > $limit; if ( $approximate ) { $ids = array_slice( $ids, 0, $limit ); } return array( 'ids' => $ids, 'approximate' => $approximate ); } /** * Every descendant term id of $term_id within $taxonomy (the full * recursive tree, not only direct children). * * @param int $term_id Ancestor term id. * @param string $taxonomy Taxonomy name. * @return int[] */ private function descendantTermIds( int $term_id, string $taxonomy ): array { if ( ! function_exists( 'get_term_children' ) ) { return array(); } $children = get_term_children( $term_id, $taxonomy ); return is_array( $children ) ? array_map( 'intval', $children ) : array(); } }