Files

327 lines
9.9 KiB
PHP
Raw Permalink Normal View History

2019-05-03 17:36:08 -04:00
<?php
/**
* Defines helper functions for executing mutations related to the cart.
*
2019-10-25 19:13:36 -04:00
* @package WPGraphQL\WooCommerce\Data\Mutation
2019-05-03 17:36:08 -04:00
* @since 0.1.0
*/
2019-10-25 19:13:36 -04:00
namespace WPGraphQL\WooCommerce\Data\Mutation;
2019-05-03 17:36:08 -04:00
use GraphQL\Error\UserError;
2020-03-24 20:55:13 -04:00
use WPGraphQL\WooCommerce\Data\Factory;
2019-05-03 17:36:08 -04:00
/**
* Class - Cart_Mutation
*/
class Cart_Mutation {
2019-12-16 17:42:03 -05:00
/**
* Retrieve `cart` output field defintion
*
* @param bool $fallback Should cart be retrieved, if not provided in payload.
* @return array
*/
public static function get_cart_field( $fallback = false ) {
return [
2019-12-16 17:42:03 -05:00
'type' => 'Cart',
'resolve' => static function ( $payload ) use ( $fallback ) {
2019-12-16 17:42:03 -05:00
$cart = ! empty( $payload['cart'] ) ? $payload['cart'] : null;
2019-12-16 17:42:03 -05:00
if ( is_null( $cart ) && $fallback ) {
2020-03-24 20:55:13 -04:00
$cart = Factory::resolve_cart();
2019-12-16 17:42:03 -05:00
}
return $cart;
},
];
2019-12-16 17:42:03 -05:00
}
2019-05-03 17:36:08 -04:00
/**
* Returns a cart item.
2019-05-03 17:36:08 -04:00
*
* @param array $input Input data describing cart item.
* @param \WPGraphQL\AppContext $context AppContext instance.
* @param \GraphQL\Type\Definition\ResolveInfo $info Query info.
2019-05-03 17:36:08 -04:00
*
* @throws \GraphQL\Error\UserError Missing/Invalid input.
*
2019-05-03 17:36:08 -04:00
* @return array
*/
public static function prepare_cart_item( $input, $context, $info ) {
if ( empty( $input['productId'] ) ) {
throw new UserError( __( 'No product ID provided', 'graphql-for-ecommerce' ) );
}
if ( ! \wc_get_product( $input['productId'] ) ) {
throw new UserError( __( 'No product found matching the ID provided', 'graphql-for-ecommerce' ) );
}
$cart_item_args = [ $input['productId'] ];
2019-08-13 16:17:14 -04:00
$cart_item_args[] = ! empty( $input['quantity'] ) ? $input['quantity'] : 1;
$cart_item_args[] = ! empty( $input['variationId'] ) ? $input['variationId'] : 0;
$cart_item_args[] = ! empty( $input['variation'] ) ? self::prepare_attributes( $input['productId'], $input['variation'] ) : [];
2019-08-13 16:17:14 -04:00
$cart_item_args[] = ! empty( $input['extraData'] )
? json_decode( $input['extraData'], true )
: [];
2019-05-03 17:36:08 -04:00
return apply_filters( 'graphql_woocommerce_new_cart_item_data', $cart_item_args, $input, $context, $info );
2019-05-03 17:36:08 -04:00
}
2019-05-07 19:05:55 -04:00
2020-10-02 12:37:30 -04:00
/**
* Processes the provided variation attributes data for the cart.
*
2021-01-21 22:41:43 -05:00
* @param int $product_id Product ID.
2020-10-02 12:37:30 -04:00
* @param array $variation_data Variation data.
2021-01-21 22:41:43 -05:00
*
2020-10-02 12:37:30 -04:00
* @return array
2021-01-21 22:41:43 -05:00
*
* @throws \GraphQL\Error\UserError Invalid cart attribute provided.
2020-10-02 12:37:30 -04:00
*/
public static function prepare_attributes( $product_id, array $variation_data = [] ) {
2023-06-13 23:17:02 +03:00
$product = wc_get_product( $product_id );
// Bail if bad product ID.
if ( ! $product ) {
throw new UserError(
sprintf(
/* translators: %s: product ID */
__( 'No product found matching the ID provided: %s', 'graphql-for-ecommerce' ),
2023-06-13 23:17:02 +03:00
$product_id
)
);
}
2020-10-02 12:37:30 -04:00
$attribute_names = array_keys( $product->get_attributes() );
$attributes = [];
2021-01-21 22:41:43 -05:00
foreach ( $variation_data as $attribute ) {
$attribute_name = $attribute['attributeName'];
2020-10-02 12:37:30 -04:00
if ( in_array( "pa_{$attribute_name}", $attribute_names, true ) ) {
$attribute_name = "pa_{$attribute_name}";
} elseif ( ! in_array( $attribute_name, $attribute_names, true ) ) {
throw new UserError(
sprintf(
2021-01-21 22:41:43 -05:00
/* translators: %1$s: attribute name, %2$s: product name */
__( '%1$s is not a valid attribute of the product: %2$s.', 'graphql-for-ecommerce' ),
2020-10-02 12:37:30 -04:00
$attribute_name,
$product->get_name()
)
);
}
$attribute_value = ! empty( $attribute['attributeValue'] ) ? $attribute['attributeValue'] : '';
2021-01-21 22:41:43 -05:00
$attribute_key = "attribute_{$attribute_name}";
2020-10-02 12:37:30 -04:00
$attributes[ $attribute_key ] = $attribute_value;
}
return $attributes;
}
/**
* Returns an array of cart items.
*
* @param array $input Input data describing cart items.
* @param \WPGraphQL\AppContext $context AppContext instance.
* @param \GraphQL\Type\Definition\ResolveInfo $info Query info.
* @param string $mutation Mutation type.
*
* @return array
* @throws \GraphQL\Error\UserError Cart item not found message.
*/
public static function retrieve_cart_items( $input, $context, $info, $mutation = '' ) {
2023-06-13 23:17:02 +03:00
$items = null;
// If "all" flag provided, retrieve all cart items.
if ( ! empty( $input['all'] ) ) {
$items = array_values( \WC()->cart->get_cart() );
}
2023-06-13 23:17:02 +03:00
// If keys are provided and cart items haven't been retrieve yet,
// retrieve the cart items by key.
if ( ! empty( $input['keys'] ) && null === $items ) {
$items = [];
foreach ( $input['keys'] as $key ) {
$item = \WC()->cart->get_cart_item( $key );
if ( empty( $item ) ) {
/* translators: Cart item not found message */
throw new UserError( sprintf( __( 'No cart item found with the key: %s', 'graphql-for-ecommerce' ), $key ) );
}
$items[] = $item;
}
}
return apply_filters( 'graphql_woocommerce_retrieve_cart_items', $items, $input, $context, $info, $mutation );
}
2019-05-07 19:05:55 -04:00
/**
* Return array of data to be when defining a cart fee.
*
* @param array $input input data describing cart item.
* @param \WPGraphQL\AppContext $context AppContext instance.
* @param \GraphQL\Type\Definition\ResolveInfo $info query info.
2019-05-07 19:05:55 -04:00
*
* @return array
*/
public static function prepare_cart_fee( $input, $context, $info ) {
$cart_item_args = [
2019-05-07 19:05:55 -04:00
$input['name'],
$input['amount'],
! empty( $input['taxable'] ) ? $input['taxable'] : false,
! empty( $input['taxClass'] ) ? $input['taxClass'] : '',
];
2019-05-07 19:05:55 -04:00
return apply_filters( 'graphql_woocommerce_new_cart_fee_data', $cart_item_args, $input, $context, $info );
2019-05-07 19:05:55 -04:00
}
2021-02-18 02:11:14 -05:00
/**
* Validates coupon and checks if application is possible
*
* @param string $code Coupon code.
* @param string $reason Reason for failure.
*
* @return bool
*/
public static function validate_coupon( $code, &$reason = '' ) {
// Get the coupon.
$the_coupon = new \WC_Coupon( $code );
// Prevent adding coupons by post ID.
if ( is_numeric( $code ) && strtoupper( $the_coupon->get_code() ) !== strtoupper( $code ) ) {
$reason = __( 'No coupon found with the code provided', 'graphql-for-ecommerce' );
2021-02-18 02:11:14 -05:00
return false;
}
// Check it can be used with cart.
$discounts = new \WC_Discounts( \WC()->cart );
$valid = $discounts->is_coupon_valid( $the_coupon );
if ( is_wp_error( $valid ) ) {
$reason = $valid->get_error_message();
2021-02-18 02:11:14 -05:00
return false;
}
// Check if applied.
if ( \WC()->cart->has_discount( $code ) ) {
$reason = __( 'This coupon has already been applied to the cart', 'graphql-for-ecommerce' );
2021-02-18 02:11:14 -05:00
return false;
}
return true;
}
/**
* Validates shipping method by checking comparing against shipping package.
*
* @param string $shipping_method Shipping method being validated.
* @param integer $index Index of the shipping package.
* @param string $reason Reason for failure.
*
* @return bool
*/
public static function validate_shipping_method( $shipping_method, $index, &$reason = '' ) {
// Get available shipping packages.
$available_packages = \WC()->cart->needs_shipping()
? \WC()->shipping()->calculate_shipping( \WC()->cart->get_shipping_packages() )
: [];
2021-02-18 02:11:14 -05:00
if ( ! isset( $available_packages[ $index ] ) ) {
$reason = sprintf(
/* translators: %d: Package index */
__( 'No shipping packages available for corresponding index %d', 'graphql-for-ecommerce' ),
2021-02-18 02:11:14 -05:00
$index
);
return false;
}
$package = $available_packages[ $index ];
$chosen_rate_index = array_search( $shipping_method, wp_list_pluck( $package['rates'], 'id' ), true );
if ( false !== $chosen_rate_index ) {
return true;
}
$product_names = [];
2021-02-18 02:11:14 -05:00
foreach ( $package['contents'] as $item_id => $values ) {
$product_names[ $item_id ] = \html_entity_decode( $values['data']->get_name() . ' &times;' . $values['quantity'] );
}
// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
$product_names = apply_filters( 'woocommerce_shipping_package_details_array', $product_names, $package );
$reason = sprintf(
/* translators: %1$s: shipping method ID, %2$s: package contents */
__( '"%1$s" is not an available shipping method for shipping package "%2$s"', 'graphql-for-ecommerce' ),
2021-02-18 02:11:14 -05:00
$shipping_method,
implode( ', ', $product_names )
);
return false;
}
/**
* Validates and prepares posted shipping methods for the user session.
*
* @param array $posted_shipping_methods Chosen shipping methods.
*
* @throws \GraphQL\Error\UserError Invalid shipping method.
2021-02-18 02:11:14 -05:00
*
2023-06-13 23:17:02 +03:00
* @return array<string,string>
2021-02-18 02:11:14 -05:00
*/
public static function prepare_shipping_methods( $posted_shipping_methods ) {
2023-06-13 23:17:02 +03:00
/**
* Get current shipping methods.
*
* @var array<string,string> $chosen_shipping_methods
*/
2021-02-18 02:11:14 -05:00
$chosen_shipping_methods = \WC()->session->get( 'chosen_shipping_methods' );
// Update current shipping methods.
foreach ( $posted_shipping_methods as $package => $chosen_method ) {
if ( empty( $chosen_method ) ) {
continue;
}
$reason = '';
if ( self::validate_shipping_method( $chosen_method, $package, $reason ) ) {
$chosen_shipping_methods[ $package ] = $chosen_method;
} else {
throw new UserError( $reason );
}
}
return $chosen_shipping_methods;
}
/**
* Validate CartItemQuantityInput item.
*
* @param array $item CartItemQuantityInput object.
*
* @return boolean
*/
public static function item_is_valid( array $item ) {
if ( empty( $item['key'] ) ) {
return false;
}
if ( ! isset( $item['quantity'] ) || ! is_numeric( $item['quantity'] ) ) {
return false;
}
return true;
}
/**
* Checks for errors thrown by the QL_Session_Handler during session token validation.
*
* @throws \GraphQL\Error\UserError If GRAPHQL_DEBUG is set to true and errors found.
2023-06-13 23:17:02 +03:00
*
* @return void
*/
public static function check_session_token() {
$token_invalid = apply_filters( 'graphql_woocommerce_session_token_errors', null );
2019-11-25 17:02:50 -05:00
if ( $token_invalid ) {
2019-11-25 20:01:35 -05:00
throw new UserError( $token_invalid );
}
\WC()->cart->get_cart_from_session();
}
2019-05-03 17:36:08 -04:00
}