CollectionsCleanupJob.php
80 lines
| 1 | <?php |
| 2 | |
| 3 | namespace SureCart\Sync\Jobs\Cleanup; |
| 4 | |
| 5 | use SureCart\Background\Job; |
| 6 | |
| 7 | /** |
| 8 | * This process fetches and queues all products collections for syncing. |
| 9 | */ |
| 10 | class CollectionsCleanupJob extends Job { |
| 11 | /** |
| 12 | * The prefix for the action. |
| 13 | * |
| 14 | * @var string |
| 15 | */ |
| 16 | protected $prefix = 'surecart'; |
| 17 | |
| 18 | /** |
| 19 | * The action. |
| 20 | * |
| 21 | * @var string |
| 22 | */ |
| 23 | protected $action = 'cleanup_product_collections'; |
| 24 | |
| 25 | /** |
| 26 | * Perform task with queued item. |
| 27 | * |
| 28 | * Override this method to perform any actions required on each |
| 29 | * queue item. Return the modified item for further processing |
| 30 | * in the next pass through. Or, return false to remove the |
| 31 | * item from the queue. |
| 32 | * |
| 33 | * @param mixed $args Queue item to iterate over. |
| 34 | * |
| 35 | * @return mixed |
| 36 | */ |
| 37 | protected function task( $args ) { |
| 38 | // Delete all terms who have sc_account in term meta as meta key & the value is not equal to the current account id. |
| 39 | $batch_size = $args['batch_size'] ?? 25; |
| 40 | $page = $args['page'] ?? 1; |
| 41 | $offset = ( $page - 1 ) * $batch_size; |
| 42 | |
| 43 | $terms = get_terms( |
| 44 | [ |
| 45 | 'number' => $batch_size, |
| 46 | 'offset' => $offset, |
| 47 | 'taxonomy' => 'sc_collection', |
| 48 | 'hide_empty' => false, |
| 49 | 'fields' => 'ids', |
| 50 | 'meta_query' => [ |
| 51 | [ |
| 52 | 'key' => 'sc_account', |
| 53 | 'value' => \SureCart::account()->id, |
| 54 | 'compare' => 'NOT IN', // Excludes terms where value is the current account ID. |
| 55 | ], |
| 56 | ], |
| 57 | ] |
| 58 | ); |
| 59 | |
| 60 | if ( empty( $terms ) ) { |
| 61 | return false; // No more terms to delete, stop processing. |
| 62 | } |
| 63 | |
| 64 | foreach ( $terms as $term_id ) { |
| 65 | $this->task->queue( $term_id ); |
| 66 | } |
| 67 | |
| 68 | // If we got fewer terms than batch size, assume there are no more terms left. |
| 69 | if ( count( $terms ) < $batch_size ) { |
| 70 | return false; |
| 71 | } |
| 72 | |
| 73 | // Continue processing the next batch. |
| 74 | return [ |
| 75 | 'page' => $page + 1, |
| 76 | 'batch_size' => $batch_size, |
| 77 | ]; |
| 78 | } |
| 79 | } |
| 80 |