PluginProbe
Sendy / trunk
Sendy vtrunk
3.4.6 3.4.7 trunk 3.0 3.0.1 3.0.2 3.0.3 3.0.4 3.0.5 3.0.6 3.0.7 3.0.8 3.0.9 3.1.0 3.1.1 3.1.2 3.1.3 3.2.0 3.2.1 3.2.2 3.2.3 3.2.4 3.2.5 3.2.6 3.2.7 All 32 releases
sendy / lib / Modules / ShippingMethodsSynchronizer.php

ShippingMethodsSynchronizer.php in Sendy trunk, at lib/Modules/ShippingMethodsSynchronizer.php

78 lines 2.3 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace Sendy\WooCommerce\Modules;
4
5 use Sendy\Api\ApiException;
6 use Sendy\WooCommerce\Enums\ProcessingMethod;
7 use Sendy\WooCommerce\Resources\ShippingMethod;
8
9 class ShippingMethodsSynchronizer
10 {
11 public function __construct()
12 {
13 if (get_option('sendy_processing_method') === ProcessingMethod::Sendy) {
14 add_action('sendy_cron', [$this, 'synchronize_shipping_methods']);
15 add_action('woocommerce_shipping_zone_method_added', [$this, 'handle_method_added'], 10, 3);
16 add_action('woocommerce_shipping_zone_method_deleted', [$this, 'handle_method_deleted'], 10, 2);
17 }
18 }
19
20 public function synchronize_shipping_methods(): void
21 {
22 if (get_option('sendy_shipping_methods_last_sync') > time() - 24 * 60 * 60) {
23 return;
24 }
25
26 $this->synchronizeShippingMethods();
27 }
28
29 public function handle_method_added($instanceId, $methodId, $zoneId): void
30 {
31 $this->synchronizeShippingMethods();
32 }
33
34 public function handle_method_deleted($instanceId, $zoneId): void
35 {
36 $this->synchronizeShippingMethods();
37 }
38
39 public function deactivate(): void
40 {
41 delete_option('sendy_shipping_methods_last_sync');
42 }
43
44 private function synchronizeShippingMethods(): void
45 {
46 $data = [];
47
48 $zones = \WC_Shipping_Zones::get_zones();
49
50 foreach ($zones as $zone) {
51 foreach ($zone['shipping_methods'] as $instanceId => $method) {
52 $data[] = [
53 'external_id' => (string) $instanceId,
54 'name' => "{$zone['zone_name']} - {$method->get_title()}",
55 ];
56 }
57 }
58
59 // The 'Rest of the world' zone is treated differently than other zones and will always have '0' as the ID
60 $defaultZone = new \WC_Shipping_Zone(0);
61
62 foreach ($defaultZone->get_shipping_methods() as $instanceId => $method) {
63 $data[] = [
64 'external_id' => (string) $instanceId,
65 'name' => __('Rest of the world', 'sendy') . " - " . $method->get_title(),
66 ];
67 }
68
69 try {
70 (new ShippingMethod())->sync($data);
71 } catch (ApiException $exception) {
72 // TODO Implement logging
73 }
74
75 update_option('sendy_shipping_methods_last_sync', time());
76 }
77 }
78