adapters = ! empty( $adapters ) ? $adapters : array( new CoreFieldAdapter(), new SeoFieldAdapter(), new FaqFieldAdapter(), new AltTextFieldAdapter(), ); } public function adapter_for( string $field_id ): ?FieldAdapterInterface { foreach ( $this->adapters as $adapter ) { if ( in_array( $field_id, $adapter->reads(), true ) ) { return $adapter; } } return null; } public function read_fields( \WC_Product $product, array $field_ids ): array { $values = array(); foreach ( $field_ids as $field_id ) { if ( ! is_string( $field_id ) ) { continue; } $adapter = $this->adapter_for( $field_id ); if ( null === $adapter ) { $values[ $field_id ] = null; continue; } $values[ $field_id ] = $adapter->read( $product, $field_id ); } return $values; } public function write_fields( \WC_Product $product, array $field_map ): array { $results = array(); $needs_product_save = false; $core_field_ids = array(); $any_changed = false; foreach ( $field_map as $field_id => $value ) { if ( ! is_string( $field_id ) ) { continue; } $adapter = $this->adapter_for( $field_id ); if ( null === $adapter ) { $results[ $field_id ] = array( 'saved' => false, 'message' => 'Unsupported field.' ); continue; } $result = $adapter->write( $product, $field_id, $value ); $results[ $field_id ] = $result; $persisted = ! empty( $result['saved'] ) || ! empty( $result['persisted'] ); $changed = $persisted && ( ! array_key_exists( 'changed', $result ) || ! empty( $result['changed'] ) ); if ( $changed ) { $any_changed = true; } if ( $adapter instanceof CoreFieldAdapter && $changed && $adapter->requires_product_save( $field_id ) ) { $needs_product_save = true; $core_field_ids[] = $field_id; } } if ( $any_changed ) { $product->set_date_modified( time() ); $needs_product_save = true; } if ( $needs_product_save && ! $this->persist_product( $product ) ) { foreach ( $core_field_ids as $field_id ) { $results[ $field_id ] = array( 'saved' => false, 'message' => 'Failed to persist product changes.', ); } } return $results; } private function persist_product( \WC_Product $product ): bool { try { $outcome = \AIPT\Api\Helpers\ProductSaveVerifier::save( $product ); return $outcome['landed']; } catch ( \Throwable $throwable ) { error_log( sprintf( '[AIPT ProductEditor] product save failed for #%d: %s', (int) $product->get_id(), $throwable->getMessage() ) ); return false; } } public function editable_field_ids(): array { $editable = array(); foreach ( $this->adapters as $adapter ) { if ( $adapter instanceof CoreFieldAdapter ) { $editable = array_merge( $editable, $adapter->editable_field_ids() ); continue; } $editable = array_merge( $editable, $adapter->reads() ); } return array_values( array_unique( $editable ) ); } }