Files

101 lines
2.2 KiB
PHP
Raw Permalink Normal View History

<?php
/**
2019-05-11 00:40:48 -04:00
* Mutation - removeCoupons
*
2019-05-11 00:40:48 -04:00
* Registers mutation for removing coupon(s) from cart.
*
2019-10-25 19:13:36 -04:00
* @package WPGraphQL\WooCommerce\Mutation
* @since 0.1.0
*/
2019-10-25 19:13:36 -04:00
namespace WPGraphQL\WooCommerce\Mutation;
use GraphQL\Error\UserError;
2019-11-24 23:54:50 -05:00
use WPGraphQL\WooCommerce\Data\Mutation\Cart_Mutation;
/**
2019-05-11 00:40:48 -04:00
* Class - Cart_Remove_Coupons
*/
2019-05-11 00:40:48 -04:00
class Cart_Remove_Coupons {
/**
* Registers mutation
2023-06-13 23:17:02 +03:00
*
* @return void
*/
public static function register_mutation() {
register_graphql_mutation(
2019-05-11 00:40:48 -04:00
'removeCoupons',
[
'inputFields' => self::get_input_fields(),
'outputFields' => self::get_output_fields(),
'mutateAndGetPayload' => self::mutate_and_get_payload(),
]
);
}
/**
* Defines the mutation input field configuration.
*
* @return array
*/
public static function get_input_fields() {
return [
'codes' => [
'type' => [ 'list_of' => 'String' ],
'description' => static function () {
return __( 'Code of coupon being applied', 'graphql-for-ecommerce' );
},
],
];
}
/**
* Defines the mutation output field configuration
*
* @return array
*/
public static function get_output_fields() {
return [
2019-12-16 17:42:03 -05:00
'cart' => Cart_Mutation::get_cart_field(),
];
}
/**
* Defines the mutation data modification closure.
*
* @return callable
*/
public static function mutate_and_get_payload() {
return static function ( $input ) {
Cart_Mutation::check_session_token();
// Retrieve product database ID if relay ID provided.
2019-05-11 00:40:48 -04:00
if ( empty( $input['codes'] ) ) {
throw new UserError( __( 'No coupon codes provided', 'graphql-for-ecommerce' ) );
}
2019-05-11 00:40:48 -04:00
foreach ( $input['codes'] as $code ) {
2019-05-11 00:40:48 -04:00
// Check if applied.
if ( ! \WC()->cart->has_discount( $code ) ) {
throw new UserError( __( 'This coupon has not been applied to the cart.', 'graphql-for-ecommerce' ) );
2019-05-11 00:40:48 -04:00
}
2019-05-11 00:40:48 -04:00
// Get cart item for payload.
$success = \WC()->cart->remove_coupon( $code );
if ( true !== $success ) {
throw new UserError( __( 'Failed to remove coupon.', 'graphql-for-ecommerce' ) );
2019-05-11 00:40:48 -04:00
}
}
// Recalculate totals after coupon removal.
\WC()->cart->calculate_totals();
do_action( 'woographql_update_session', true );
// Return payload.
return [ 'cart' => \WC()->cart ];
};
}
}