` content * for the same field selection. * * @package AIPT\Api\ContentStructure\Engine\Context * @since 2.8.0 */ namespace AIPT\Api\ContentStructure\Engine\Context; use AIPT\Core\ContentStructure\Domain\FieldCatalog; use WC_Product; defined( 'ABSPATH' ) || exit; /** * Product-scope context builder. */ class ProductContextBuilder { use FieldContextTrait; /** * @var FieldCatalog */ private $fields; /** * @param FieldCatalog|null $fields Field catalog; a default instance is * constructed when omitted. */ public function __construct( ?FieldCatalog $fields = null ) { $this->fields = $fields ?? new FieldCatalog(); } /** * Build the allowed product context. * * @param WC_Product $product Product. * @param string[] $allowed_refs FieldRefs the policy allows (unordered). * @return array{text:string,facts:array,numericTokens:string[],fieldValues:array,attributeRefs:string[],attributeLabels:array} */ public function build( WC_Product $product, array $allowed_refs ): array { $ordered_refs = $this->orderedRefs( $allowed_refs ); $context = $this->composeFieldContext( $ordered_refs, function ( string $ref ) use ( $product ) { return $this->fields->productValue( $product, $ref ); }, function ( string $ref ) { return $this->fields->label( $ref ); } ); $attribute_ref_labels = $this->fields->attributeRefLabelsForProduct( $product ); $context['attributeRefs'] = array_keys( $attribute_ref_labels ); $context['attributeLabels'] = $attribute_ref_labels; return $context; } /** * Resolve a single FieldRef directly, independent of the policy * allowlist. Used by the planner to evaluate a section `condition` or a * `data` mode field selection that was not necessarily included in * `sources.productFields` (the AI-visible allowlist is a separate * concept from "this field exists and the plugin may read it"). * * @param WC_Product $product Product. * @param string $ref FieldRef. * @return array{type:string,value:mixed,empty:bool} */ public function resolveField( WC_Product $product, string $ref ): array { return $this->fields->productValue( $product, $ref ); } /** * Label for a FieldRef (delegates to FieldCatalog). * * @param string $ref FieldRef. * @return string */ public function label( string $ref ): string { return $this->fields->label( $ref ); } /** * Order $allowed_refs by the FieldCatalog's own catalog order, dropping * any ref the catalog does not know (defense in depth: the definition * was already validated by DefinitionNormalizer, so this should not * happen in practice). * * @param string[] $allowed_refs Allowed FieldRefs. * @return string[] */ private function orderedRefs( array $allowed_refs ): array { $allowed = array_fill_keys( $allowed_refs, true ); $ordered = array(); foreach ( $this->fields->forScope( 'product' ) as $entry ) { if ( isset( $allowed[ $entry['ref'] ] ) ) { $ordered[] = $entry['ref']; } } return $ordered; } }