Skip to content
This repository has been archived by the owner on Feb 23, 2024. It is now read-only.

Commit

Permalink
calculate cart totals afer running extensions
Browse files Browse the repository at this point in the history
  • Loading branch information
senadir committed Oct 27, 2022
1 parent b8cb54d commit c9aa4b5
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 13 deletions.
12 changes: 1 addition & 11 deletions src/StoreApi/Routes/V1/AbstractCartRoute.php
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ public function __construct( SchemaController $schema_controller, AbstractSchema
*/
public function get_response( \WP_REST_Request $request ) {
$this->load_cart_session( $request );
$this->calculate_totals();
$this->cart_controller->calculate_totals();

if ( $this->requires_nonce( $request ) ) {
$nonce_check = $this->check_nonce( $request );
Expand Down Expand Up @@ -229,16 +229,6 @@ protected function cart_updated( \WP_REST_Request $request ) {
}
}

/**
* Ensures the cart totals are calculated before an API response is generated.
*/
protected function calculate_totals() {
wc()->cart->get_cart();
wc()->cart->calculate_fees();
wc()->cart->calculate_shipping();
wc()->cart->calculate_totals();
}

/**
* For non-GET endpoints, require and validate a nonce to prevent CSRF attacks.
*
Expand Down
8 changes: 6 additions & 2 deletions src/StoreApi/Schemas/V1/CartExtensionsSchema.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,12 +69,16 @@ public function get_item_response( $request = null ) {
400
);
}

$controller = new CartController();

if ( is_callable( $callback ) ) {
$callback( $request['data'] );
// We recalculate the cart if we had something to run.
$controller->calculate_totals();
}

$controller = new CartController();
$cart = $controller->get_cart_instance();
$cart = $controller->get_cart_instance();

return rest_ensure_response( $this->cart_schema->get_item_response( $cart ) );
}
Expand Down
11 changes: 11 additions & 0 deletions src/StoreApi/Utilities/CartController.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,17 @@ public function load_cart() {
}
}

/**
* Recalculates the cart totals.
*/
public function calculate_totals() {
$cart = $this->get_cart_instance();
$cart->get_cart();
$cart->calculate_fees();
$cart->calculate_shipping();
$cart->calculate_totals();
}

/**
* Based on the core cart class but returns errors rather than rendering notices directly.
*
Expand Down

0 comments on commit c9aa4b5

Please sign in to comment.