Files

110 lines
2.7 KiB
PHP
Raw Permalink Normal View History

<?php
/**
* Mutation - removeItemsFromCart
*
* Registers mutation for removing cart item(s) from the 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;
use GraphQL\Type\Definition\ResolveInfo;
use WPGraphQL\AppContext;
2019-10-25 19:13:36 -04:00
use WPGraphQL\WooCommerce\Data\Mutation\Cart_Mutation;
/**
* Class - Cart_Remove_Items
*/
class Cart_Remove_Items {
/**
* Registers mutation
2023-06-13 23:17:02 +03:00
*
* @return void
*/
public static function register_mutation() {
register_graphql_mutation(
'removeItemsFromCart',
[
'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 [
'keys' => [
'type' => [ 'list_of' => 'ID' ],
'description' => static function () {
return __( 'Item keys of the items being removed', 'graphql-for-ecommerce' );
},
],
'all' => [
'type' => 'Boolean',
'description' => static function () {
return __( 'Remove all cart items', 'graphql-for-ecommerce' );
},
],
];
}
/**
* Defines the mutation output field configuration
*
* @return array
*/
public static function get_output_fields() {
return [
'cartItems' => [
'type' => [ 'list_of' => 'CartItem' ],
'resolve' => static function ( $payload ) {
return $payload['items'];
},
],
2019-12-16 17:42:03 -05:00
'cart' => Cart_Mutation::get_cart_field( true ),
];
}
/**
* Defines the mutation data modification closure.
*
* @return callable
*/
public static function mutate_and_get_payload() {
return static function ( $input, AppContext $context, ResolveInfo $info ) {
Cart_Mutation::check_session_token();
if ( \WC()->cart->is_empty() ) {
throw new UserError( __( 'No items in cart to remove.', 'graphql-for-ecommerce' ) );
}
if ( empty( $input['keys'] ) && empty( $input['all'] ) ) {
throw new UserError( __( 'No cart item keys provided', 'graphql-for-ecommerce' ) );
}
$cart_items = Cart_Mutation::retrieve_cart_items( $input, $context, $info, 'remove' );
foreach ( $cart_items as $item ) {
$success = \WC()->cart->remove_cart_item( $item['key'] );
if ( false === $success ) {
/* translators: Cart item removal failure message */
throw new UserError( sprintf( __( 'Failed to remove item %s from cart.', 'graphql-for-ecommerce' ), $item['key'] ) );
}
}
do_action( 'woographql_update_session', true );
// Return payload.
return [ 'items' => $cart_items ];
};
}
}