/**
* Create or update an order shipping method
*
* @since 2.2
* @param \WC_Order $order
* @param array $shipping item data
* @param string $action 'create' to add shipping or 'update' to update it
* @throws WC_API_Exception invalid data, server error
*/
protected function set_shipping($order, $shipping, $action)
{
// total must be a positive float
if (isset($shipping['total']) && floatval($shipping['total']) < 0) {
throw new WC_API_Exception('woocommerce_invalid_shipping_total', __('Shipping total must be a positive amount', 'woocommerce'), 400);
}
if ('create' === $action) {
// method ID is required
if (!isset($shipping['method_id'])) {
throw new WC_API_Exception('woocommerce_invalid_shipping_item', __('Shipping method ID is required', 'woocommerce'), 400);
}
$rate = new WC_Shipping_Rate($shipping['method_id'], isset($shipping['method_title']) ? $shipping['method_title'] : '', isset($shipping['total']) ? floatval($shipping['total']) : 0, array(), $shipping['method_id']);
$item = new WC_Order_Item_Shipping();
$item->set_shipping_rate($rate);
$shipping_id = $item->save();
if (!$shipping_id) {
throw new WC_API_Exception('woocommerce_cannot_create_shipping', __('Cannot create shipping method, try again', 'woocommerce'), 500);
}
} else {
$item = new WC_Order_Item_Shipping($shipping['id']);
if (isset($shipping['method_id'])) {
$item->set_method_id($shipping['method_id']);
}
if (isset($shipping['method_title'])) {
$item->set_method_title($shipping['method_title']);
}
if (isset($shipping['total'])) {
$item->set_total(floatval($shipping['total']));
}
$shipping_id = $item->save();
if (!$shipping_id) {
throw new WC_API_Exception('woocommerce_cannot_update_shipping', __('Cannot update shipping method, try again', 'woocommerce'), 500);
}
}
}