few * large files") instead of one 1000+ line module. * * @package AIPT\Core\ContentStructure\Domain * @since 2.8.0 */ namespace AIPT\Core\ContentStructure\Domain; use AIPT\Api\ProductEditor\ContentDefaultsService; defined( 'ABSPATH' ) || exit; /** * Normalizes and validates Blueprint definitions for all six generators. */ class DefinitionNormalizer { /** * Product fields every new definition reads (`sources.productFields`), * for every generator and every starter template. Public because * `EntitlementPolicy` withholds the paid ones among them on Free without * reporting it: a merchant never chose them. * * @var string[] */ public const DEFAULT_PRODUCT_FIELDS = array( 'core:name', 'core:attributes', 'core:categories', 'core:short_description', 'core:grouped_children' ); /** * @var FieldCatalog */ private $fields; /** * @var FormulaStructureNormalizer */ private $formula; /** * @param FieldCatalog|null $fields Field catalog; a default instance is * constructed when omitted. */ public function __construct( ?FieldCatalog $fields = null ) { $this->fields = $fields ?? new FieldCatalog(); $this->formula = new FormulaStructureNormalizer( $this->fields ); } /** * Normalize and validate a Blueprint definition for one generator. * * @param string $generator One of Generators::all(). * @param array $input Raw decoded definition (the whole * BlueprintDefinition object: schemaVersion, * structure, voice, sources, rules). * @param array $context array{knownSourceIds?: int[], allowCustomFields?: bool, validateOnSave?: bool}. * A `meta:` field ref is only ever accepted when * allowCustomFields is explicitly true; omitting * it fails closed. `validateOnSave` enables the * "pointless definition" semantic checks (an * empty selected-fields section, an empty fixed * section, a blueprint with no enabled section); * omitting it (the default) keeps those checks * off, which every execution-time caller * (resolving an already-stored, previously * validated definition) relies on so a pinned * run never starts failing against a new rule. * Only the save paths (create and update) * pass it true; duplicate copies a stored * definition without re-validating it. * @return array{definition: array, errors: array, notices: array} */ public function normalize( string $generator, array $input, array $context = array() ): array { $errors = array(); $notices = array(); if ( ! Generators::isValid( $generator ) ) { $errors[] = DefinitionPrimitives::issue( 'generator', 'invalid_enum', __( 'Unknown generator.', 'ai-product-tools' ) ); return array( 'definition' => array(), 'errors' => $errors, 'notices' => $notices, ); } $defaults = $this->defaults( $generator ); $scope = $this->scopeFor( $generator ); $known_source_ids = array_map( 'intval', is_array( $context['knownSourceIds'] ?? null ) ? $context['knownSourceIds'] : array() ); $allow_custom_fields = DefinitionPrimitives::boolOr( $context['allowCustomFields'] ?? false, false ); $validate_on_save = DefinitionPrimitives::boolOr( $context['validateOnSave'] ?? false, false ); $schema_version = DefinitionPrimitives::intOr( $input['schemaVersion'] ?? null, $defaults['schemaVersion'] ); $structure_input = is_array( $input['structure'] ?? null ) ? $input['structure'] : array(); $structure = $this->normalizeStructure( $generator, $structure_input, $defaults['structure'], $scope, $known_source_ids, $allow_custom_fields, $validate_on_save, $errors, $notices ); $voice = $this->normalizeVoice( is_array( $input['voice'] ?? null ) ? $input['voice'] : array(), $defaults['voice'], $errors ); $sources = $this->normalizeSourcePolicy( is_array( $input['sources'] ?? null ) ? $input['sources'] : array(), $defaults['sources'], $known_source_ids, $allow_custom_fields, $errors ); $rules = $this->normalizeRules( is_array( $input['rules'] ?? null ) ? $input['rules'] : array(), $defaults['rules'], $errors ); return array( 'definition' => array( 'schemaVersion' => $schema_version, 'structure' => $structure, 'voice' => $voice, 'sources' => $sources, 'rules' => $rules, ), 'errors' => $errors, 'notices' => $notices, ); } /** * Catalog defaults for a brand-new definition of $generator, and the * values normalize() backfills for any top-level key an input omits. * * This does not guarantee the result independently satisfies every * validation rule for every generator (e.g. `title` requires at least * one part; the empty `parts: []` default does not). A generator's * actual safe starting point is a built-in template * (`Templates\TemplateCatalog`), not this method. * * @param string $generator One of Generators::all(). * @return array BlueprintDefinition-shaped array. */ public function defaults( string $generator ): array { return array( 'schemaVersion' => 1, 'structure' => $this->defaultStructure( $generator ), 'voice' => array( 'expression' => null, 'note' => '' ), 'sources' => array( 'productFields' => self::DEFAULT_PRODUCT_FIELDS, 'items' => array( array( 'ref' => 'product', 'enabled' => true ) ), 'conflictPolicy' => 'review', 'allowedDomains' => array(), ), 'rules' => array( 'language' => 'store', 'headingLevel' => 'h2', 'bannedPhrases' => array(), 'requiredFailure' => 'review', 'instructions' => array(), ), ); } /** * FieldCatalog scope for a generator's primary subject. * * @param string $generator One of Generators::all(). * @return string 'product' | 'term' | 'image'. */ private function scopeFor( string $generator ): string { if ( Generators::TAXONOMY === $generator ) { return 'term'; } if ( Generators::IMAGE_ALT === $generator ) { return 'image'; } return 'product'; } /** * Empty/blank structure for one generator, used by defaults(). * * @param string $generator One of Generators::all(). * @return array */ private function defaultStructure( string $generator ): array { switch ( $generator ) { case Generators::DESCRIPTION: return array( 'sections' => array(), 'companions' => array( 'shortDescription' => array( 'format' => 'paragraph', 'length' => array( 'targetMin' => 40, 'targetMax' => 60, 'hardMax' => null ), 'items' => array( 'max' => 5 ), ), 'tags' => array( 'max' => 10 ), ), ); case Generators::TAXONOMY: return array( 'sections' => array(), 'sampleProducts' => 10 ); case Generators::TITLE: return array( 'parts' => array(), 'separator' => 'dash', 'maxChars' => 60, 'overflowDropPartId' => null, 'dedupe' => true, 'keywords' => array(), ); case Generators::SEO_META: return array( 'title' => array( 'tokens' => array(), 'separator' => 'pipe', 'targetMin' => 40, 'targetMax' => 60, 'hardMax' => 60 ), 'description' => array( 'tokens' => array(), 'targetMin' => 120, 'targetMax' => 160, 'hardMax' => 160 ), 'keyword' => array( 'source' => 'focus_keyword', 'once' => true ), ); case Generators::FAQ: return array( 'groups' => array(), 'maxQuestions' => 8, 'mode' => 'both' ); case Generators::IMAGE_ALT: return array( 'context' => 'product_data', 'maxChars' => 125, 'rules' => array( 'noImageOf' => true, 'keywordOnce' => true, 'varyAcrossImages' => true, 'includeColor' => false, 'includeProductName' => true, ), 'instruction' => '', 'starter' => '', ); default: return array(); } } /** * Dispatch to the per-generator structure normalizer. * * @param string $generator One of Generators::all(). * @param array $input Raw structure input. * @param array $default defaultStructure() for this generator. * @param string $scope FieldCatalog scope. * @param int[] $known_source_ids Ids valid for 'src:' refs. * @param bool $allow_custom_fields Context flag. * @param bool $validate_on_save Whether this normalize() call is a save. * @param array &$errors Collected errors. * @param array &$notices Collected notices. * @return array */ private function normalizeStructure( string $generator, array $input, array $default, string $scope, array $known_source_ids, bool $allow_custom_fields, bool $validate_on_save, array &$errors, array &$notices ): array { switch ( $generator ) { case Generators::DESCRIPTION: return $this->normalizeDescriptionStructure( $input, $default, $scope, $known_source_ids, $allow_custom_fields, $validate_on_save, $errors, $notices ); case Generators::TAXONOMY: return $this->normalizeTaxonomyStructure( $input, $default, $scope, $known_source_ids, $allow_custom_fields, $validate_on_save, $errors, $notices ); case Generators::TITLE: return $this->formula->normalizeTitleStructure( $input, $default, $scope, $allow_custom_fields, $errors ); case Generators::SEO_META: return $this->formula->normalizeSeoMetaStructure( $input, $default, $scope, $allow_custom_fields, $errors ); case Generators::FAQ: return $this->formula->normalizeFaqStructure( $input, $default, $scope, $known_source_ids, $allow_custom_fields, $errors ); case Generators::IMAGE_ALT: return $this->formula->normalizeImageAltStructure( $input, $default, $errors ); default: return array(); } } /** * @param array $input Raw structure input. * @param array $default Default structure. * @param string $scope FieldCatalog scope ('product'). * @param int[] $known_source_ids Ids valid for 'src:' refs. * @param bool $allow_custom_fields Context flag. * @param bool $validate_on_save Whether this normalize() call is a save. * @param array &$errors Collected errors. * @param array &$notices Collected notices. * @return array{sections:array,companions:array} */ private function normalizeDescriptionStructure( array $input, array $default, string $scope, array $known_source_ids, bool $allow_custom_fields, bool $validate_on_save, array &$errors, array &$notices ): array { $sections = $this->normalizeSectionList( is_array( $input['sections'] ?? null ) ? $input['sections'] : array(), array_keys( SectionCatalog::typesFor( Generators::DESCRIPTION ) ), $scope, $known_source_ids, $allow_custom_fields, $validate_on_save, 'structure.sections', $errors, $notices ); DefinitionPrimitives::requireAnEnabledSection( $sections, $validate_on_save, 'structure.sections', $errors ); $companions_input = is_array( $input['companions'] ?? null ) ? $input['companions'] : array(); $short_input = is_array( $companions_input['shortDescription'] ?? null ) ? $companions_input['shortDescription'] : array(); $short_default = $default['companions']['shortDescription']; $short_format = $short_input['format'] ?? $short_default['format']; if ( ! DefinitionPrimitives::inEnum( $short_format, array( 'paragraph', 'bullets' ) ) ) { $errors[] = DefinitionPrimitives::issue( 'structure.companions.shortDescription.format', 'invalid_enum', __( 'Invalid short description format.', 'ai-product-tools' ) ); $short_format = $short_default['format']; } $short_length = DefinitionPrimitives::wordRange( $short_input['length'] ?? null, $short_default['length'], 'structure.companions.shortDescription.length', $errors ); $short_items = DefinitionPrimitives::items( $short_input['items'] ?? null, $short_default['items'], 'ai', 'structure.companions.shortDescription.items', $errors ); $tags_input = is_array( $companions_input['tags'] ?? null ) ? $companions_input['tags'] : array(); $tags_max = DefinitionPrimitives::intOr( $tags_input['max'] ?? null, $default['companions']['tags']['max'] ); if ( $tags_max < 1 || $tags_max > DefinitionPrimitives::AI_ITEMS_MAX ) { $errors[] = DefinitionPrimitives::issue( 'structure.companions.tags.max', 'out_of_range', __( 'Tag limit is out of range.', 'ai-product-tools' ) ); } return array( 'sections' => $sections, 'companions' => array( 'shortDescription' => array( 'format' => $short_format, 'length' => $short_length, 'items' => array( 'max' => $short_items['max'] ), ), 'tags' => array( 'max' => $tags_max ), ), ); } /** * @param array $input Raw structure input. * @param array $default Default structure. * @param string $scope FieldCatalog scope ('term'). * @param int[] $known_source_ids Ids valid for 'src:' refs. * @param bool $allow_custom_fields Context flag. * @param bool $validate_on_save Whether this normalize() call is a save. * @param array &$errors Collected errors. * @param array &$notices Collected notices. * @return array{sections:array,sampleProducts:int} */ private function normalizeTaxonomyStructure( array $input, array $default, string $scope, array $known_source_ids, bool $allow_custom_fields, bool $validate_on_save, array &$errors, array &$notices ): array { $sections = $this->normalizeSectionList( is_array( $input['sections'] ?? null ) ? $input['sections'] : array(), array_keys( SectionCatalog::typesFor( Generators::TAXONOMY ) ), $scope, $known_source_ids, $allow_custom_fields, $validate_on_save, 'structure.sections', $errors, $notices ); DefinitionPrimitives::requireAnEnabledSection( $sections, $validate_on_save, 'structure.sections', $errors ); $sample_products = DefinitionPrimitives::intOr( $input['sampleProducts'] ?? null, $default['sampleProducts'] ); if ( $sample_products < DefinitionPrimitives::TAXONOMY_SAMPLE_PRODUCTS_MIN || $sample_products > DefinitionPrimitives::TAXONOMY_SAMPLE_PRODUCTS_MAX ) { $errors[] = DefinitionPrimitives::issue( 'structure.sampleProducts', 'out_of_range', __( 'Sample product count is out of range.', 'ai-product-tools' ) ); } return array( 'sections' => $sections, 'sampleProducts' => $sample_products ); } /** * Normalize a BlueprintSection[] list: 0..SECTIONS_MAX items, each * validated by type pool, with duplicate/invalid ids rejected across * the whole list (not silently renamed). * * @param array $raw_sections Raw section list. * @param string[] $type_pool Valid `type` values for this generator. * @param string $scope FieldCatalog scope. * @param int[] $known_source_ids Ids valid for 'src:' refs. * @param bool $allow_custom_fields Context flag. * @param bool $validate_on_save Whether this normalize() call is a save. * @param string $path Error path prefix (no trailing dot). * @param array &$errors Collected errors. * @param array &$notices Collected notices. * @return array */ private function normalizeSectionList( array $raw_sections, array $type_pool, string $scope, array $known_source_ids, bool $allow_custom_fields, bool $validate_on_save, string $path, array &$errors, array &$notices ): array { if ( count( $raw_sections ) > DefinitionPrimitives::SECTIONS_MAX ) { $errors[] = DefinitionPrimitives::issue( $path, 'too_many', __( 'Too many sections.', 'ai-product-tools' ) ); $raw_sections = array_slice( $raw_sections, 0, DefinitionPrimitives::SECTIONS_MAX ); } $seen_ids = array(); $sections = array(); foreach ( array_values( $raw_sections ) as $index => $raw_section ) { if ( ! is_array( $raw_section ) ) { $errors[] = DefinitionPrimitives::issue( $path . '[' . $index . ']', 'invalid_shape', __( 'Invalid section.', 'ai-product-tools' ) ); continue; } $sections[] = $this->normalizeSection( $raw_section, $type_pool, $scope, $known_source_ids, $allow_custom_fields, $validate_on_save, $path . '[' . $index . ']', $seen_ids, $errors, $notices ); } return $sections; } /** * Normalize one BlueprintSection. * * @param array $item Raw section. * @param string[] $type_pool Valid `type` values for this generator. * @param string $scope FieldCatalog scope. * @param int[] $known_source_ids Ids valid for 'src:' refs. * @param bool $allow_custom_fields Context flag. * @param bool $validate_on_save Whether this normalize() call is a save. * @param string $path Error path for this item (no trailing dot). * @param array &$seen_ids Ids already used earlier in this list. * @param array &$errors Collected errors. * @param array &$notices Collected notices. * @return array BlueprintSection-shaped array. */ private function normalizeSection( array $item, array $type_pool, string $scope, array $known_source_ids, bool $allow_custom_fields, bool $validate_on_save, string $path, array &$seen_ids, array &$errors, array &$notices ): array { $id = DefinitionPrimitives::normalizeId( $item['id'] ?? null, $path, $seen_ids, $errors ); $type = $item['type'] ?? ''; if ( ! in_array( $type, $type_pool, true ) ) { $errors[] = DefinitionPrimitives::issue( $path . '.type', 'invalid_enum', __( 'Invalid section type.', 'ai-product-tools' ) ); $type = $type_pool[0] ?? 'custom'; } $catalog_entry = SectionCatalog::get( $type ); $default_row = SectionCatalog::newSection( $type ); $enabled = DefinitionPrimitives::boolOr( $item['enabled'] ?? null, true ); $allowed_modes = null !== $catalog_entry ? $catalog_entry['modes'] : array( 'ai' ); $mode = $item['mode'] ?? $default_row['mode']; if ( ! DefinitionPrimitives::inEnum( $mode, $allowed_modes ) ) { $errors[] = DefinitionPrimitives::issue( $path . '.mode', 'invalid_enum', __( 'This mode is not allowed for this section type.', 'ai-product-tools' ) ); $mode = $default_row['mode']; } $allowed_formats = ( null !== $catalog_entry && isset( $catalog_entry['formats'][ $mode ] ) ) ? $catalog_entry['formats'][ $mode ] : array( 'paragraph' ); $format = $item['format'] ?? $default_row['format']; if ( ! DefinitionPrimitives::inEnum( $format, $allowed_formats ) ) { $errors[] = DefinitionPrimitives::issue( $path . '.format', 'invalid_enum', __( 'This format is not allowed for this section mode.', 'ai-product-tools' ) ); $format = $allowed_formats[0]; } $name_result = DefinitionPrimitives::singleLineText( $item['name'] ?? $default_row['name'], DefinitionPrimitives::NAME_MAX_LEN ); if ( $name_result['overLimit'] ) { $errors[] = DefinitionPrimitives::issue( $path . '.name', 'too_long', __( 'Section name is too long.', 'ai-product-tools' ) ); } $heading = DefinitionPrimitives::heading( $item['heading'] ?? null, $default_row['heading'], $path . '.heading', $errors ); $focus_result = DefinitionPrimitives::singleLineText( $item['focus'] ?? '', DefinitionPrimitives::FOCUS_MAX_LEN ); if ( $focus_result['overLimit'] ) { $errors[] = DefinitionPrimitives::issue( $path . '.focus', 'too_long', __( 'Focus text is too long.', 'ai-product-tools' ) ); } $detail = $item['detail'] ?? 'balanced'; if ( ! DefinitionPrimitives::inEnum( $detail, array( 'concise', 'balanced', 'detailed' ) ) ) { $errors[] = DefinitionPrimitives::issue( $path . '.detail', 'invalid_enum', __( 'Invalid detail level.', 'ai-product-tools' ) ); $detail = 'balanced'; } $length = DefinitionPrimitives::wordRange( $item['length'] ?? null, $default_row['length'], $path . '.length', $errors ); $items = DefinitionPrimitives::items( $item['items'] ?? null, $default_row['items'], 'data' === $mode ? 'data' : 'ai', $path . '.items', $errors ); $fixed_text_result = DefinitionPrimitives::fixedText( $item['fixedText'] ?? $default_row['fixedText'] ); if ( $fixed_text_result['overLimit'] ) { $errors[] = DefinitionPrimitives::issue( $path . '.fixedText', 'too_long', __( 'Fixed text is too long.', 'ai-product-tools' ) ); } if ( $fixed_text_result['changed'] ) { $notices[] = DefinitionPrimitives::issue( $path . '.fixedText', 'sanitized', __( 'Some formatting was removed from this fixed text because it is not allowed.', 'ai-product-tools' ) ); } $fields = DefinitionPrimitives::fields( $item['fields'] ?? null, $default_row['fields'], $this->fields, $scope, $allow_custom_fields, $path . '.fields', $errors ); DefinitionPrimitives::requireDataFieldsSelected( $mode, $fields, $enabled, $validate_on_save, $path, $errors ); DefinitionPrimitives::requireFixedTextPresent( $mode, $fixed_text_result['value'], $enabled, $validate_on_save, $path, $errors ); $sources = DefinitionPrimitives::sectionSources( $item['sources'] ?? null, $default_row['sources'], $known_source_ids, $path . '.sources', $errors ); $missing = DefinitionPrimitives::missingPolicy( $item['missing'] ?? null, $default_row['missing'], array( 'skip', 'fallback', 'review' ), $path . '.missing', $errors ); $condition = DefinitionPrimitives::condition( $item['condition'] ?? null, $default_row['condition'], $this->fields, $scope, $allow_custom_fields, $path . '.condition', $errors ); $tone = $item['tone'] ?? ''; if ( ! DefinitionPrimitives::inEnum( $tone, array( '', 'more_technical', 'warmer', 'shorter_sentences', 'more_formal' ) ) ) { $errors[] = DefinitionPrimitives::issue( $path . '.tone', 'invalid_enum', __( 'Invalid tone.', 'ai-product-tools' ) ); $tone = ''; } $instruction_result = DefinitionPrimitives::multiLineText( $item['instruction'] ?? '', DefinitionPrimitives::INSTRUCTION_MAX_LEN ); if ( $instruction_result['overLimit'] ) { $errors[] = DefinitionPrimitives::issue( $path . '.instruction', 'too_long', __( 'Instruction is too long.', 'ai-product-tools' ) ); } return array( 'id' => $id, 'type' => $type, 'name' => $name_result['value'], 'enabled' => $enabled, 'mode' => $mode, 'format' => $format, 'heading' => $heading, 'focus' => $focus_result['value'], 'detail' => $detail, 'length' => $length, 'items' => $items, 'fixedText' => $fixed_text_result['value'], 'fields' => $fields, 'sources' => $sources, 'missing' => $missing, 'condition' => $condition, 'tone' => $tone, 'instruction' => $instruction_result['value'], ); } /** * @param array $input Raw voice overrides. * @param array $default Default voice overrides. * @param array &$errors Collected errors. * @return array{expression:int|null,note:string} */ private function normalizeVoice( array $input, array $default, array &$errors ): array { $expression = array_key_exists( 'expression', $input ) ? $input['expression'] : $default['expression']; if ( null !== $expression && ! in_array( $expression, array( 0, 1, 2 ), true ) ) { $errors[] = DefinitionPrimitives::issue( 'voice.expression', 'invalid_enum', __( 'Invalid expression override.', 'ai-product-tools' ) ); $expression = null; } $note_result = DefinitionPrimitives::multiLineText( $input['note'] ?? $default['note'], DefinitionPrimitives::VOICE_NOTE_MAX_LEN ); if ( $note_result['overLimit'] ) { $errors[] = DefinitionPrimitives::issue( 'voice.note', 'too_long', __( 'Voice note is too long.', 'ai-product-tools' ) ); } return array( 'expression' => $expression, 'note' => $note_result['value'], ); } /** * @param array $input Raw source policy. * @param array $default Default source policy. * @param int[] $known_source_ids Ids valid for 'src:' refs. * @param bool $allow_custom_fields Context flag (see normalize()'s docblock). * @param array &$errors Collected errors. * @return array BlueprintSourcePolicy-shaped array. */ private function normalizeSourcePolicy( array $input, array $default, array $known_source_ids, bool $allow_custom_fields, array &$errors ): array { $raw_fields = is_array( $input['productFields'] ?? null ) ? $input['productFields'] : $default['productFields']; if ( count( $raw_fields ) > DefinitionPrimitives::PRODUCT_FIELDS_MAX ) { $errors[] = DefinitionPrimitives::issue( 'sources.productFields', 'too_many', __( 'Too many fields selected.', 'ai-product-tools' ) ); $raw_fields = array_slice( $raw_fields, 0, DefinitionPrimitives::PRODUCT_FIELDS_MAX ); } $product_fields = array(); foreach ( $raw_fields as $i => $ref ) { if ( is_string( $ref ) && DefinitionPrimitives::validFieldRef( $ref, $this->fields, 'product', $allow_custom_fields ) ) { $product_fields[] = $ref; } else { $errors[] = DefinitionPrimitives::issue( 'sources.productFields[' . $i . ']', 'invalid_field_ref', DefinitionPrimitives::unavailableFieldMessage( $ref ) ); } } $raw_items = is_array( $input['items'] ?? null ) ? $input['items'] : $default['items']; if ( count( $raw_items ) > DefinitionPrimitives::SOURCE_POLICY_ITEMS_MAX ) { $errors[] = DefinitionPrimitives::issue( 'sources.items', 'too_many', __( 'Too many sources.', 'ai-product-tools' ) ); $raw_items = array_slice( $raw_items, 0, DefinitionPrimitives::SOURCE_POLICY_ITEMS_MAX ); } $items = array(); $has_product = false; foreach ( $raw_items as $i => $raw_item ) { $ref = is_array( $raw_item ) ? ( $raw_item['ref'] ?? null ) : null; $enabled = is_array( $raw_item ) ? DefinitionPrimitives::boolOr( $raw_item['enabled'] ?? null, true ) : true; if ( ! DefinitionPrimitives::isValidSourceRef( $ref, $known_source_ids ) ) { $errors[] = DefinitionPrimitives::issue( 'sources.items[' . $i . ']', 'unknown_source_ref', __( 'Unknown source reference.', 'ai-product-tools' ) ); continue; } if ( 'product' === $ref ) { $has_product = true; } $items[] = array( 'ref' => $ref, 'enabled' => $enabled ); } if ( ! $has_product ) { array_unshift( $items, array( 'ref' => 'product', 'enabled' => true ) ); } $conflict_policy = $input['conflictPolicy'] ?? $default['conflictPolicy']; if ( ! DefinitionPrimitives::inEnum( $conflict_policy, array( 'review', 'prefer', 'skip' ) ) ) { $errors[] = DefinitionPrimitives::issue( 'sources.conflictPolicy', 'invalid_enum', __( 'Invalid conflict policy.', 'ai-product-tools' ) ); $conflict_policy = $default['conflictPolicy']; } $raw_domains = is_array( $input['allowedDomains'] ?? null ) ? $input['allowedDomains'] : $default['allowedDomains']; if ( count( $raw_domains ) > DefinitionPrimitives::ALLOWED_DOMAINS_MAX ) { $errors[] = DefinitionPrimitives::issue( 'sources.allowedDomains', 'too_many', __( 'Too many domains.', 'ai-product-tools' ) ); $raw_domains = array_slice( $raw_domains, 0, DefinitionPrimitives::ALLOWED_DOMAINS_MAX ); } $allowed_domains = array(); foreach ( $raw_domains as $i => $domain ) { $domain = is_string( $domain ) ? strtolower( trim( $domain ) ) : ''; if ( '' === $domain || false !== strpos( $domain, '/' ) || false !== strpos( $domain, ' ' ) || mb_strlen( $domain, 'UTF-8' ) > DefinitionPrimitives::ALLOWED_DOMAIN_MAX_LEN ) { $errors[] = DefinitionPrimitives::issue( 'sources.allowedDomains[' . $i . ']', 'invalid_domain', __( 'Invalid domain.', 'ai-product-tools' ) ); continue; } $allowed_domains[] = $domain; } return array( 'productFields' => $product_fields, 'items' => $items, 'conflictPolicy' => $conflict_policy, 'allowedDomains' => $allowed_domains, ); } /** * @param array $input Raw rules. * @param array $default Default rules. * @param array &$errors Collected errors. * @return array BlueprintRules-shaped array. */ private function normalizeRules( array $input, array $default, array &$errors ): array { $language = $input['language'] ?? $default['language']; if ( 'store' !== $language && ! in_array( $language, ContentDefaultsService::SUPPORTED_LANGUAGES, true ) ) { $errors[] = DefinitionPrimitives::issue( 'rules.language', 'invalid_enum', __( 'Invalid language.', 'ai-product-tools' ) ); $language = $default['language']; } $heading_level = $input['headingLevel'] ?? $default['headingLevel']; if ( ! DefinitionPrimitives::inEnum( $heading_level, array( 'h2', 'h3', 'h4' ) ) ) { $errors[] = DefinitionPrimitives::issue( 'rules.headingLevel', 'invalid_enum', __( 'Invalid heading level.', 'ai-product-tools' ) ); $heading_level = $default['headingLevel']; } $raw_banned = is_array( $input['bannedPhrases'] ?? null ) ? $input['bannedPhrases'] : $default['bannedPhrases']; if ( count( $raw_banned ) > DefinitionPrimitives::BANNED_PHRASES_MAX ) { $errors[] = DefinitionPrimitives::issue( 'rules.bannedPhrases', 'too_many', __( 'Too many banned phrases.', 'ai-product-tools' ) ); $raw_banned = array_slice( $raw_banned, 0, DefinitionPrimitives::BANNED_PHRASES_MAX ); } $banned_phrases = array(); foreach ( $raw_banned as $i => $phrase ) { $result = DefinitionPrimitives::singleLineText( $phrase, DefinitionPrimitives::BANNED_PHRASE_MAX_LEN ); if ( $result['overLimit'] ) { $errors[] = DefinitionPrimitives::issue( 'rules.bannedPhrases[' . $i . ']', 'too_long', __( 'Banned phrase is too long.', 'ai-product-tools' ) ); continue; } if ( '' !== $result['value'] ) { $banned_phrases[] = $result['value']; } } $required_failure = $input['requiredFailure'] ?? $default['requiredFailure']; if ( ! DefinitionPrimitives::inEnum( $required_failure, array( 'review', 'partial' ) ) ) { $errors[] = DefinitionPrimitives::issue( 'rules.requiredFailure', 'invalid_enum', __( 'Invalid required-failure policy.', 'ai-product-tools' ) ); $required_failure = $default['requiredFailure']; } $raw_instructions = is_array( $input['instructions'] ?? null ) ? array_values( $input['instructions'] ) : $default['instructions']; if ( count( $raw_instructions ) > DefinitionPrimitives::RULE_INSTRUCTIONS_MAX ) { $errors[] = DefinitionPrimitives::issue( 'rules.instructions', 'too_many', __( 'Too many instructions.', 'ai-product-tools' ) ); $raw_instructions = array_slice( $raw_instructions, 0, DefinitionPrimitives::RULE_INSTRUCTIONS_MAX ); } $seen_ids = array(); $instructions = array(); foreach ( $raw_instructions as $i => $raw_instruction ) { if ( ! is_array( $raw_instruction ) ) { $errors[] = DefinitionPrimitives::issue( 'rules.instructions[' . $i . ']', 'invalid_shape', __( 'Invalid instruction.', 'ai-product-tools' ) ); continue; } $path = 'rules.instructions[' . $i . ']'; $id = DefinitionPrimitives::normalizeId( $raw_instruction['id'] ?? null, $path, $seen_ids, $errors ); $text_result = DefinitionPrimitives::multiLineText( $raw_instruction['text'] ?? '', DefinitionPrimitives::RULE_INSTRUCTION_TEXT_MAX_LEN ); if ( $text_result['overLimit'] ) { $errors[] = DefinitionPrimitives::issue( $path . '.text', 'too_long', __( 'Instruction text is too long.', 'ai-product-tools' ) ); } $origin = $raw_instruction['origin'] ?? 'user'; if ( ! DefinitionPrimitives::inEnum( $origin, array( 'user', 'legacy' ) ) ) { $errors[] = DefinitionPrimitives::issue( $path . '.origin', 'invalid_enum', __( 'Invalid instruction origin.', 'ai-product-tools' ) ); $origin = 'user'; } $instructions[] = array( 'id' => $id, 'text' => $text_result['value'], 'origin' => $origin, 'enabled' => DefinitionPrimitives::boolOr( $raw_instruction['enabled'] ?? null, true ), ); } return array( 'language' => $language, 'headingLevel' => $heading_level, 'bannedPhrases' => $banned_phrases, 'requiredFailure' => $required_failure, 'instructions' => $instructions, ); } }