| 1 |
<?php |
| 2 |
|
| 3 |
namespace SyncBasalam\Services; |
| 4 |
|
| 5 |
use SyncBasalam\Admin\Settings\SettingsConfig; |
| 6 |
use SyncBasalam\Admin\Settings\SettingsManager; |
| 7 |
use SyncBasalam\JobManager; |
| 8 |
|
| 9 |
defined('ABSPATH') || exit; |
| 10 |
|
| 11 |
class ScheduledProductSync |
| 12 |
{ |
| 13 |
public const CRON_HOOK = 'sync_basalam_scheduled_full_product_update'; |
| 14 |
private const FORTY_EIGHT_HOURS = 'sync_basalam_every_48_hours'; |
| 15 |
private const FULL_UPDATE_JOB = 'sync_basalam_update_all_products'; |
| 16 |
|
| 17 |
public function registerHooks(): void |
| 18 |
{ |
| 19 |
add_filter('cron_schedules', [$this, 'addCronSchedule']); |
| 20 |
add_action('init', [$this, 'ensureScheduled']); |
| 21 |
add_action(self::CRON_HOOK, [$this, 'enqueueFullUpdate']); |
| 22 |
} |
| 23 |
|
| 24 |
public function addCronSchedule(array $schedules): array |
| 25 |
{ |
| 26 |
$schedules[self::FORTY_EIGHT_HOURS] = [ |
| 27 |
'interval' => 48 * HOUR_IN_SECONDS, |
| 28 |
'display' => __('Every 48 hours', 'sync-basalam'), |
| 29 |
]; |
| 30 |
|
| 31 |
return $schedules; |
| 32 |
} |
| 33 |
|
| 34 |
public function ensureScheduled(): void |
| 35 |
{ |
| 36 |
$interval = (int) SettingsManager::getSettings(SettingsConfig::AUTO_FULL_UPDATE_INTERVAL); |
| 37 |
$recurrence = $interval === 24 ? 'daily' : ($interval === 48 ? self::FORTY_EIGHT_HOURS : null); |
| 38 |
$nextRun = wp_next_scheduled(self::CRON_HOOK); |
| 39 |
|
| 40 |
if ($recurrence === null) { |
| 41 |
if ($nextRun !== false) self::unschedule(); |
| 42 |
return; |
| 43 |
} |
| 44 |
|
| 45 |
if ($nextRun !== false && wp_get_schedule(self::CRON_HOOK) === $recurrence) return; |
| 46 |
|
| 47 |
if ($nextRun !== false) self::unschedule(); |
| 48 |
|
| 49 |
wp_schedule_event(time() + ($interval * HOUR_IN_SECONDS), $recurrence, self::CRON_HOOK); |
| 50 |
} |
| 51 |
|
| 52 |
public static function unschedule(): void |
| 53 |
{ |
| 54 |
wp_clear_scheduled_hook(self::CRON_HOOK); |
| 55 |
} |
| 56 |
|
| 57 |
public function enqueueFullUpdate(): void |
| 58 |
{ |
| 59 |
if ((int) SettingsManager::getSettings(SettingsConfig::AUTO_FULL_UPDATE_INTERVAL) === 0) return; |
| 60 |
if (!SettingsManager::getSettings(SettingsConfig::TOKEN)) return; |
| 61 |
|
| 62 |
$vendorSyncPolicy = syncBasalamContainer()->get(VendorSyncPolicy::class); |
| 63 |
if (!$vendorSyncPolicy->canUpdate() || !SettingsManager::isProductUpdateSelectionValid()) return; |
| 64 |
|
| 65 |
$jobManager = new JobManager(); |
| 66 |
$activeStatuses = ['pending', 'processing']; |
| 67 |
foreach ([self::FULL_UPDATE_JOB, 'sync_basalam_bulk_update_products'] as $jobType) { |
| 68 |
if ($jobManager->getCountJobs(['job_type' => $jobType, 'status' => $activeStatuses]) > 0) return; |
| 69 |
} |
| 70 |
|
| 71 |
$jobManager->createJob(self::FULL_UPDATE_JOB, 'pending', wp_json_encode(['last_updatable_product_id' => 0])); |
| 72 |
} |
| 73 |
} |
| 74 |
|