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

UpdateUtils::prepare_line_item_dataprotectedWC 1.0

Create or update a line item, overridden to add COGS data as needed.

Method of the class: UpdateUtils{}

No Hooks.

Returns

WC_Order_Item_Product.

Usage

// protected - for code of main (parent) or child class
$result = $this->prepare_line_item_data( $request_data, $action, $item );
$request_data(array) (required)
Line item data.
$action(string)
'create' to add line item or 'update' to update it.
Default: 'create'
$item(object)
Passed when updating an item. Null during creation.
Default: null

UpdateUtils::prepare_line_item_data() code WC 10.4.3

protected function prepare_line_item_data( $request_data, $action = 'create', $item = null ) {
	$item    = is_null( $item ) ? new WC_Order_Item_Product( ! empty( $request_data['id'] ) ? $request_data['id'] : '' ) : $item;
	$product = wc_get_product( $this->get_product_id_from_line_item( $request_data, $action ) );

	if ( $product && $product !== $item->get_product() ) {
		$item->set_product( $product );

		if ( 'create' === $action ) {
			$quantity = isset( $request_data['quantity'] ) ? $request_data['quantity'] : 1;
			$total    = wc_get_price_excluding_tax( $product, array( 'qty' => $quantity ) );
			$item->set_total( $total );
			$item->set_subtotal( $total );
		}
	}

	$this->maybe_set_item_props( $item, array( 'name', 'quantity', 'total', 'subtotal', 'tax_class' ), $request_data );
	$this->maybe_set_item_meta_data( $item, $request_data );

	if ( ! $item->has_cogs() || ! $this->cogs_is_enabled() ) {
		return $item;
	}

	$cogs_value = $request_data['cost_of_goods_sold']['total_value'] ?? null;
	if ( ! is_null( $cogs_value ) ) {
		$item->set_cogs_value( (float) $cogs_value );
	}

	return $item;
}