WooCommerceImportCleanupService.php
2 months ago
WooCommerceImportJob.php
2 months ago
WooCommerceImportService.php
2 weeks ago
WooCommerceImportTask.php
2 months ago
WooCommerceProductMapper.php
2 months ago
WooCommerceImportCleanupService.php
78 lines
| 1 | <?php |
| 2 | |
| 3 | namespace SureCart\Sync\WooCommerce; |
| 4 | |
| 5 | use SureCart\Models\Product; |
| 6 | |
| 7 | /** |
| 8 | * Cleans up WooCommerce import meta when a SureCart product is deleted, |
| 9 | * allowing the WC product to be re-imported. |
| 10 | */ |
| 11 | class WooCommerceImportCleanupService { |
| 12 | /** |
| 13 | * Bootstrap the service by hooking into product deletion. |
| 14 | * |
| 15 | * @return void |
| 16 | */ |
| 17 | public function bootstrap() { |
| 18 | add_action( 'surecart/product_deleted', [ $this, 'handleProductDeleted' ] ); |
| 19 | } |
| 20 | |
| 21 | /** |
| 22 | * When a SureCart product is deleted, clear the import flag |
| 23 | * on the corresponding WooCommerce product so it can be re-imported. |
| 24 | * |
| 25 | * @param Product $product The deleted SureCart product. |
| 26 | * @return void |
| 27 | */ |
| 28 | public function handleProductDeleted( Product $product ) { |
| 29 | if ( ! class_exists( 'WooCommerce' ) ) { |
| 30 | return; |
| 31 | } |
| 32 | |
| 33 | $wc_product_id = $this->getWcProductId( $product ); |
| 34 | if ( empty( $wc_product_id ) ) { |
| 35 | return; |
| 36 | } |
| 37 | |
| 38 | // Verify the WC product exists. |
| 39 | if ( get_post_type( (int) $wc_product_id ) !== 'product' ) { |
| 40 | return; |
| 41 | } |
| 42 | |
| 43 | // Clear the import flag so the product can be re-imported. |
| 44 | delete_post_meta( (int) $wc_product_id, '_surecart_imported' ); |
| 45 | |
| 46 | // Invalidate cached excluded IDs used by WooCommerceImportJob. |
| 47 | delete_transient( 'sc_woo_import_excluded_ids' ); |
| 48 | |
| 49 | // Reset the fallback purge throttle so the next admin page load re-checks. |
| 50 | delete_transient( 'sc_woo_import_purge_checked' ); |
| 51 | } |
| 52 | |
| 53 | /** |
| 54 | * Extract wc_product_id from the product metadata. |
| 55 | * Handles both object and array formats. |
| 56 | * |
| 57 | * @param Product $product The SureCart product. |
| 58 | * @return int|null |
| 59 | */ |
| 60 | protected function getWcProductId( Product $product ) { |
| 61 | $metadata = $product->metadata ?? null; |
| 62 | |
| 63 | if ( empty( $metadata ) ) { |
| 64 | return null; |
| 65 | } |
| 66 | |
| 67 | if ( is_object( $metadata ) ) { |
| 68 | return $metadata->wc_product_id ?? null; |
| 69 | } |
| 70 | |
| 71 | if ( is_array( $metadata ) ) { |
| 72 | return $metadata['wc_product_id'] ?? null; |
| 73 | } |
| 74 | |
| 75 | return null; |
| 76 | } |
| 77 | } |
| 78 |