Merge pull request #17871 from ragulka/delete-refund-on-exception

Ensure refund is deleted when exception is thrown during wc_create_refund()
This commit is contained in:
Mike Jolley 2017-11-23 13:06:40 +00:00 committed by GitHub
commit 85cd9647df
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 33 additions and 3 deletions

View File

@ -1735,9 +1735,6 @@ class WC_AJAX {
wp_send_json_success( $response_data ); wp_send_json_success( $response_data );
} catch ( Exception $e ) { } catch ( Exception $e ) {
if ( $refund && is_a( $refund, 'WC_Order_Refund' ) ) {
wp_delete_post( $refund->get_id(), true );
}
wp_send_json_error( array( 'error' => $e->getMessage() ) ); wp_send_json_error( array( 'error' => $e->getMessage() ) );
} }
} }

View File

@ -587,6 +587,9 @@ function wc_create_refund( $args = array() ) {
do_action( 'woocommerce_order_refunded', $order->get_id(), $refund->get_id() ); do_action( 'woocommerce_order_refunded', $order->get_id(), $refund->get_id() );
} catch ( Exception $e ) { } catch ( Exception $e ) {
if ( isset( $refund ) && is_a( $refund, 'WC_Order_Refund' ) ) {
wp_delete_post( $refund->get_id(), true );
}
return new WP_Error( 'error', $e->getMessage() ); return new WP_Error( 'error', $e->getMessage() );
} }

View File

@ -81,6 +81,21 @@ class WC_Unit_Test_Case extends WP_UnitTestCase {
$this->assertInstanceOf( 'WP_Error', $actual, $message ); $this->assertInstanceOf( 'WP_Error', $actual, $message );
} }
/**
* Throws an exception with an optional message and code.
*
* Note: can't use `throwException` as that's reserved.
*
* @since 3.3-dev
* @param string $message
* @param int $code
* @throws \Exception
*/
public function throwAnException( $message = null, $code = null ) {
$message = $message ? $message : "We're all doomed!";
throw new Exception( $message, $code );
}
/** /**
* Backport assertNotFalse to PHPUnit 3.6.12 which only runs in PHP 5.2. * Backport assertNotFalse to PHPUnit 3.6.12 which only runs in PHP 5.2.
* *

View File

@ -1656,6 +1656,21 @@ class WC_Tests_CRUD_Orders extends WC_Unit_Test_Case {
$this->assertEquals( 4, $object->get_remaining_refund_items() ); $this->assertEquals( 4, $object->get_remaining_refund_items() );
} }
/**
* Test that if an exception is thrown when creating a refund, the refund is deleted from database.
*/
function test_refund_exception() {
$order = WC_Helper_Order::create_order();
add_action( 'woocommerce_create_refund', array( $this, 'throwAnException' ) );
$refund = wc_create_refund( array(
'order_id' => $order->get_id(),
'amount' => $order->get_total(),
'line_items' => array(),
) );
remove_action( 'woocommerce_create_refund', array( $this, 'throwAnException' ) );
$this->assertEmpty( $order->get_refunds() );
}
/** /**
* Test apply_coupon and remove_coupon with a fixed discount coupon. * Test apply_coupon and remove_coupon with a fixed discount coupon.
* @since 3.2.0 * @since 3.2.0