assignments = $assignments ?? new AssignmentStore(); $this->blueprints = $blueprints ?? new BlueprintStore(); $this->snapshots = $snapshots ?? new SnapshotStore(); $this->entitlementPolicy = $entitlementPolicy ?? new EntitlementPolicy(); } /** * @param string $generator Generator key (already validated by the caller). * @param array>|null $preloaded_rows This generator's assignment rows, already fetched by the caller, used instead of a fresh AssignmentStore::listForGenerator() call. * @param bool $with_history Whether to look up each slot's `lastWrittenRevision`; a signature leaves it out, so its builder skips the query. * @return array StructureState. */ public function build( string $generator, ?array $preloaded_rows = null, bool $with_history = true ): array { $rows = $preloaded_rows ?? $this->assignments->listForGenerator( $generator ); $default_row = $this->findRow( $rows, 'store' ); $default_blueprint_id = null !== $default_row ? (int) $default_row['blueprintId'] : null; $default_blueprint = null !== $default_blueprint_id ? $this->lookupBlueprint( $default_blueprint_id ) : null; if ( null !== $default_blueprint_id && null === $default_blueprint ) { $default_blueprint_id = null; } $extra_slots_locked = ! $this->entitlementPolicy->extraSlotsAllowed(); $slots = array(); $order = array(); $slots[] = $this->slotShape( 'default', 'default', null !== $default_blueprint ? $this->blueprintSummary( $default_blueprint ) : null, null === $default_blueprint ? $this->builtInShape( $generator ) : null, array(), false, self::slotLanguage( $default_blueprint ) ); if ( Generators::TAXONOMY === $generator ) { $tags_row = $this->findTaxonomyRow( $rows, self::TAGS_TAXONOMY ); if ( null !== $tags_row ) { $tags_blueprint = $this->lookupBlueprint( (int) $tags_row['blueprintId'] ); if ( null !== $tags_blueprint ) { $slots[] = $this->slotShape( 'tags', 'tags', $this->blueprintSummary( $tags_blueprint ), null, array(), $extra_slots_locked, self::slotLanguage( $tags_blueprint ) ); } } } else { foreach ( $this->orderedExceptionGroups( $rows, $default_blueprint_id ) as $blueprint_id => $category_rows ) { $blueprint = $this->lookupBlueprint( $blueprint_id ); if ( null === $blueprint ) { continue; } $key = 'exception:' . $blueprint_id; $slots[] = $this->slotShape( $key, 'exception', $this->blueprintSummary( $blueprint ), null, $this->categoriesShape( $category_rows ), $extra_slots_locked, self::slotLanguage( $blueprint ) ); $order[] = $key; } } if ( $with_history ) { $this->fillLastWrittenRevisions( $slots ); } return array( 'generator' => $generator, 'executionMode' => BlueprintIntegration::executionPath( $generator )['path'], 'slots' => $slots, 'order' => $order, 'historyEnabled' => SnapshotStore::historyCaptureEnabled(), 'storeLanguage' => (string) get_option( 'aipt_language', 'English' ), 'multilingual' => function_exists( 'pll_get_post_language' ) || defined( 'ICL_SITEPRESS_VERSION' ), ); } /** * Reshape a built StructureState into the smaller StructureSignature * the localized data block carries for every generator (no counts, no * categories beyond their names, no built-in template name). * * @param array $state A build() result. * @return array StructureSignature. */ public static function toSignature( array $state ): array { $slots = array(); foreach ( $state['slots'] as $slot ) { $blueprint = $slot['blueprint']; $slots[ $slot['key'] ] = array( 'kind' => $slot['kind'], 'blueprintId' => null !== $blueprint ? (int) $blueprint['id'] : 0, 'revision' => null !== $blueprint ? (int) $blueprint['revision'] : 0, 'updatedBy' => null !== $blueprint ? $blueprint['updatedBy'] : null, 'categoryNames' => array_map( static function ( array $category ): string { return $category['name']; }, $slot['categories'] ), ); } return array( 'executionMode' => $state['executionMode'], 'slots' => $slots, 'order' => $state['order'], ); } /** * @param string $key Slot key. * @param string $kind 'default'|'exception'|'tags'. * @param array|null $blueprint StructureSlotBlueprint, or null for a built-in default. * @param array|null $built_in {templateKey,name}, or null when a Blueprint is saved. * @param array> $categories StructureSlotCategory list (exceptions only). * @param bool $locked Whether this slot's own assignment exists but this plan does not apply it (Business); always false for 'default'. * @param string $language The structure's own output language, or 'store' ({@see slotLanguage()}). * @return array StructureSlot, with zeroed counts/sample (filled in separately when requested). */ private function slotShape( string $key, string $kind, ?array $blueprint, ?array $built_in, array $categories, bool $locked, string $language ): array { return array( 'key' => $key, 'kind' => $kind, 'blueprint' => $blueprint, 'builtIn' => $built_in, 'categories' => $categories, 'locked' => $locked, 'language' => $language, 'counts' => array( 'subjects' => 0, 'approximate' => false, 'automationJobs' => 0 ), 'lastWrittenRevision' => null, 'sample' => array(), ); } /** * The output language a slot's structure sets in its rules: a * language name, or 'store' when it follows the store language (a * built-in template never sets one). * * @param array|null $blueprint Raw BlueprintStore row, or null for a built-in default. * @return string */ private static function slotLanguage( ?array $blueprint ): string { $language = trim( (string) ( $blueprint['definition']['rules']['language'] ?? '' ) ); return ( '' === $language || 'store' === strtolower( $language ) ) ? 'store' : $language; } /** * @param array $blueprint Raw BlueprintStore row. * @return array StructureSlotBlueprint. */ private function blueprintSummary( array $blueprint ): array { return array( 'id' => (int) $blueprint['id'], 'name' => (string) $blueprint['name'], 'revision' => (int) $blueprint['revision'], 'updatedAt' => self::isoDate( (string) ( $blueprint['updatedAt'] ?? '' ) ), 'updatedBy' => self::userSummary( (int) ( $blueprint['updatedBy'] ?? 0 ) ), 'brandProfileId' => (int) $blueprint['brandProfileId'] > 0 ? (int) $blueprint['brandProfileId'] : null, ); } /** * @param string $generator Generator key. * @return array{templateKey:string,name:string} */ private function builtInShape( string $generator ): array { $template_key = TemplateCatalog::defaultKey( $generator ); $template = TemplateCatalog::get( $generator, $template_key ); return array( 'templateKey' => $template_key, 'name' => null !== $template ? (string) $template['name'] : $template_key, ); } /** * @param array> $category_rows Category assignment rows of one exception, each a raw AssignmentStore row. * @return array> StructureSlotCategory list. */ private function categoriesShape( array $category_rows ): array { $categories = array(); foreach ( $category_rows as $row ) { $term_id = (int) $row['targetId']; $term = function_exists( 'get_term' ) ? get_term( $term_id, 'product_cat' ) : null; $categories[] = array( 'id' => $term_id, 'name' => $term instanceof \WP_Term ? html_entity_decode( (string) $term->name, ENT_QUOTES, 'UTF-8' ) : '', 'productCount' => $term instanceof \WP_Term ? (int) $term->count : 0, 'hasChildren' => ! empty( $row['includeChildren'] ), ); } return $categories; } /** * @param array> $rows Every row for this generator. * @param string $target_type Target type to find. * @return array|null */ private function findRow( array $rows, string $target_type ): ?array { foreach ( $rows as $row ) { if ( $target_type === ( $row['targetType'] ?? '' ) ) { return $row; } } return null; } /** * @param array> $rows Every row for this generator. * @param string $taxonomy Taxonomy name. * @return array|null */ private function findTaxonomyRow( array $rows, string $taxonomy ): ?array { foreach ( $rows as $row ) { if ( 'taxonomy' === ( $row['targetType'] ?? '' ) && $taxonomy === (string) ( $row['taxonomy'] ?? '' ) ) { return $row; } } return null; } /** * Group every 'category' row by blueprint id (skipping any row that * points at the default's own Blueprint — that blueprint already has * its 'default' slot, so it is never ALSO listed as an exception), and * order the groups by their rows' priority then blueprint id, matching * the write endpoints' own priority assignment (10, 20, 30, ... in * creation order). * * @param array> $rows Every row for this generator. * @param int|null $default_blueprint_id The default slot's Blueprint id, or null. * @return array>> Blueprint id => its category rows, already ordered. */ private function orderedExceptionGroups( array $rows, ?int $default_blueprint_id ): array { $groups = array(); $min_priority = array(); foreach ( $rows as $row ) { if ( 'category' !== ( $row['targetType'] ?? '' ) ) { continue; } $blueprint_id = (int) $row['blueprintId']; if ( $blueprint_id === $default_blueprint_id ) { continue; } $groups[ $blueprint_id ][] = $row; $priority = (int) ( $row['priority'] ?? 10 ); $min_priority[ $blueprint_id ] = isset( $min_priority[ $blueprint_id ] ) ? min( $min_priority[ $blueprint_id ], $priority ) : $priority; } uksort( $groups, static function ( int $a, int $b ) use ( $min_priority ): int { $cmp = ( $min_priority[ $a ] ?? 10 ) <=> ( $min_priority[ $b ] ?? 10 ); return 0 !== $cmp ? $cmp : $a <=> $b; } ); return $groups; } /** * Fill every slot's `lastWrittenRevision` in place, in one batched * {@see SnapshotStore::highestWrittenRevisions()} call — skipped * entirely (every slot keeps `null`) when Content History is off. * * @param array> &$slots Slots built so far, updated in place. * @return void */ private function fillLastWrittenRevisions( array &$slots ): void { if ( ! SnapshotStore::historyCaptureEnabled() ) { return; } $blueprint_ids = array(); foreach ( $slots as $slot ) { if ( null !== $slot['blueprint'] ) { $blueprint_ids[ (int) $slot['blueprint']['id'] ] = true; } } if ( empty( $blueprint_ids ) ) { return; } $revisions = $this->snapshots->highestWrittenRevisions( array_keys( $blueprint_ids ) ); foreach ( $slots as $key => $slot ) { if ( null === $slot['blueprint'] ) { continue; } $slots[ $key ]['lastWrittenRevision'] = $revisions[ (int) $slot['blueprint']['id'] ] ?? null; } } /** * @param int $blueprint_id Blueprint id. * @return array|null */ private function lookupBlueprint( int $blueprint_id ): ?array { return $this->blueprints->get( $blueprint_id ); } /** * @param string $mysql_utc MySQL UTC datetime, or '' for "unset". * @return string */ private static function isoDate( string $mysql_utc ): string { if ( '' === $mysql_utc ) { return ''; } $timestamp = strtotime( $mysql_utc . ' UTC' ); return false !== $timestamp ? gmdate( 'c', $timestamp ) : ''; } /** * @param int $user_id User id. * @return array{id:int,name:string}|null */ private static function userSummary( int $user_id ): ?array { if ( $user_id <= 0 ) { return null; } $user = get_userdata( $user_id ); if ( false === $user ) { return null; } return array( 'id' => $user_id, 'name' => (string) $user->display_name ); } }