fields = $fields ?? new FieldCatalog(); } /** * Every image of $product, in position order. * * @param WC_Product $product Product. * @return array */ public function imagesForProduct( WC_Product $product ): array { $images = array(); $featured_id = (int) $product->get_image_id(); if ( $featured_id > 0 ) { $images[] = array( 'attachmentId' => $featured_id, 'isFeatured' => true ); } foreach ( (array) $product->get_gallery_image_ids() as $gallery_id ) { $gallery_id = (int) $gallery_id; if ( $gallery_id > 0 && $gallery_id !== $featured_id ) { $images[] = array( 'attachmentId' => $gallery_id, 'isFeatured' => false ); } } foreach ( $images as $position => $image ) { $images[ $position ]['position'] = $position; } return $images; } /** * Build the allowed context for one image. * * @param int $attachment_id Attachment id. * @param int $product_id Parent product id. * @param int $position 0-based position among the product's images. * @param string[] $allowed_refs FieldRefs to resolve (unordered). * @return array{text:string,facts:array,numericTokens:string[],fieldValues:array} */ public function build( int $attachment_id, int $product_id, int $position, array $allowed_refs ): array { $ordered_refs = $this->orderedRefs( $allowed_refs ); return $this->composeFieldContext( $ordered_refs, function ( string $ref ) use ( $attachment_id, $product_id, $position ) { return $this->fields->imageValue( $attachment_id, $product_id, $position, $ref ); }, function ( string $ref ) { return $this->fields->label( $ref ); } ); } /** * @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( 'image' ) as $entry ) { if ( isset( $allowed[ $entry['ref'] ] ) ) { $ordered[] = $entry['ref']; } } return $ordered; } }