Automattic\WooCommerce\Internal\RestApi\Routes\V4\Orders

UpdateUtils::update_line_itemprotectedWC 1.0

Wrapper method to create/update order items. When updating, the item ID provided is checked to ensure it is associated with the order.

Method of the class: UpdateUtils{}

Hooks from the method

Returns

Int. The ID of the updated or created item.

Usage

// protected - for code of main (parent) or child class
$result = $this->update_line_item( $order, $line_items_type, $line_item_data );
$order(WC_Order) (required)
order object.
$line_items_type(string) (required)
The item type.
$line_item_data(array) (required)
item provided in the request body.

UpdateUtils::update_line_item() code WC 10.4.3

protected function update_line_item( WC_Order $order, string $line_items_type, array $line_item_data ) {
	global $wpdb;

	$action = empty( $line_item_data['id'] ) ? 'create' : 'update';
	$method = 'prepare_' . $line_items_type . '_data';
	$item   = null;

	// Verify provided line item ID is associated with order.
	if ( 'update' === $action ) {
		$item = $order->get_item( absint( $line_item_data['id'] ), false );

		if ( ! $item ) {
			throw new WC_REST_Exception( 'woocommerce_rest_invalid_item_id', esc_html__( 'Order item ID provided is not associated with order.', 'woocommerce' ), 400 );
		}
	}

	// Prepare item data.
	$item = $this->$method( $line_item_data, $action, $item );

	/**
	 * Allow extensions be notified before the item is saved.
	 *
	 * @param WC_Order_Item $item The item object.
	 * @param array         $request_data The item data.
	 *
	 * @since 4.5.0.
	 */
	do_action( 'woocommerce_rest_set_order_item', $item, $line_item_data );

	// If creating the order, add the item to it.
	if ( 'create' === $action ) {
		$order->add_item( $item );
	} else {
		$item->save();
	}

	// Maybe update product stock quantity.
	if ( 'line_item' === $line_items_type && in_array( $order->get_status(), array( OrderStatus::PROCESSING, OrderStatus::COMPLETED, OrderStatus::ON_HOLD ), true ) ) {
		require_once WC_ABSPATH . 'includes/admin/wc-admin-functions.php';
		$changed_stock = wc_maybe_adjust_line_item_product_stock( $item );
		if ( $changed_stock && ! is_wp_error( $changed_stock ) ) {
			$order->add_order_note(
				sprintf(
					// translators: %s item name.
					__( 'Adjusted stock: %s.', 'woocommerce' ),
					sprintf(
						'%1$s (%2$s→%3$s)',
						$item->get_name(),
						$changed_stock['from'],
						$changed_stock['to']
					)
				),
				false,
				true,
				array(
					'note_group' => OrderNoteGroup::PRODUCT_STOCK,
				)
			);
		}
	}

	return $item->get_id();
}