From 1ddd2f134ad551d2675dfeea6d026599a61d358b Mon Sep 17 00:00:00 2001 From: vendidero Date: Tue, 16 Jul 2024 10:03:00 +0200 Subject: [PATCH] Prevent persisting shipment items before shipment has been saved to make sure no orphan (shipment_id = 0) items exist in DB. Prevent reading items for shipments with empty id. --- includes/wc-gzd-shipment-functions.php | 5 +++-- src/DataStores/Shipment.php | 4 ++++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/includes/wc-gzd-shipment-functions.php b/includes/wc-gzd-shipment-functions.php index 8874ccb..3a0afcf 100644 --- a/includes/wc-gzd-shipment-functions.php +++ b/includes/wc-gzd-shipment-functions.php @@ -461,7 +461,6 @@ function wc_gzd_create_shipment( $order_shipment, $args = array() ) { function wc_gzd_create_shipment_item( $shipment, $order_item, $args = array() ) { try { - if ( ! $order_item || ! is_a( $order_item, 'WC_Order_Item' ) ) { throw new Exception( _x( 'Invalid order item', 'shipments', 'woocommerce-germanized-shipments' ) ); } @@ -471,8 +470,10 @@ function wc_gzd_create_shipment_item( $shipment, $order_item, $args = array() ) $item->set_order_item_id( $order_item->get_id() ); $item->set_shipment( $shipment ); $item->sync( $args ); - $item->save(); + if ( $shipment->get_id() > 0 ) { + $item->save(); + } } catch ( Exception $e ) { return new WP_Error( 'error', $e->getMessage() ); } diff --git a/src/DataStores/Shipment.php b/src/DataStores/Shipment.php index 141f2e6..9618689 100644 --- a/src/DataStores/Shipment.php +++ b/src/DataStores/Shipment.php @@ -559,6 +559,10 @@ protected function update_or_delete_meta( $object, $meta_key, $meta_value ) { public function read_items( $shipment ) { global $wpdb; + if ( $shipment->get_id() <= 0 ) { + return array(); + } + // Get from cache if available. $items = 0 < $shipment->get_id() ? wp_cache_get( 'shipment-items-' . $shipment->get_id(), 'shipments' ) : false;