JobService.php
| 1 | <?php |
| 2 | |
| 3 | namespace SureCart\Sync\Jobs; |
| 4 | |
| 5 | /** |
| 6 | * Job service. |
| 7 | * |
| 8 | * Jobs are processes that queue up tasks to be processed at later time. |
| 9 | * These jobs handle queuing up and processing the syncing and cleanup of |
| 10 | * products and collections. |
| 11 | */ |
| 12 | class JobService { |
| 13 | /** |
| 14 | * The app. |
| 15 | * |
| 16 | * @var \SureCart\App |
| 17 | */ |
| 18 | protected $app; |
| 19 | |
| 20 | /** |
| 21 | * Constructor. |
| 22 | * |
| 23 | * @param \SureCart\App $app The app. |
| 24 | */ |
| 25 | public function __construct( $app ) { |
| 26 | $this->app = $app; |
| 27 | } |
| 28 | |
| 29 | /** |
| 30 | * Run all jobs. |
| 31 | * |
| 32 | * @param array $args The arguments. |
| 33 | * |
| 34 | * @return \WP_Error|void |
| 35 | */ |
| 36 | public function run( $args = [] ) { |
| 37 | // cancel previous processes. |
| 38 | $this->cancel(); |
| 39 | |
| 40 | $args = wp_parse_args( |
| 41 | $args, |
| 42 | [ |
| 43 | 'page' => 1, |
| 44 | 'per_page' => 25, |
| 45 | ] |
| 46 | ); |
| 47 | |
| 48 | // run all jobs. |
| 49 | $result['cleanup_collections'] = $this->cleanup()->collections()->data( $args )->save(); |
| 50 | $result['cleanup_products'] = $this->cleanup()->products()->data( $args )->save(); |
| 51 | $result['sync_products'] = $this->sync()->products()->data( $args )->save()->dispatch(); |
| 52 | |
| 53 | // if any are \WP_Error, return the first one. |
| 54 | foreach ( $result as $value ) { |
| 55 | if ( is_wp_error( $value ) ) { |
| 56 | error_log( $value->get_error_message() ); // phpcs:ignore |
| 57 | return $value; |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | return $result; |
| 62 | } |
| 63 | |
| 64 | /** |
| 65 | * Get the sync jobs. |
| 66 | * |
| 67 | * @return \SureCart\Sync\SyncProcess |
| 68 | */ |
| 69 | public function sync() { |
| 70 | return $this->app->resolve( 'surecart.jobs.sync' ); |
| 71 | } |
| 72 | |
| 73 | /** |
| 74 | * Get the cleanup jobs. |
| 75 | * |
| 76 | * @return \SureCart\Sync\CleanupProcess |
| 77 | */ |
| 78 | public function cleanup() { |
| 79 | return $this->app->resolve( 'surecart.jobs.cleanup' ); |
| 80 | } |
| 81 | |
| 82 | /** |
| 83 | * Cancel all jobs. |
| 84 | * |
| 85 | * @return void |
| 86 | */ |
| 87 | public function cancel() { |
| 88 | $this->sync()->cancel(); |
| 89 | $this->cleanup()->cancel(); |
| 90 | } |
| 91 | |
| 92 | /** |
| 93 | * Is the sync active? |
| 94 | * |
| 95 | * @return boolean |
| 96 | */ |
| 97 | public function isActive() { |
| 98 | return $this->sync()->isActive() || $this->cleanup()->isActive(); |
| 99 | } |
| 100 | } |
| 101 |