Automattic\WooCommerce\Internal\RestApi\Routes\V4\Refunds
DataUtils::validate_line_items
Validate line items (schema format) before conversion to internal format.
Method of the class: DataUtils{}
No Hooks.
Returns
true|false|WP_Error.
Usage
$DataUtils = new DataUtils(); $DataUtils->validate_line_items( $line_items, $order );
- $line_items(array) (required)
- The line items to validate.
- $order(WC_Order) (required)
- The order object.
DataUtils::validate_line_items() DataUtils::validate line items code WC 10.4.3
public function validate_line_items( $line_items, WC_Order $order ) {
foreach ( $line_items as $line_item ) {
$line_item_id = $line_item['line_item_id'] ?? null;
if ( ! $line_item_id ) {
return new WP_Error( 'invalid_line_item', __( 'Line item ID is required.', 'woocommerce' ) );
}
$item = $order->get_item( $line_item_id );
// Validate item exists and belongs to the order.
if ( ! $item || $item->get_order_id() !== $order->get_id() ) {
return new WP_Error( 'invalid_line_item', __( 'Line item not found.', 'woocommerce' ) );
}
if ( ! $item instanceof \WC_Order_Item_Product && ! $item instanceof \WC_Order_Item_Fee && ! $item instanceof \WC_Order_Item_Shipping ) {
return new WP_Error( 'invalid_line_item', __( 'Line item is not a product, fee, or shipping line.', 'woocommerce' ) );
}
// Validate item quantity is not greater than the item quantity.
if ( $item->get_quantity() < $line_item['quantity'] ) {
/* translators: %s: item quantity */
return new WP_Error( 'invalid_line_item', sprintf( __( 'Line item quantity cannot be greater than the item quantity (%s).', 'woocommerce' ), $item->get_quantity() ) );
}
// Validate refund total is not greater than the item total.
if ( $item->get_total() < $line_item['refund_total'] ) {
return new WP_Error(
'invalid_refund_amount',
sprintf(
/* translators: %s: item total */
__( 'Refund total cannot be greater than the line item total (%s).', 'woocommerce' ),
$item->get_total()
)
);
}
if ( isset( $line_item['refund_tax'] ) ) {
$item_taxes = $item->get_taxes();
if ( $item_taxes ) {
$allowed_tax_ids = array_keys( $item_taxes['total'] ?? array() );
foreach ( $line_item['refund_tax'] as $refund_tax ) {
if ( ! isset( $refund_tax['id'], $refund_tax['refund_total'] ) ) {
return new WP_Error( 'invalid_line_item', __( 'Tax id and refund_total are required.', 'woocommerce' ) );
}
$tax_id = $refund_tax['id'];
$tax_refund_total = $refund_tax['refund_total'];
if ( ! in_array( $tax_id, $allowed_tax_ids, true ) ) {
return new WP_Error(
'invalid_line_item',
sprintf(
/* translators: %s: tax IDs */
__( 'Line item tax not found. Must be: %s.', 'woocommerce' ),
implode( ', ', $allowed_tax_ids )
)
);
}
if ( $item_taxes['total'][ $tax_id ] < $tax_refund_total ) {
return new WP_Error(
'invalid_refund_amount',
sprintf(
/* translators: %s: tax total */
__( 'Refund tax total cannot be greater than the line item tax total (%s).', 'woocommerce' ),
$item_taxes['total'][ $tax_id ]
)
);
}
}
}
}
}
return true;
}