Commit 14d8808aeca for woocommerce
commit 14d8808aeca49603cc624c7ffd993d201109ab76
Author: Chris Lilitsas <1105590+xristos3490@users.noreply.github.com>
Date: Wed Nov 18 17:14:21 2026 +0200
Move product import placeholder cleanup into its own class (#70689)
* refactor: move product import placeholder cleanup into its own class
* refactor: rename placeholder cleanup class to ImportPlaceholders
* refactor: share the import marker delete and test the cleanup request
diff --git a/plugins/woocommerce/changelog/update-product-import-placeholder-cleanup b/plugins/woocommerce/changelog/update-product-import-placeholder-cleanup
new file mode 100644
index 00000000000..548f04ecc3a
--- /dev/null
+++ b/plugins/woocommerce/changelog/update-product-import-placeholder-cleanup
@@ -0,0 +1,3 @@
+Significance: patch
+Type: dev
+Comment: Move product import placeholder cleanup into its own class; no behaviour change.
diff --git a/plugins/woocommerce/includes/admin/importers/class-wc-product-csv-importer-controller.php b/plugins/woocommerce/includes/admin/importers/class-wc-product-csv-importer-controller.php
index da0b0170a88..6c3b687295f 100644
--- a/plugins/woocommerce/includes/admin/importers/class-wc-product-csv-importer-controller.php
+++ b/plugins/woocommerce/includes/admin/importers/class-wc-product-csv-importer-controller.php
@@ -5,6 +5,7 @@
* @package WooCommerce\Admin\Importers
*/
+use Automattic\WooCommerce\Internal\Admin\ImportExport\Product\ImportPlaceholders;
use Automattic\WooCommerce\Internal\CostOfGoodsSold\CostOfGoodsSoldController;
use Automattic\WooCommerce\Internal\Utilities\FilesystemUtil;
use Automattic\WooCommerce\Internal\Utilities\URL;
@@ -26,21 +27,6 @@ if ( ! class_exists( 'WP_Importer' ) ) {
*/
class WC_Product_CSV_Importer_Controller {
- /**
- * Number of temporary products deleted per query when cleaning up after an import.
- */
- private const CLEANUP_BATCH_SIZE = 100;
-
- /**
- * Status the importer gives the temporary products it creates for unresolved references.
- */
- private const CLEANUP_PLACEHOLDER_STATUS = 'importing';
-
- /**
- * Status a temporary product is moved to once cleanup has claimed it for deletion.
- */
- private const CLEANUP_CLAIMED_STATUS = 'importing-cleanup';
-
/**
* Prefix of the AJAX position that runs, and resumes, the cleanup phase.
*/
@@ -336,56 +322,6 @@ class WC_Product_CSV_Importer_Controller {
$this->output_footer();
}
- /**
- * Remove temporary products and mapping data left by the importer.
- *
- * @param int $cursor Highest placeholder ID earlier cleanup requests have examined.
- * @return int|null ID to resume from, or null once no placeholders are left.
- */
- private static function cleanup_after_import( int $cursor = 0 ): ?int {
- global $wpdb;
-
- if ( 0 === $cursor ) {
- self::delete_original_id_markers();
- }
-
- /** This filter is documented in includes/import/abstract-wc-product-importer.php */
- $time_limit = (int) apply_filters( 'woocommerce_product_importer_default_time_limit', 20 ); // phpcs:ignore WooCommerce.Commenting.CommentHooks.MissingSinceComment
- $deadline = time() + $time_limit;
-
- // Page by ID so a placeholder that cannot be deleted is passed over instead of being read again.
- while ( true ) {
- // The claimed status is also selected so a request that died mid-batch does not strand its placeholders.
- // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
- $post_ids = $wpdb->get_col(
- $wpdb->prepare(
- "SELECT ID FROM {$wpdb->posts} WHERE post_type IN ( 'product', 'product_variation' ) AND post_status IN ( %s, %s ) AND ID > %d ORDER BY ID ASC LIMIT %d",
- self::CLEANUP_PLACEHOLDER_STATUS,
- self::CLEANUP_CLAIMED_STATUS,
- $cursor,
- self::CLEANUP_BATCH_SIZE
- )
- );
-
- if ( ! $post_ids ) {
- return null;
- }
-
- $post_ids = array_map( 'absint', $post_ids );
- $cursor = (int) end( $post_ids );
-
- // Ascending IDs delete a placeholder parent before its variations, so WooCommerce removes them through the normal lifecycle.
- foreach ( $post_ids as $post_id ) {
- self::delete_claimed_placeholder( $post_id );
-
- // One delete lifecycle can take seconds, so check the budget per placeholder rather than per batch.
- if ( time() >= $deadline ) {
- return $post_id;
- }
- }
- }
- }
-
/**
* Run one bounded pass of the post-import cleanup and tell the client where to resume.
*
@@ -395,7 +331,7 @@ class WC_Product_CSV_Importer_Controller {
* @param int $cursor Highest placeholder ID earlier cleanup requests have examined.
*/
private static function dispatch_ajax_cleanup( int $cursor ): void {
- $next_cursor = self::cleanup_after_import( $cursor );
+ $next_cursor = wc_get_container()->get( ImportPlaceholders::class )->cleanup_after_import( $cursor );
$response = array(
'position' => null === $next_cursor ? 'done' : self::CLEANUP_POSITION_PREFIX . $next_cursor,
@@ -414,108 +350,6 @@ class WC_Product_CSV_Importer_Controller {
wp_send_json_success( $response );
}
- /**
- * Release temporary products a cleanup request claimed but did not live to delete.
- *
- * A fatal inside the delete lifecycle leaves the claimed status behind, and the importer only
- * recognises a placeholder by the status it was created with, so the CSV row owning that SKU
- * would be skipped as an existing product. Healing at the start of a run keeps that contained.
- */
- private static function release_stranded_cleanup_claims(): void {
- global $wpdb;
-
- // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
- $post_ids = $wpdb->get_col(
- $wpdb->prepare(
- "SELECT ID FROM {$wpdb->posts} WHERE post_type IN ( 'product', 'product_variation' ) AND post_status = %s",
- self::CLEANUP_CLAIMED_STATUS
- )
- );
-
- if ( ! $post_ids ) {
- return;
- }
-
- // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
- $wpdb->query(
- $wpdb->prepare(
- "UPDATE {$wpdb->posts} SET post_status = %s WHERE post_type IN ( 'product', 'product_variation' ) AND post_status = %s",
- self::CLEANUP_PLACEHOLDER_STATUS,
- self::CLEANUP_CLAIMED_STATUS
- )
- );
-
- wp_cache_delete_multiple( array_map( 'absint', $post_ids ), 'posts' );
- }
-
- /**
- * Remove temporary mappings between CSV IDs and imported products.
- *
- * The last import batch clears them so a run abandoned during cleanup leaves none behind.
- * Markers from a run abandoned earlier are kept so a retry of the same file skips rows already imported.
- * Concurrent imports are unsupported: markers and placeholder cleanup are shared site-wide.
- */
- private static function delete_original_id_markers(): void {
- global $wpdb;
-
- // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.SlowDBQuery.slow_db_query_meta_key -- The importer requires one uncached cleanup of its temporary mapping markers.
- $wpdb->delete( $wpdb->postmeta, array( 'meta_key' => '_original_id' ) );
- }
-
- /**
- * Claim one importer placeholder and delete it only if the claim succeeded.
- *
- * Reading the status from the object cache cannot decide this: a process that completes a
- * placeholder does not invalidate this process's cache, so a published product would still
- * look like a placeholder and be force deleted. The guarded UPDATE makes the status check
- * atomic instead, the way ActionScheduler_DBStore::claim_actions() claims actions, and runs
- * per post so a placeholder completed while the batch is being deleted is still protected.
- *
- * @param int $post_id Candidate post ID.
- */
- private static function delete_claimed_placeholder( int $post_id ): void {
- global $wpdb;
-
- // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
- $wpdb->query(
- $wpdb->prepare(
- "UPDATE {$wpdb->posts} SET post_status = %s WHERE ID = %d AND post_type IN ( 'product', 'product_variation' ) AND post_status IN ( %s, %s )",
- self::CLEANUP_CLAIMED_STATUS,
- $post_id,
- self::CLEANUP_PLACEHOLDER_STATUS,
- self::CLEANUP_CLAIMED_STATUS
- )
- );
-
- // The claim wrote the row behind the object cache's back, so read it back from the database.
- wp_cache_delete( $post_id, 'posts' );
-
- $post = get_post( $post_id );
-
- if ( ! $post || self::CLEANUP_CLAIMED_STATUS !== $post->post_status ) {
- return;
- }
-
- try {
- wp_delete_post( $post_id, true );
- } finally {
- // Release the claim if the post outlived the delete lifecycle, so it stays a placeholder for the next run.
- // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
- $released = $wpdb->query(
- $wpdb->prepare(
- "UPDATE {$wpdb->posts} SET post_status = %s WHERE ID = %d AND post_status = %s",
- self::CLEANUP_PLACEHOLDER_STATUS,
- $post_id,
- self::CLEANUP_CLAIMED_STATUS
- )
- );
-
- if ( $released ) {
- wp_cache_delete( $post_id, 'posts' );
- }
- }
- }
-
/**
* Processes AJAX requests related to a product CSV import.
*
@@ -563,7 +397,7 @@ class WC_Product_CSV_Importer_Controller {
}
if ( 0 === $params['start_pos'] ) {
- self::release_stranded_cleanup_claims();
+ wc_get_container()->get( ImportPlaceholders::class )->release_stranded_cleanup_claims();
}
include_once WC_ABSPATH . 'includes/import/class-wc-product-csv-importer.php';
@@ -574,7 +408,7 @@ class WC_Product_CSV_Importer_Controller {
$error_log = array_merge( $error_log, $results['failed'], $results['skipped'], $results['warnings'] ?? array() );
if ( 100 === $percent_complete ) {
- self::delete_original_id_markers();
+ wc_get_container()->get( ImportPlaceholders::class )->delete_original_id_markers();
}
update_user_option( get_current_user_id(), 'product_import_error_log', $error_log );
diff --git a/plugins/woocommerce/src/Internal/Admin/ImportExport/Product/ImportPlaceholders.php b/plugins/woocommerce/src/Internal/Admin/ImportExport/Product/ImportPlaceholders.php
new file mode 100644
index 00000000000..e6f7f9e51ba
--- /dev/null
+++ b/plugins/woocommerce/src/Internal/Admin/ImportExport/Product/ImportPlaceholders.php
@@ -0,0 +1,184 @@
+<?php
+
+declare( strict_types=1 );
+
+namespace Automattic\WooCommerce\Internal\Admin\ImportExport\Product;
+
+/**
+ * Removes placeholder products the product CSV importer creates for unresolved references
+ * (for example a variation whose parent has not been imported yet) once the import that
+ * created them has finished.
+ *
+ * The cleanup covers every placeholder on the site, not just the ones the current run created.
+ *
+ * @since 11.4.0
+ */
+final class ImportPlaceholders {
+
+ /**
+ * Number of temporary products deleted per query when cleaning up after an import.
+ */
+ private const CLEANUP_BATCH_SIZE = 100;
+
+ /**
+ * Status the importer gives the temporary products it creates for unresolved references.
+ */
+ private const CLEANUP_PLACEHOLDER_STATUS = 'importing';
+
+ /**
+ * Status a temporary product is moved to once cleanup has claimed it for deletion.
+ */
+ private const CLEANUP_CLAIMED_STATUS = 'importing-cleanup';
+
+ /**
+ * Remove temporary products and mapping data left by the importer.
+ *
+ * @param int $cursor Highest placeholder ID earlier cleanup requests have examined.
+ * @return int|null ID to resume from, or null once no placeholders are left.
+ */
+ public function cleanup_after_import( int $cursor = 0 ): ?int {
+ global $wpdb;
+
+ if ( 0 === $cursor ) {
+ $this->delete_original_id_markers();
+ }
+
+ /** This filter is documented in includes/import/abstract-wc-product-importer.php */
+ $time_limit = (int) apply_filters( 'woocommerce_product_importer_default_time_limit', 20 ); // phpcs:ignore WooCommerce.Commenting.CommentHooks.MissingSinceComment
+ $deadline = time() + $time_limit;
+
+ // Page by ID so a placeholder that cannot be deleted is passed over instead of being read again.
+ while ( true ) {
+ // The claimed status is also selected so a request that died mid-batch does not strand its placeholders.
+ // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
+ $post_ids = $wpdb->get_col(
+ $wpdb->prepare(
+ "SELECT ID FROM {$wpdb->posts} WHERE post_type IN ( 'product', 'product_variation' ) AND post_status IN ( %s, %s ) AND ID > %d ORDER BY ID ASC LIMIT %d",
+ self::CLEANUP_PLACEHOLDER_STATUS,
+ self::CLEANUP_CLAIMED_STATUS,
+ $cursor,
+ self::CLEANUP_BATCH_SIZE
+ )
+ );
+
+ if ( ! $post_ids ) {
+ return null;
+ }
+
+ $post_ids = array_map( 'absint', $post_ids );
+ $cursor = (int) end( $post_ids );
+
+ // Ascending IDs delete a placeholder parent before its variations, so WooCommerce removes them through the normal lifecycle.
+ foreach ( $post_ids as $post_id ) {
+ $this->delete_claimed_placeholder( $post_id );
+
+ // One delete lifecycle can take seconds, so check the budget per placeholder rather than per batch.
+ if ( time() >= $deadline ) {
+ return $post_id;
+ }
+ }
+ }
+ }
+
+ /**
+ * Remove temporary mappings between CSV IDs and imported products.
+ *
+ * The last import batch clears them so a run abandoned during cleanup leaves none behind.
+ * Markers from a run abandoned earlier are kept so a retry of the same file skips rows already imported.
+ * Concurrent imports are unsupported: markers and placeholder cleanup are shared site-wide.
+ */
+ public function delete_original_id_markers(): void {
+ global $wpdb;
+
+ // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.SlowDBQuery.slow_db_query_meta_key -- The importer requires one uncached cleanup of its temporary mapping markers.
+ $wpdb->delete( $wpdb->postmeta, array( 'meta_key' => '_original_id' ) );
+ }
+
+ /**
+ * Release temporary products a cleanup request claimed but did not live to delete.
+ *
+ * A fatal inside the delete lifecycle leaves the claimed status behind, and the importer only
+ * recognises a placeholder by the status it was created with, so the CSV row owning that SKU
+ * would be skipped as an existing product. Healing at the start of a run keeps that contained.
+ */
+ public function release_stranded_cleanup_claims(): void {
+ global $wpdb;
+
+ // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
+ $post_ids = $wpdb->get_col(
+ $wpdb->prepare(
+ "SELECT ID FROM {$wpdb->posts} WHERE post_type IN ( 'product', 'product_variation' ) AND post_status = %s",
+ self::CLEANUP_CLAIMED_STATUS
+ )
+ );
+
+ if ( ! $post_ids ) {
+ return;
+ }
+
+ // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
+ $wpdb->query(
+ $wpdb->prepare(
+ "UPDATE {$wpdb->posts} SET post_status = %s WHERE post_type IN ( 'product', 'product_variation' ) AND post_status = %s",
+ self::CLEANUP_PLACEHOLDER_STATUS,
+ self::CLEANUP_CLAIMED_STATUS
+ )
+ );
+
+ wp_cache_delete_multiple( array_map( 'absint', $post_ids ), 'posts' );
+ }
+
+ /**
+ * Claim one importer placeholder and delete it only if the claim succeeded.
+ *
+ * Reading the status from the object cache cannot decide this: a process that completes a
+ * placeholder does not invalidate this process's cache, so a published product would still
+ * look like a placeholder and be force deleted. The guarded UPDATE makes the status check
+ * atomic instead, the way ActionScheduler_DBStore::claim_actions() claims actions, and runs
+ * per post so a placeholder completed while the batch is being deleted is still protected.
+ *
+ * @param int $post_id Candidate post ID.
+ */
+ private function delete_claimed_placeholder( int $post_id ): void {
+ global $wpdb;
+
+ // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
+ $wpdb->query(
+ $wpdb->prepare(
+ "UPDATE {$wpdb->posts} SET post_status = %s WHERE ID = %d AND post_type IN ( 'product', 'product_variation' ) AND post_status IN ( %s, %s )",
+ self::CLEANUP_CLAIMED_STATUS,
+ $post_id,
+ self::CLEANUP_PLACEHOLDER_STATUS,
+ self::CLEANUP_CLAIMED_STATUS
+ )
+ );
+
+ // The claim wrote the row behind the object cache's back, so read it back from the database.
+ wp_cache_delete( $post_id, 'posts' );
+
+ $post = get_post( $post_id );
+
+ if ( ! $post || self::CLEANUP_CLAIMED_STATUS !== $post->post_status ) {
+ return;
+ }
+
+ try {
+ wp_delete_post( $post_id, true );
+ } finally {
+ // Release the claim if the post outlived the delete lifecycle, so it stays a placeholder for the next run.
+ // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
+ $released = $wpdb->query(
+ $wpdb->prepare(
+ "UPDATE {$wpdb->posts} SET post_status = %s WHERE ID = %d AND post_status = %s",
+ self::CLEANUP_PLACEHOLDER_STATUS,
+ $post_id,
+ self::CLEANUP_CLAIMED_STATUS
+ )
+ );
+
+ if ( $released ) {
+ wp_cache_delete( $post_id, 'posts' );
+ }
+ }
+ }
+}
diff --git a/plugins/woocommerce/tests/php/includes/admin/importers/class-wc-product-csv-importer-controller-test.php b/plugins/woocommerce/tests/php/includes/admin/importers/class-wc-product-csv-importer-controller-test.php
index ad903ba6428..4fb75043955 100644
--- a/plugins/woocommerce/tests/php/includes/admin/importers/class-wc-product-csv-importer-controller-test.php
+++ b/plugins/woocommerce/tests/php/includes/admin/importers/class-wc-product-csv-importer-controller-test.php
@@ -373,10 +373,7 @@ class WC_Product_CSV_Importer_Controller_Test extends WC_Unit_Test_Case {
)
);
- $class = new ReflectionClass( WC_Product_CSV_Importer_Controller::class );
- $method = $class->getMethod( 'release_stranded_cleanup_claims' );
- $method->setAccessible( true );
- $method->invoke( null );
+ ( new \Automattic\WooCommerce\Internal\Admin\ImportExport\Product\ImportPlaceholders() )->release_stranded_cleanup_claims();
// The importer only treats the placeholder status as absent, so the row has to read that way again.
$this->assertSame( 'importing', get_post_status( $stranded_id ) );
@@ -538,6 +535,21 @@ class WC_Product_CSV_Importer_Controller_Test extends WC_Unit_Test_Case {
$this->assertSame( 0, (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->postmeta} WHERE meta_key = '_original_id'" ) );
}
+ /**
+ * @testdox A cleanup request should delete placeholders and finish the import.
+ */
+ public function test_cleanup_request_deletes_placeholders_and_finishes(): void {
+ $placeholder = new WC_Product_Simple();
+ $placeholder->set_status( 'importing' );
+ $placeholder->save();
+
+ $response = $this->dispatch_import_request( 'cleanup:0' );
+
+ $this->assertSame( 'done', $response['data']['position'] );
+ $this->assertArrayHasKey( 'url', $response['data'] );
+ $this->assertNull( get_post( $placeholder->get_id() ) );
+ }
+
/**
* @testdox A resumed request should leave the markers of the run in progress alone.
*/
@@ -725,11 +737,7 @@ class WC_Product_CSV_Importer_Controller_Test extends WC_Unit_Test_Case {
* @return int|null ID to resume from, or null once no placeholders are left.
*/
private function invoke_cleanup_after_import( int $cursor = 0 ): ?int {
- $class = new ReflectionClass( WC_Product_CSV_Importer_Controller::class );
- $method = $class->getMethod( 'cleanup_after_import' );
- $method->setAccessible( true );
-
- return $method->invoke( null, $cursor );
+ return ( new \Automattic\WooCommerce\Internal\Admin\ImportExport\Product\ImportPlaceholders() )->cleanup_after_import( $cursor );
}
/**