Files
wp-graphql-woocommerce/includes/mutation/class-cart-remove-coupons.php
T
Geoff TaylorandGitHub 684732aa0d perf: Migrate type descriptions to lazy lambdas (#1005)
* perf: Migrate type descriptions to lazy lambdas

Convert all eager description strings from:
  'description' => __( '...', 'wp-graphql-woocommerce' ),
to deferred lambdas:
  'description' => static function () { return __( '...', 'wp-graphql-woocommerce' ); },

This defers the __() translation call until the description is actually
needed (e.g. during schema introspection), avoiding unnecessary
translation overhead on every GraphQL request. Mirrors the pattern
used in WPGraphQL core.

1206 descriptions converted across 169 files.

* chore: Linter compliances met
2026-03-30 23:37:51 -04:00

101 lines
2.2 KiB
PHP

<?php
/**
* Mutation - removeCoupons
*
* Registers mutation for removing coupon(s) from cart.
*
* @package WPGraphQL\WooCommerce\Mutation
* @since 0.1.0
*/
namespace WPGraphQL\WooCommerce\Mutation;
use GraphQL\Error\UserError;
use WPGraphQL\WooCommerce\Data\Mutation\Cart_Mutation;
/**
* Class - Cart_Remove_Coupons
*/
class Cart_Remove_Coupons {
/**
* Registers mutation
*
* @return void
*/
public static function register_mutation() {
register_graphql_mutation(
'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', 'wp-graphql-woocommerce' );
},
],
];
}
/**
* Defines the mutation output field configuration
*
* @return array
*/
public static function get_output_fields() {
return [
'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.
if ( empty( $input['codes'] ) ) {
throw new UserError( __( 'No coupon codes provided', 'wp-graphql-woocommerce' ) );
}
foreach ( $input['codes'] as $code ) {
// Check if applied.
if ( ! \WC()->cart->has_discount( $code ) ) {
throw new UserError( __( 'This coupon has not been applied to the cart.', 'wp-graphql-woocommerce' ) );
}
// Get cart item for payload.
$success = \WC()->cart->remove_coupon( $code );
if ( true !== $success ) {
throw new UserError( __( 'Failed to remove coupon.', 'wp-graphql-woocommerce' ) );
}
}
// Recalculate totals after coupon removal.
\WC()->cart->calculate_totals();
do_action( 'woographql_update_session', true );
// Return payload.
return [ 'cart' => \WC()->cart ];
};
}
}