'GET', 'callback' => array( __CLASS__, 'catalog' ), 'permission_callback' => array( __CLASS__, 'check_permissions_read' ), ), ) ); register_rest_route( 'aipt/v1', '/content-structure/templates', array( array( 'methods' => 'GET', 'callback' => array( __CLASS__, 'templates' ), 'permission_callback' => array( __CLASS__, 'check_permissions_read' ), 'args' => array( 'generator' => array( 'sanitize_callback' => 'sanitize_key' ), ), ), ) ); register_rest_route( 'aipt/v1', '/content-structure/blueprints', array( array( 'methods' => 'GET', 'callback' => array( __CLASS__, 'list_blueprints' ), 'permission_callback' => array( __CLASS__, 'check_permissions_read' ), 'args' => self::listArgs(), ), array( 'methods' => 'POST', 'callback' => array( __CLASS__, 'create_blueprint' ), 'permission_callback' => array( __CLASS__, 'check_permissions_read' ), ), ) ); register_rest_route( 'aipt/v1', '/content-structure/blueprints/(?P\d+)', array( array( 'methods' => 'GET', 'callback' => array( __CLASS__, 'get_blueprint' ), 'permission_callback' => array( __CLASS__, 'check_permissions_read' ), 'args' => self::idArgs(), ), array( 'methods' => 'PUT', 'callback' => array( __CLASS__, 'update_blueprint' ), 'permission_callback' => array( __CLASS__, 'check_permissions_read' ), 'args' => self::idArgs(), ), array( 'methods' => 'DELETE', 'callback' => array( __CLASS__, 'delete_blueprint' ), 'permission_callback' => array( __CLASS__, 'check_permissions_read' ), 'args' => self::idArgs(), ), ) ); register_rest_route( 'aipt/v1', '/content-structure/blueprints/(?P\d+)/duplicate', array( array( 'methods' => 'POST', 'callback' => array( __CLASS__, 'duplicate_blueprint' ), 'permission_callback' => array( __CLASS__, 'check_permissions_read' ), 'args' => self::idArgs(), ), ) ); register_rest_route( 'aipt/v1', '/content-structure/blueprints/(?P\d+)/impact', array( array( 'methods' => 'GET', 'callback' => array( __CLASS__, 'get_impact' ), 'permission_callback' => array( __CLASS__, 'check_permissions_read' ), 'args' => self::idArgs(), ), ) ); register_rest_route( 'aipt/v1', '/content-structure/blueprints/(?P\d+)/scope', array( array( 'methods' => 'GET', 'callback' => array( __CLASS__, 'get_scope' ), 'permission_callback' => array( __CLASS__, 'check_permissions_read' ), 'args' => self::idArgs(), ), ) ); register_rest_route( 'aipt/v1', '/content-structure/blueprints/usage-counts', array( array( 'methods' => 'GET', 'callback' => array( __CLASS__, 'get_usage_counts' ), 'permission_callback' => array( __CLASS__, 'check_permissions_read' ), 'args' => array( 'ids' => array( 'required' => true, 'type' => 'array', 'items' => array( 'type' => 'integer' ) ), ), ), ) ); register_rest_route( 'aipt/v1', '/content-structure/blueprints/example-structure', array( array( 'methods' => 'POST', 'callback' => array( __CLASS__, 'detect_example_structure' ), 'permission_callback' => array( __CLASS__, 'check_permissions_read' ), ), ) ); register_rest_route( 'aipt/v1', '/content-structure/field-values', array( array( 'methods' => 'GET', 'callback' => array( __CLASS__, 'get_field_values' ), 'permission_callback' => array( __CLASS__, 'check_permissions_read' ), 'args' => array( 'subjectType' => array( 'required' => true, 'sanitize_callback' => 'sanitize_key' ), 'subjectId' => array( 'required' => true, 'sanitize_callback' => 'absint' ), 'refs' => array( 'required' => true, 'type' => 'array', 'items' => array( 'type' => 'string' ) ), ), ), ) ); } /** * GET /content-structure/catalog * * @return WP_REST_Response */ public static function catalog(): WP_REST_Response { return self::success( CatalogBuilder::build( static::fieldCatalog(), current_user_can( RestConstants::CAP_USE ), current_user_can( RestConstants::CAP_MANAGE ) ) ); } /** * GET /content-structure/templates?generator= * * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public static function templates( WP_REST_Request $request ) { $generator = (string) $request->get_param( 'generator' ); if ( ! Generators::isValid( $generator ) ) { return self::invalidGeneratorError(); } return self::success( TemplateCatalog::templatesFor( $generator ) ); } /** * GET /content-structure/blueprints * * @param WP_REST_Request $request Request object. * @return WP_REST_Response */ public static function list_blueprints( WP_REST_Request $request ): WP_REST_Response { $filters = array(); $generator = (string) $request->get_param( 'generator' ); if ( '' !== $generator ) { $filters['generator'] = sanitize_key( $generator ); } $status = (string) $request->get_param( 'status' ); if ( '' !== $status ) { $filters['status'] = sanitize_key( $status ); } $search = $request->get_param( 'search' ); if ( is_string( $search ) && '' !== trim( $search ) ) { $filters['search'] = sanitize_text_field( wp_unslash( $search ) ); } $result = static::blueprintStore()->list( $filters, self::parseCursor( $request ), self::parseLimit( $request ) ); $brand_profiles = static::brandProfileStore(); $assignments = static::assignmentStore(); $profile_cache = array(); $items = array_map( function ( array $row ) use ( $brand_profiles, $assignments, &$profile_cache ): array { return BlueprintShapes::summaryShape( $row, $brand_profiles, $assignments, $profile_cache ); }, $result['items'] ); return self::success( array( 'items' => $items, 'total' => $result['total'], 'hasMore' => $result['hasMore'], 'nextCursor' => $result['nextCursor'], ) ); } /** * POST /content-structure/blueprints * * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public static function create_blueprint( WP_REST_Request $request ) { $body = (array) $request->get_json_params(); $generator = isset( $body['generator'] ) ? sanitize_key( (string) $body['generator'] ) : ''; if ( ! Generators::isValid( $generator ) ) { return self::invalidGeneratorError(); } $name = isset( $body['name'] ) ? sanitize_text_field( (string) $body['name'] ) : ''; if ( '' === trim( $name ) ) { return self::invalidDefinitionError( array( DefinitionPrimitives::issue( 'name', 'required', __( 'A template name is required.', 'ai-product-tools' ) ) ), array() ); } if ( mb_strlen( $name ) > self::NAME_MAX_LENGTH ) { return self::nameTooLongError(); } $origin = isset( $body['origin'] ) ? mb_substr( sanitize_text_field( (string) $body['origin'] ), 0, self::ORIGIN_MAX_LENGTH ) : ''; $definition_input = is_array( $body['definition'] ?? null ) ? $body['definition'] : array(); $normalized = ( new DefinitionNormalizer( static::fieldCatalog() ) )->normalize( $generator, $definition_input, self::normalizerContext( $definition_input ) ); $errors = $normalized['errors']; $brand_profile_id = self::validatedBrandProfileId( $body['brandProfileId'] ?? 0, $errors ); if ( ! empty( $errors ) ) { return self::invalidDefinitionError( $errors, $normalized['notices'] ); } $normalized['definition'] = self::enforceAllowedDomains( $normalized['definition'], null ); $id = static::blueprintStore()->create( array( 'name' => $name, 'generator' => $generator, 'status' => 'active', 'schemaVersion' => (int) $normalized['definition']['schemaVersion'], 'definition' => $normalized['definition'], 'definitionHash' => DefinitionHasher::hash( $normalized['definition'] ), 'brandProfileId' => $brand_profile_id, 'origin' => $origin, 'createdBy' => get_current_user_id(), ) ); if ( $id <= 0 ) { return self::error( 'aipt_blueprint_create_failed', __( 'The template could not be created.', 'ai-product-tools' ), 500 ); } $row = static::blueprintStore()->get( $id ); return self::success( self::blueprintShape( $row ) + array( 'notices' => $normalized['notices'] ) ); } /** * GET /content-structure/blueprints/{id} * * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public static function get_blueprint( WP_REST_Request $request ) { $row = static::blueprintStore()->get( (int) $request->get_param( 'id' ) ); if ( null === $row ) { return self::notFoundError(); } return self::success( self::blueprintShape( $row ) ); } /** * PUT /content-structure/blueprints/{id} * * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public static function update_blueprint( WP_REST_Request $request ) { $id = (int) $request->get_param( 'id' ); $current = static::blueprintStore()->get( $id ); if ( null === $current ) { return self::notFoundError(); } $body = (array) $request->get_json_params(); $expected_revision = isset( $body['expectedRevision'] ) ? (int) $body['expectedRevision'] : -1; $name = isset( $body['name'] ) ? sanitize_text_field( (string) $body['name'] ) : (string) $current['name']; if ( '' === trim( $name ) ) { return self::invalidDefinitionError( array( DefinitionPrimitives::issue( 'name', 'required', __( 'A template name is required.', 'ai-product-tools' ) ) ), array() ); } if ( mb_strlen( $name ) > self::NAME_MAX_LENGTH ) { return self::nameTooLongError(); } $generator = (string) $current['generator']; $definition_input = is_array( $body['definition'] ?? null ) ? $body['definition'] : $current['definition']; $normalized = ( new DefinitionNormalizer( static::fieldCatalog()->withStoredRefsOf( (array) $current['definition'] ) ) )->normalize( $generator, $definition_input, self::normalizerContext( $definition_input ) ); $errors = $normalized['errors']; $brand_profile_id = array_key_exists( 'brandProfileId', $body ) ? self::validatedBrandProfileId( $body['brandProfileId'], $errors ) : (int) $current['brandProfileId']; if ( ! empty( $errors ) ) { return self::invalidDefinitionError( $errors, $normalized['notices'] ); } $normalized['definition'] = self::enforceAllowedDomains( $normalized['definition'], $current['definition'] ); $result = static::blueprintStore()->update( $id, array( 'name' => $name, 'definition' => $normalized['definition'], 'definitionHash' => DefinitionHasher::hash( $normalized['definition'] ), 'brandProfileId' => $brand_profile_id, 'updatedBy' => get_current_user_id(), ), $expected_revision ); if ( ! $result['ok'] ) { return self::revisionConflictError( $result['current'] ); } return self::success( self::blueprintShape( $result['current'] ) + array( 'notices' => $normalized['notices'] ) ); } /** * POST /content-structure/blueprints/{id}/duplicate * * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public static function duplicate_blueprint( WP_REST_Request $request ) { $id = (int) $request->get_param( 'id' ); $source = static::blueprintStore()->get( $id ); if ( null === $source ) { return self::notFoundError(); } $body = (array) $request->get_json_params(); $given_name = isset( $body['name'] ) && '' !== trim( (string) $body['name'] ); $name = $given_name ? sanitize_text_field( (string) $body['name'] ) : sprintf( /* translators: %s: source template name. */ __( 'Copy of %s', 'ai-product-tools' ), $source['name'] ); if ( mb_strlen( $name ) > self::NAME_MAX_LENGTH ) { if ( $given_name ) { return self::nameTooLongError(); } $name = mb_substr( $name, 0, self::NAME_MAX_LENGTH ); } $definition = BlueprintShapes::regenerateStructureIds( (string) $source['generator'], $source['definition'] ); $new_id = static::blueprintStore()->create( array( 'name' => $name, 'generator' => $source['generator'], 'status' => 'active', 'schemaVersion' => (int) $source['schemaVersion'], 'definition' => $definition, 'definitionHash' => DefinitionHasher::hash( $definition ), 'brandProfileId' => (int) $source['brandProfileId'], 'origin' => 'duplicate:' . $id, 'createdBy' => get_current_user_id(), ) ); if ( $new_id <= 0 ) { return self::error( 'aipt_blueprint_create_failed', __( 'The template could not be duplicated.', 'ai-product-tools' ), 500 ); } $copied = self::copyBlueprintScopedSources( $id, $new_id, $definition ); if ( null === $copied ) { static::blueprintStore()->delete( $new_id ); return self::error( 'aipt_blueprint_create_failed', __( 'The template could not be duplicated.', 'ai-product-tools' ), 500 ); } if ( $copied !== $definition ) { $rewritten = static::blueprintStore()->update( $new_id, array( 'definition' => $copied, 'definitionHash' => DefinitionHasher::hash( $copied ), ), 1 ); if ( empty( $rewritten['ok'] ) ) { foreach ( static::sourceStore()->listByScope( 'blueprint', $new_id ) as $copied_source ) { static::sourceStore()->delete( (int) $copied_source['id'] ); } static::blueprintStore()->delete( $new_id ); return self::error( 'aipt_blueprint_create_failed', __( 'The template could not be duplicated.', 'ai-product-tools' ), 500 ); } } return self::success( self::blueprintShape( static::blueprintStore()->get( $new_id ) ) ); } /** * GET /content-structure/blueprints/{id}/impact * * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public static function get_impact( WP_REST_Request $request ) { $id = (int) $request->get_param( 'id' ); $blueprint = static::blueprintStore()->get( $id ); if ( null === $blueprint ) { return self::notFoundError(); } return self::success( self::impactShape( $blueprint ) ); } /** * DELETE /content-structure/blueprints/{id}?impactHash= * * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public static function delete_blueprint( WP_REST_Request $request ) { $id = (int) $request->get_param( 'id' ); $blueprint = static::blueprintStore()->get( $id ); if ( null === $blueprint ) { return self::notFoundError(); } if ( ! empty( static::assignmentStore()->listByBlueprint( $id ) ) && ! current_user_can( RestConstants::CAP_MANAGE ) ) { return self::forbiddenError(); } $impact = self::impactShape( $blueprint ); $given_hash = (string) $request->get_param( 'impactHash' ); if ( '' === $given_hash || ! hash_equals( $impact['impactHash'], $given_hash ) ) { return self::error( 'aipt_blueprint_impact_changed', __( 'What this delete affects has changed since you last checked. Review the refreshed impact and try again.', 'ai-product-tools' ), 409, array( 'impact' => $impact ) ); } $removed = OrphanCleaner::on_blueprint_deleted( $id ); static::blueprintStore()->delete( $id ); return self::success( array( 'deleted' => true, 'removed' => array( 'assignments' => (int) ( $removed['assignments'] ?? 0 ), 'sources' => (int) ( $removed['sources'] ?? 0 ), 'results' => (int) ( $removed['results'] ?? 0 ), ), ) ); } /** * GET /content-structure/blueprints/{id}/scope * * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public static function get_scope( WP_REST_Request $request ) { $id = (int) $request->get_param( 'id' ); $blueprint = static::blueprintStore()->get( $id ); if ( null === $blueprint ) { return self::notFoundError(); } $scope = static::assignmentScope()->productsForBlueprint( (string) $blueprint['generator'], $id ); return self::success( array( 'total' => $scope['total'], 'sample' => $scope['sample'], 'approximate' => $scope['approximate'], ) ); } /** * GET /content-structure/blueprints/usage-counts?ids[]=1&ids[]=2 * * The Library list's "used by about N products" line for a whole page of * rows: resolves the same winner count get_scope() does, once per * requested id, so a row's number always matches what opening that * Blueprint's own scope view would show. An id that is not a real * Blueprint is silently skipped (a row with nothing to show), not an * error, since a row can only ask about ids it already has. * * Several rows often share one generator (e.g. a store default plus a few * category-specific Blueprints), and resolving a row's winner count walks * that generator's whole candidate pool — up to the full catalog for a * store default. So this fetches each distinct generator's assignment * rows once up front and hands them to every row that needs them, the * same way a bulk product-selection resolve already shares one fetch * across many products, instead of letting each row's own resolution * re-query them from scratch. * * The counts pass through the `aipt_content_structure_usage_counts` * filter, so an extension can add its own per-row data. * * @param WP_REST_Request $request Request object. * @return WP_REST_Response */ public static function get_usage_counts( WP_REST_Request $request ) { $raw_ids = (array) $request->get_param( 'ids' ); $ids = array_slice( array_values( array_unique( array_filter( array_map( 'absint', $raw_ids ) ) ) ), 0, self::USAGE_COUNTS_IDS_MAX ); $blueprints_by_id = array(); foreach ( $ids as $id ) { $blueprint = static::blueprintStore()->get( $id ); if ( null !== $blueprint ) { $blueprints_by_id[ $id ] = $blueprint; } } $rows_by_generator = array(); foreach ( $blueprints_by_id as $blueprint ) { $generator = (string) $blueprint['generator']; if ( ! isset( $rows_by_generator[ $generator ] ) ) { $rows_by_generator[ $generator ] = static::assignmentStore()->listForGenerator( $generator ); } } $counts = array(); foreach ( $blueprints_by_id as $id => $blueprint ) { $generator = (string) $blueprint['generator']; $scope = static::assignmentScope()->productsForBlueprint( $generator, $id, self::USAGE_COUNTS_SCOPE_LIMIT, $rows_by_generator[ $generator ] ); $counts[ $id ] = array( 'total' => $scope['total'], 'approximate' => $scope['approximate'], ); } /** * Filters the Library rows' usage counts before they are returned. * * @param array> $counts Usage counts by structure id. * @param array> $blueprints_by_id Those structures by id. */ $counts = apply_filters( 'aipt_content_structure_usage_counts', $counts, $blueprints_by_id ); return self::success( array( 'counts' => is_array( $counts ) ? $counts : array() ) ); } /** * GET /content-structure/field-values * * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public static function get_field_values( WP_REST_Request $request ) { $subject_type = (string) $request->get_param( 'subjectType' ); $subject_id = (int) $request->get_param( 'subjectId' ); $refs = (array) $request->get_param( 'refs' ); $refs = array_slice( array_values( array_map( 'strval', $refs ) ), 0, self::FIELD_VALUES_REFS_MAX ); if ( ! in_array( $subject_type, array( 'product', 'term', 'attachment' ), true ) || $subject_id <= 0 ) { return self::error( 'aipt_blueprint_invalid_subject', __( 'Unknown or missing subject.', 'ai-product-tools' ), 400 ); } $fields = static::fieldCatalog(); $values = array(); if ( 'product' === $subject_type ) { if ( ! current_user_can( 'edit_post', $subject_id ) ) { return self::forbiddenError(); } $product = function_exists( 'wc_get_product' ) ? wc_get_product( $subject_id ) : null; if ( ! $product instanceof \WC_Product ) { return self::notFoundError(); } foreach ( $refs as $ref ) { $values[ $ref ] = $fields->productValue( $product, $ref ); } } elseif ( 'term' === $subject_type ) { $term = function_exists( 'get_term' ) ? get_term( $subject_id ) : null; if ( ! $term instanceof \WP_Term ) { return self::notFoundError(); } if ( ! current_user_can( 'edit_term', $subject_id ) ) { return self::forbiddenError(); } foreach ( $refs as $ref ) { $values[ $ref ] = $fields->termValue( $term, $ref ); } } else { $post = function_exists( 'get_post' ) ? get_post( $subject_id ) : null; if ( null === $post ) { return self::notFoundError(); } $product_id = (int) $post->post_parent; if ( ! current_user_can( 'edit_post', $product_id ) ) { return self::forbiddenError(); } $position = BlueprintShapes::attachmentPosition( $product_id, $subject_id ); foreach ( $refs as $ref ) { $values[ $ref ] = $fields->imageValue( $subject_id, $product_id, $position, $ref ); } } return self::success( array( 'values' => $values ) ); } /** * POST /content-structure/blueprints/example-structure * * Takes one example Description (a product's own long description, or * pasted text) and returns a draft BlueprintDefinition built purely from * parsing — no AI call, nothing stored. Description-only: the detector's * heading-keyword vocabulary (features/benefits/specifications/ * warranty/…) names Description section types; Taxonomy's four section * types describe a CATEGORY page, which a product description's * structure does not meaningfully map onto. * * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public static function detect_example_structure( WP_REST_Request $request ) { $body = (array) $request->get_json_params(); $generator = isset( $body['generator'] ) ? sanitize_key( (string) $body['generator'] ) : ''; if ( ! Generators::isValid( $generator ) ) { return self::invalidGeneratorError(); } if ( Generators::DESCRIPTION !== $generator ) { return self::error( 'aipt_blueprint_invalid_generator', __( 'Building from an example is only available for the Long description generator.', 'ai-product-tools' ), 400 ); } $product_id = isset( $body['productId'] ) ? absint( $body['productId'] ) : 0; $pasted = isset( $body['text'] ) && is_string( $body['text'] ) ? wp_unslash( $body['text'] ) : ''; if ( $product_id <= 0 && '' === trim( $pasted ) ) { return self::error( 'aipt_blueprint_invalid_request', __( 'Pick a product or paste a description first.', 'ai-product-tools' ), 400 ); } $product_name = ''; $example_text = $pasted; if ( $product_id > 0 ) { if ( ! current_user_can( 'edit_post', $product_id ) ) { return self::forbiddenError(); } $product = function_exists( 'wc_get_product' ) ? wc_get_product( $product_id ) : null; if ( ! $product instanceof \WC_Product ) { return self::notFoundError(); } $example_text = (string) $product->get_description(); $product_name = (string) $product->get_name(); } $detected = ( new ExampleStructureDetector() )->detect( $example_text, $product_name ); $normalized = ( new DefinitionNormalizer( static::fieldCatalog() ) )->normalize( $generator, array( 'structure' => array( 'sections' => $detected['sections'] ) ), array( 'validateOnSave' => true ) ); return self::success( array( 'definition' => $normalized['definition'], 'errors' => $normalized['errors'], 'notices' => array_merge( $detected['notices'], $normalized['notices'] ), ) ); } /** * @param array $row Raw BlueprintStore row. * @return array Blueprint (extends BlueprintSummary). */ private static function blueprintShape( array $row ): array { return BlueprintShapes::fullShape( $row, static::brandProfileStore(), static::assignmentStore() ); } /** * @param array $blueprint Raw BlueprintStore row. * @return array DeleteImpact. */ private static function impactShape( array $blueprint ): array { return BlueprintShapes::computeImpact( $blueprint, static::assignmentStore(), static::sourceStore(), static::blueprintStore() ); } /** * Normalizer context for the save paths (create and update), which also * run the save-only semantic checks. Duplicate copies an already-stored * definition as-is, so a blueprint saved before those checks existed can * still be copied; the copy is checked on its own first save. * * @param array $definition Raw submitted BlueprintDefinition, used to find every 'src:' it references. * @return array */ private static function normalizerContext( array $definition = array() ): array { return array( 'knownSourceIds' => static::knownSourceIds( $definition ), 'allowCustomFields' => static::fieldCatalog()->customFieldsAllowed(), 'validateOnSave' => true, ); } /** * Ids valid for a 'src:' reference: SourceStore::list()'s first 500 * rows sorted by name (an existing, bounded "known sources" baseline) * plus every id the submitted definition itself references, checked * directly against the store — so a structure referencing a source * outside that first page is still recognized as known instead of * rejected as "Unknown source reference". * * @param array $definition Raw submitted BlueprintDefinition. * @return int[] */ private static function knownSourceIds( array $definition ): array { $first_page = array_map( static function ( array $source ): int { return (int) $source['id']; }, static::sourceStore()->list( array(), 500 ) ); $referenced = static::sourceStore()->existingIds( self::referencedSourceIds( $definition ) ); return array_values( array_unique( array_merge( $first_page, $referenced ) ) ); } /** * Copy the sources scoped to one template onto its duplicate and point * the duplicate's 'src:' references at the copies. A template-scoped * source only applies to the template it is scoped to and is deleted with * it, so references left on the original's rows would be skipped at run * time and dangle after the original is deleted. Sources of any other * scope stay shared and keep their references. * * @param int $from_id Original template id. * @param int $to_id Duplicate template id. * @param array $definition Duplicate definition holding the original's references. * @return array|null The definition with remapped references, or null when a copy failed (copies already made are removed). */ private static function copyBlueprintScopedSources( int $from_id, int $to_id, array $definition ): ?array { $store = static::sourceStore(); $map = array(); $created = array(); foreach ( $store->listByScope( 'blueprint', $from_id ) as $row ) { $new_source_id = $store->create( array( 'name' => $row['name'], 'kind' => $row['kind'], 'url' => $row['url'], 'urlField' => $row['urlField'], 'scopeType' => 'blueprint', 'scopeId' => $to_id, 'staleAfterDays' => $row['staleAfterDays'], ) ); $disabled_failed = false; if ( $new_source_id > 0 && ! $row['enabled'] ) { $created_row = $store->get( $new_source_id ); $disabled = null !== $created_row && $store->update( $new_source_id, array( 'enabled' => false ), (int) $created_row['version'] )['ok']; $disabled_failed = ! $disabled; } if ( $new_source_id <= 0 || $disabled_failed ) { if ( $new_source_id > 0 ) { $created[] = $new_source_id; } foreach ( $created as $created_id ) { $store->delete( $created_id ); } return null; } $created[] = $new_source_id; $map[ 'src:' . (int) $row['id'] ] = 'src:' . $new_source_id; } if ( empty( $map ) ) { return $definition; } array_walk_recursive( $definition, static function ( &$value ) use ( $map ): void { if ( is_string( $value ) && isset( $map[ $value ] ) ) { $value = $map[ $value ]; } } ); return $definition; } /** * Every id referenced as 'src:' anywhere in a raw (not yet * validated) BlueprintDefinition — the structure's per-section source * selections and the top-level source policy alike — without * depending on DefinitionNormalizer's own traversal of that shape. * * @param array $definition Raw submitted BlueprintDefinition. * @return int[] */ private static function referencedSourceIds( array $definition ): array { $ids = array(); array_walk_recursive( $definition, static function ( $value ) use ( &$ids ): void { if ( is_string( $value ) && 1 === preg_match( '/^src:(\d+)$/', $value, $match ) ) { $ids[] = (int) $match[1]; } } ); return array_values( array_unique( $ids ) ); } /** * @param mixed $raw Raw brandProfileId input. * @param array &$errors Collected errors (appended to on an unknown id). * @return int */ private static function validatedBrandProfileId( $raw, array &$errors ): int { $id = is_numeric( $raw ) ? (int) $raw : 0; if ( $id <= 0 ) { return 0; } if ( null === static::brandProfileStore()->get( $id ) ) { $errors[] = DefinitionPrimitives::issue( 'brandProfileId', 'not_found', __( 'The selected voice does not exist.', 'ai-product-tools' ) ); return 0; } return $id; } /** * @return WP_Error */ private static function invalidGeneratorError(): WP_Error { return self::error( 'aipt_blueprint_invalid_generator', __( 'Unknown content type.', 'ai-product-tools' ), 400 ); } /** * @return WP_Error */ private static function notFoundError(): WP_Error { return self::error( 'aipt_blueprint_not_found', __( 'This template no longer exists.', 'ai-product-tools' ), 404 ); } /** * @return WP_Error */ private static function forbiddenError(): WP_Error { return self::error( 'rest_forbidden', __( 'You do not have permission to view this subject.', 'ai-product-tools' ), 403 ); } /** * @param array $errors Validation errors. * @param array $notices Validation notices. * @return WP_Error */ private static function invalidDefinitionError( array $errors, array $notices ): WP_Error { return self::error( 'aipt_blueprint_invalid_definition', __( 'This template is not valid.', 'ai-product-tools' ), 400, array( 'errors' => $errors, 'notices' => $notices ) ); } /** * A name past {@see NAME_MAX_LENGTH} (the `aipt_blueprints.name` * varchar(190) column width), shaped like {@see invalidDefinitionError()} * so the client's existing field-error handling covers it with no new * response shape to learn. * * @since 2.8.0 * @return WP_Error */ private static function nameTooLongError(): WP_Error { return self::invalidDefinitionError( array( DefinitionPrimitives::issue( 'name', 'too_long', __( 'Use a name of 190 characters or fewer.', 'ai-product-tools' ) ) ), array() ); } /** * @param array|null $current Current row after a failed conditional update. * @return WP_Error */ private static function revisionConflictError( ?array $current ): WP_Error { return self::error( 'aipt_blueprint_revision_conflict', __( 'This template changed since you loaded it. Reload and try again.', 'ai-product-tools' ), 409, array( 'currentRevision' => null !== $current ? (int) $current['revision'] : null, 'updatedBy' => null !== $current ? self::userSummary( (int) $current['updatedBy'] ) : null, 'updatedAt' => null !== $current ? self::isoDate( (string) $current['updatedAt'] ) : null, ) ); } /** * @return array */ private static function listArgs(): array { return array( 'generator' => array( 'sanitize_callback' => 'sanitize_key' ), 'search' => array( 'sanitize_callback' => 'sanitize_text_field' ), 'status' => array( 'sanitize_callback' => 'sanitize_key' ), 'cursor' => array( 'sanitize_callback' => 'sanitize_text_field' ), 'limit' => array( 'sanitize_callback' => 'absint' ), ); } /** * @return array */ private static function idArgs(): array { return array( 'id' => array( 'required' => true, 'sanitize_callback' => 'absint' ), ); } /** * @return BlueprintStore */ protected static function blueprintStore(): BlueprintStore { return new BlueprintStore(); } /** * @return BrandProfileStore */ protected static function brandProfileStore(): BrandProfileStore { return new BrandProfileStore(); } /** * @return SourceStore */ protected static function sourceStore(): SourceStore { return new SourceStore(); } /** * @return AssignmentStore */ protected static function assignmentStore(): AssignmentStore { return new AssignmentStore(); } /** * @return AssignmentScope */ protected static function assignmentScope(): AssignmentScope { return new AssignmentScope(); } /** * @return FieldCatalog */ protected static function fieldCatalog(): FieldCatalog { return new FieldCatalog(); } }