*/ private const VALUE_FACT_KEYWORDS = array( 'warranty' => array( 'warranty', 'warranties', 'guarantee', 'garanti' ), 'care' => array( 'care:', 'care instructions', 'hand wash', 'machine wash', 'dry clean', 'tumble dry', 'dry flat', 'dishwasher', 'wipe clean', 'wipe with', 'bakım:', 'kuru temizleme', 'yıkama', 'bakım talimat', 'bulaşık makinesi' ), 'compat' => array( 'compatible', 'compatibility', 'works with', 'uyumlu' ), ); /** * @var SectionPlanner */ private $planner; /** * @var SourceContextBuilder */ private $sourceContextBuilder; public function __construct() { $this->planner = new SectionPlanner(); $this->sourceContextBuilder = new SourceContextBuilder(); } /** * Build the subject's field context {text, facts, numericTokens, * fieldValues, resolve, label, nameRef}, plus a resolver/label callable * so a condition or a data field selection that reaches OUTSIDE the * AI-visible allowlist can still be evaluated. * * @param array $ctx Execution context (see GeneratorInterface). * @return array */ public function buildSubjectContext( array $ctx ): array { if ( Generators::TAXONOMY === ( $ctx['generator'] ?? '' ) ) { $builder = new TermContextBuilder(); $term = $ctx['term']; $all_refs = array_column( ( new FieldCatalog() )->forScope( 'term' ), 'ref' ); $sample_products = isset( $ctx['definition']['structure']['sampleProducts'] ) ? (int) $ctx['definition']['structure']['sampleProducts'] : 10; $context = $builder->build( $term, $all_refs, $sample_products ); $context['resolve'] = function ( string $ref ) use ( $builder, $term, $sample_products ) { return $builder->resolveField( $term, $ref, $sample_products ); }; $context['label'] = function ( string $ref ) use ( $builder ) { return $builder->label( $ref ); }; $context['nameRef'] = 'term:name'; return $context; } $builder = new ProductContextBuilder(); $product = $ctx['product']; $allowed = $ctx['definition']['sources']['productFields'] ?? array(); $context = $builder->build( $product, $allowed ); $context['product'] = $product; $context['resolve'] = function ( string $ref ) use ( $builder, $product ) { return $builder->resolveField( $product, $ref ); }; $context['label'] = function ( string $ref ) use ( $builder ) { return $builder->label( $ref ); }; $context['nameRef'] = 'core:name'; return $context; } /** * @param array[] $sections Sections. * @param array $subject_context buildSubjectContext()'s result. * @param array $source_result SourceContextBuilder::build()'s result. * @param array $blueprint_items BlueprintSourcePolicy.items. * @return array Plan keyed by section id. */ public function planSections( array $sections, array $subject_context, array $source_result, array $blueprint_items ): array { $needed_refs = array(); foreach ( $sections as $section ) { if ( ! empty( $section['condition']['enabled'] ) && '' !== $section['condition']['field'] ) { $needed_refs[] = $section['condition']['field']; } if ( 'data' === ( $section['mode'] ?? '' ) && null === SectionTypeExtensions::data( (string) ( $section['type'] ?? '' ) ) ) { $needed_refs = array_merge( $needed_refs, $this->dataFieldRefs( $section, $subject_context ) ); } } $needed_refs = array_values( array_unique( $needed_refs ) ); $attribute_labels = $subject_context['attributeLabels'] ?? array(); $resolved_fields = array(); $field_labels = array(); foreach ( $needed_refs as $ref ) { $resolved_fields[ $ref ] = call_user_func( $subject_context['resolve'], $ref ); $field_labels[ $ref ] = array_key_exists( $ref, $attribute_labels ) ? $attribute_labels[ $ref ] : (string) call_user_func( $subject_context['label'], $ref ); } $plans = array(); foreach ( $sections as $section ) { $id = $section['id']; $extension = 'data' === ( $section['mode'] ?? '' ) ? SectionTypeExtensions::data( (string) ( $section['type'] ?? '' ) ) : null; if ( null !== $extension ) { $plans[ $id ] = $this->planExtensionData( $section, $extension, $subject_context, $resolved_fields, $field_labels ); continue; } if ( 'data' === ( $section['mode'] ?? '' ) ) { $data_refs = $this->dataFieldRefs( $section, $subject_context ); $data_fields = array_intersect_key( $resolved_fields, array_flip( $data_refs ) ); $plan = $this->planner->plan( $section, array( 'resolvedFields' => $data_fields, 'fieldLabels' => $field_labels ) ); $plan['resolvedFields'] = array(); $plan['sectionMissingPolicy'] = (string) ( $section['missing']['policy'] ?? 'skip' ); foreach ( $data_fields as $ref => $resolved ) { $plan['resolvedFields'][ $ref ] = $resolved + array( 'label' => $field_labels[ $ref ] ?? $ref ); } $plans[ $id ] = $plan; continue; } $signals = $this->requiredSignalsFor( $section, $subject_context, $source_result['blocks'], $blueprint_items ); $plan = $this->planner->plan( $section, array( 'resolvedFields' => $resolved_fields, 'fieldLabels' => $field_labels, 'requiredSignals' => $signals ) ); $plan['sectionMissingPolicy'] = (string) ( $section['missing']['policy'] ?? 'skip' ); $plans[ $id ] = $plan; } return $plans; } /** * Plan a `data` section an extension builds from its own data. The * data is only read for an enabled section whose condition passes, and * only for a product subject; it never joins `$resolved_fields`, so no * other section, condition or AI call can see it. * * @param array $section Normalized BlueprintSection. * @param DataSectionExtension $extension The section type's extension. * @param array $subject_context buildSubjectContext()'s result. * @param array $resolved_fields Every condition/data ref, resolved. * @param array $field_labels Their labels. * @return array Plan, carrying the data under `extensionData` and, without any, the extension's code under `extensionSkip`. */ private function planExtensionData( array $section, DataSectionExtension $extension, array $subject_context, array $resolved_fields, array $field_labels ): array { $product = $subject_context['product'] ?? null; $condition = isset( $section['condition'] ) && is_array( $section['condition'] ) ? $section['condition'] : array( 'enabled' => false ); $built = array( 'data' => null, 'skip' => '' ); if ( ! empty( $section['enabled'] ) && $product instanceof WC_Product && $this->planner->evaluateCondition( $condition, $resolved_fields ) ) { $built = $extension->dataFor( $product ); } $data = is_array( $built['data'] ?? null ) ? $built['data'] : null; $skip = (string) ( $built['skip'] ?? '' ); $plan = $this->planner->plan( $section, array( 'resolvedFields' => $resolved_fields, 'fieldLabels' => $field_labels, 'extensionData' => $data, 'extensionSkipReason' => null === $data ? $extension->skipSentence( $skip ) : '', ) ); $plan['extensionData'] = $data; $plan['extensionSkip'] = $skip; $plan['resolvedFields'] = array(); $plan['sectionMissingPolicy'] = (string) ( $section['missing']['policy'] ?? 'skip' ); return $plan; } /** * @param array $section Normalized BlueprintSection (mode 'data'). * @param array $subject_context buildSubjectContext()'s result. * @return string[] */ private function dataFieldRefs( array $section, array $subject_context ): array { if ( 'selected' === ( $section['fields']['mode'] ?? 'all' ) ) { return array_values( (array) ( $section['fields']['keys'] ?? array() ) ); } if ( isset( $subject_context['attributeRefs'] ) ) { return $subject_context['attributeRefs']; } return array_keys( $subject_context['fieldValues'] ); } /** * @param array $section Normalized BlueprintSection (mode 'ai'). * @param array $subject_context buildSubjectContext()'s result. * @param array $source_blocks SourceContextBuilder::build()'s `blocks`. * @param array $blueprint_items BlueprintSourcePolicy.items. * @return array{hasName:bool,hasAnyAllowedField:bool,hasWarranty:bool,hasCareFact:bool,hasCompatibilityFact:bool,hasOwnData?:bool} */ private function requiredSignalsFor( array $section, array $subject_context, array $source_blocks, array $blueprint_items ): array { $refs = $this->sourceContextBuilder->refsForSection( $section['sources'], $blueprint_items ); $name_ref = $subject_context['nameRef']; $field_values = $subject_context['fieldValues']; $name_value = $field_values[ $name_ref ] ?? null; $has_name = null !== $name_value && empty( $name_value['empty'] ); $has_any_field = false; foreach ( $field_values as $ref => $value ) { if ( $ref !== $name_ref && empty( $value['empty'] ) ) { $has_any_field = true; break; } } $usable_blocks = $this->sourceContextBuilder->usableBlocksForRefs( $source_blocks, $refs ); $fact_labels = array(); foreach ( $usable_blocks as $block ) { if ( ! $has_any_field && '' !== trim( (string) $block['text'] ) ) { $has_any_field = true; } foreach ( (array) $block['facts'] as $fact ) { $fact_labels[] = (string) ( $fact['label'] ?? '' ); } } $signals = array( 'hasName' => $has_name, 'hasAnyAllowedField' => $has_any_field, 'hasWarranty' => $this->signalMatches( $field_values, $fact_labels, 'warranty' ), 'hasCareFact' => $this->signalMatches( $field_values, $fact_labels, 'care' ), 'hasCompatibilityFact' => $this->signalMatches( $field_values, $fact_labels, 'compat' ), ); $type = (string) ( $section['type'] ?? '' ); if ( SectionCatalog::isIsolatedUnit( $type ) ) { $extension = SectionTypeExtensions::isolated( $type ); $product = $subject_context['product'] ?? null; $has_own_data = null !== $extension && $product instanceof WC_Product && $extension->hasData( $product ); $signals['hasOwnData'] = $has_own_data; if ( ! $has_own_data && null !== $extension && $product instanceof WC_Product ) { $specific_reason = $extension->checkReason( $product, array() ); if ( '' !== $specific_reason ) { $signals['dataStarvedReason'] = $specific_reason; } } } return $signals; } /** * Build the synthetic subject context for one isolated-unit TYPE's own * AI call (SectionCatalog::isIsolatedUnit()): built by the type's * extension from data specific to that type alone, never from the * subject's own product/term fields, so its data can never leak into * any other pending section's call and no other section's data ever * reaches this one. * * @param string $type Isolated section type. * @param array $ctx Execution context (see GeneratorInterface). * @return array{text:string,facts:array,numericTokens:string[]} */ public function buildIsolatedSubjectContext( string $type, array $ctx ): array { $extension = SectionTypeExtensions::isolated( $type ); $product = $ctx['product'] ?? null; if ( null !== $extension && $product instanceof WC_Product ) { return $extension->context( $product ); } return array( 'text' => '', 'facts' => array(), 'numericTokens' => array() ); } /** * Whether the subject's fields or the given source facts carry a * warranty, care or compatibility fact: the check those section types * are planned by, shared with FAQ groups on the same topics. * * @param array $field_values ref => resolved. * @param string[] $fact_labels Source fact labels. * @param string $keyword 'warranty', 'care' or 'compat'. * @return bool */ public function hasTopicFact( array $field_values, array $fact_labels, string $keyword ): bool { return $this->signalMatches( $field_values, $fact_labels, $keyword ); } /** * @param array $field_values ref => resolved. * @param string[] $fact_labels Source fact labels. * @param string $keyword Case-insensitive substring to look for. * @return bool */ private function signalMatches( array $field_values, array $fact_labels, string $keyword ): bool { foreach ( $field_values as $ref => $value ) { if ( false !== stripos( $ref, $keyword ) && empty( $value['empty'] ) ) { return true; } } foreach ( $fact_labels as $label ) { if ( false !== stripos( $label, $keyword ) ) { return true; } } return $this->valueTextMatches( $field_values, $keyword ); } /** * Whether an in-scope field's own resolved VALUE (never its ref key or * an external fact's label — both already checked above) names a * $keyword category fact: the gap those two checks leave open, since a * product's long/short description or an attribute's value can state * "Hand wash cold, dry flat" without the field's ref ever containing * "care" (seen live: a dedicated care section skipped as data-starved * while that exact sentence sat in the product's own description). * Scoped to the handful of fields free text actually lives in * (description, short description, attributes) so an unrelated field * (price, SKU, categories, …) can never trip a signal on an incidental * word. * * @param array $field_values Ref => resolved {type,value,empty}. * @param string $keyword One of self::VALUE_FACT_KEYWORDS's keys. * @return bool */ private function valueTextMatches( array $field_values, string $keyword ): bool { $needles = self::VALUE_FACT_KEYWORDS[ $keyword ] ?? array(); if ( empty( $needles ) ) { return false; } foreach ( $field_values as $ref => $value ) { if ( ! $this->isValueScannedRef( (string) $ref ) || ! empty( $value['empty'] ) ) { continue; } $text = $this->scannedValueText( $value ); foreach ( $needles as $needle ) { if ( false !== mb_stripos( $text, $needle, 0, 'UTF-8' ) ) { return true; } } } return false; } /** * @param string $ref FieldRef. * @return bool Whether $ref's own resolved value is free text worth * keyword-searching for a care/warranty/compatibility fact * ({@see valueTextMatches()}) — the description, the short * description, or an attribute (individually, or via the * "all attributes" pairs field). */ private function isValueScannedRef( string $ref ): bool { return in_array( $ref, array( 'core:description', 'core:short_description', 'core:attributes' ), true ) || 0 === strpos( $ref, 'attr:' ); } /** * @param array $resolved {type,value,empty}. * @return string Plain text to keyword-search; `pairs` are flattened to * "label value label value…" so an attribute's own name * can also carry the fact (e.g. a "Washing instructions" * attribute whose ref name itself says nothing about * "care"). */ private function scannedValueText( array $resolved ): string { if ( 'pairs' === ( $resolved['type'] ?? '' ) ) { $parts = array(); foreach ( (array) ( $resolved['value'] ?? array() ) as $pair ) { $parts[] = (string) ( is_array( $pair ) ? ( $pair['label'] ?? '' ) : '' ); $parts[] = (string) ( is_array( $pair ) ? ( $pair['value'] ?? '' ) : '' ); } return implode( ' ', $parts ); } return (string) ( $resolved['value'] ?? '' ); } }