| 1 |
<?php |
| 2 |
/** |
| 3 |
* Packeta shipping method class. |
| 4 |
* |
| 5 |
* @package Packetery |
| 6 |
*/ |
| 7 |
|
| 8 |
declare( strict_types=1 ); |
| 9 |
|
| 10 |
namespace Packetery\Module; |
| 11 |
|
| 12 |
/** |
| 13 |
* Packeta shipping method class. |
| 14 |
*/ |
| 15 |
class ShippingMethod extends \WC_Shipping_Method { |
| 16 |
|
| 17 |
public const PACKETERY_METHOD_ID = 'packetery_shipping_method'; |
| 18 |
|
| 19 |
/** |
| 20 |
* Checkout object. |
| 21 |
* |
| 22 |
* @var Checkout |
| 23 |
*/ |
| 24 |
private $checkout; |
| 25 |
|
| 26 |
/** |
| 27 |
* Constructor for Packeta shipping class |
| 28 |
* |
| 29 |
* @param int $instance_id Shipping method instance id. |
| 30 |
*/ |
| 31 |
public function __construct( int $instance_id = 0 ) { |
| 32 |
parent::__construct(); |
| 33 |
$this->id = self::PACKETERY_METHOD_ID; |
| 34 |
$this->instance_id = absint( $instance_id ); |
| 35 |
$this->method_title = __( 'Packeta Shipping Method', 'packetery' ); |
| 36 |
$this->title = __( 'Packeta Shipping Method', 'packetery' ); |
| 37 |
$this->enabled = 'yes'; // This can be added as an setting but for this example its forced enabled. |
| 38 |
$this->supports = array( |
| 39 |
'shipping-zones', |
| 40 |
); |
| 41 |
$this->init(); |
| 42 |
|
| 43 |
$container = CompatibilityBridge::getContainer(); |
| 44 |
$this->checkout = $container->getByType( Checkout::class ); |
| 45 |
} |
| 46 |
|
| 47 |
/** |
| 48 |
* Init settings. |
| 49 |
* |
| 50 |
* @return void |
| 51 |
*/ |
| 52 |
public function init(): void { |
| 53 |
// todo Load the settings API |
| 54 |
// $this->init_form_fields(); // This is part of the settings API. Override the method to add your own settings |
| 55 |
// $this->init_settings(); // This is part of the settings API. Loads settings you previously init. |
| 56 |
|
| 57 |
// Save settings in admin if you have any defined. |
| 58 |
\add_action( |
| 59 |
'woocommerce_update_options_shipping_' . $this->id, |
| 60 |
array( |
| 61 |
$this, |
| 62 |
'process_admin_options', |
| 63 |
) |
| 64 |
); |
| 65 |
} |
| 66 |
|
| 67 |
/** |
| 68 |
* Function to calculate shipping fee. |
| 69 |
* Triggered by cart contents change, country change. |
| 70 |
* |
| 71 |
* @param array $package Order information. |
| 72 |
* |
| 73 |
* @return void |
| 74 |
*/ |
| 75 |
public function calculate_shipping( $package = [] ): void { |
| 76 |
$customRates = $this->checkout->getShippingRates(); |
| 77 |
foreach ( $customRates as $customRate ) { |
| 78 |
$this->add_rate( $customRate ); |
| 79 |
} |
| 80 |
} |
| 81 |
} |
| 82 |
|