| 1 |
<?php |
| 2 |
/** |
| 3 |
* Class MetaboxesWrapper. |
| 4 |
* |
| 5 |
* @package Packetery |
| 6 |
*/ |
| 7 |
|
| 8 |
declare( strict_types=1 ); |
| 9 |
|
| 10 |
namespace Packetery\Module\Order; |
| 11 |
|
| 12 |
use WC_Order; |
| 13 |
|
| 14 |
/** |
| 15 |
* Class MetaboxesWrapper. |
| 16 |
*/ |
| 17 |
class MetaboxesWrapper { |
| 18 |
|
| 19 |
/** |
| 20 |
* General order metabox. |
| 21 |
* |
| 22 |
* @var Metabox |
| 23 |
*/ |
| 24 |
private $generalMetabox; |
| 25 |
|
| 26 |
/** |
| 27 |
* Customs declaration metabox. |
| 28 |
* |
| 29 |
* @var CustomsDeclarationMetabox |
| 30 |
*/ |
| 31 |
private $customDeclarationMetabox; |
| 32 |
|
| 33 |
/** |
| 34 |
* Order repository. |
| 35 |
* |
| 36 |
* @var Repository |
| 37 |
*/ |
| 38 |
private $orderRepository; |
| 39 |
|
| 40 |
/** |
| 41 |
* Constructor. |
| 42 |
* |
| 43 |
* @param Metabox $generalMetabox General metabox. |
| 44 |
* @param CustomsDeclarationMetabox $customDeclarationMetabox Customs declaration metabox. |
| 45 |
* @param Repository $orderRepository Order repository. |
| 46 |
*/ |
| 47 |
public function __construct( |
| 48 |
Metabox $generalMetabox, |
| 49 |
CustomsDeclarationMetabox $customDeclarationMetabox, |
| 50 |
Repository $orderRepository |
| 51 |
) { |
| 52 |
$this->generalMetabox = $generalMetabox; |
| 53 |
$this->customDeclarationMetabox = $customDeclarationMetabox; |
| 54 |
$this->orderRepository = $orderRepository; |
| 55 |
} |
| 56 |
|
| 57 |
/** |
| 58 |
* Registers metaboxes. |
| 59 |
* |
| 60 |
* @return void |
| 61 |
*/ |
| 62 |
public function register(): void { |
| 63 |
$this->generalMetabox->register(); |
| 64 |
$this->customDeclarationMetabox->register(); |
| 65 |
add_action( 'woocommerce_before_order_object_save', [ $this, 'beforeOrderSave' ], PHP_INT_MAX ); |
| 66 |
} |
| 67 |
|
| 68 |
/** |
| 69 |
* Updates order object before persisting its new data to DB. |
| 70 |
* |
| 71 |
* @param WC_Order $wcOrder WC Order. |
| 72 |
* |
| 73 |
* @return void |
| 74 |
*/ |
| 75 |
public function beforeOrderSave( WC_Order $wcOrder ): void { |
| 76 |
$order = $this->orderRepository->getByIdWithValidCarrier( $wcOrder->get_id() ); |
| 77 |
if ( $order === null ) { |
| 78 |
return; |
| 79 |
} |
| 80 |
|
| 81 |
$this->generalMetabox->saveFields( $order, $wcOrder ); |
| 82 |
} |
| 83 |
|
| 84 |
/** |
| 85 |
* Saves metabox fields. |
| 86 |
* |
| 87 |
* @param int|mixed $wcOrderId Order ID. |
| 88 |
* |
| 89 |
* @return void |
| 90 |
* @throws \WC_Data_Exception When invalid data are passed during shipping address update. |
| 91 |
*/ |
| 92 |
public function saveFields( $wcOrderId ): void { |
| 93 |
$order = $this->orderRepository->getByIdWithValidCarrier( (int) $wcOrderId ); |
| 94 |
|
| 95 |
if ( $order === null ) { |
| 96 |
return; |
| 97 |
} |
| 98 |
|
| 99 |
$this->customDeclarationMetabox->saveFields( $order ); |
| 100 |
} |
| 101 |
} |
| 102 |
|