UpdateCoupon.php
60 lines
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace Automattic\WooCommerce\Api\Mutations\Coupons; |
| 6 | |
| 7 | use Automattic\WooCommerce\Api\ApiException; |
| 8 | use Automattic\WooCommerce\Api\Attributes\Description; |
| 9 | use Automattic\WooCommerce\Api\Attributes\RequiredCapability; |
| 10 | use Automattic\WooCommerce\Api\InputTypes\Coupons\UpdateCouponInput; |
| 11 | use Automattic\WooCommerce\Api\Utils\Coupons\CouponMapper; |
| 12 | use Automattic\WooCommerce\Api\Types\Coupons\Coupon; |
| 13 | |
| 14 | /** |
| 15 | * Mutation to update an existing coupon. |
| 16 | */ |
| 17 | #[Description( 'Update an existing coupon.' )] |
| 18 | #[RequiredCapability( 'manage_woocommerce' )] |
| 19 | class UpdateCoupon { |
| 20 | /** |
| 21 | * Execute the mutation. |
| 22 | * |
| 23 | * @param UpdateCouponInput $input The fields to update. |
| 24 | * @return Coupon |
| 25 | * @throws ApiException When the coupon is not found. |
| 26 | */ |
| 27 | public function execute( |
| 28 | #[Description( 'The fields to update.' )] |
| 29 | UpdateCouponInput $input, |
| 30 | ): Coupon { |
| 31 | $wc_coupon = new \WC_Coupon( $input->id ); |
| 32 | |
| 33 | if ( ! $wc_coupon->get_id() ) { |
| 34 | throw new ApiException( 'Coupon not found.', 'NOT_FOUND', status_code: 404 ); |
| 35 | } |
| 36 | |
| 37 | foreach ( array( 'code', 'description', 'amount', 'date_expires', 'individual_use', 'product_ids', 'excluded_product_ids', 'usage_limit', 'usage_limit_per_user', 'limit_usage_to_x_items', 'free_shipping', 'product_categories', 'excluded_product_categories', 'exclude_sale_items', 'minimum_amount', 'maximum_amount', 'email_restrictions' ) as $field ) { |
| 38 | if ( $input->was_provided( $field ) ) { |
| 39 | $wc_coupon->{"set_{$field}"}( $input->$field ); |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | // Nullable enums: only invoke the setter when the client supplied a |
| 44 | // non-null value. An explicit null means "ignore this field" here — |
| 45 | // WC_Coupon's enum setters don't accept null and would fall back to |
| 46 | // their defaults (e.g. 'fixed_cart' for discount_type), silently |
| 47 | // overwriting whatever is already on the coupon. |
| 48 | if ( $input->was_provided( 'discount_type' ) && null !== $input->discount_type ) { |
| 49 | $wc_coupon->set_discount_type( $input->discount_type->value ); |
| 50 | } |
| 51 | if ( $input->was_provided( 'status' ) && null !== $input->status ) { |
| 52 | $wc_coupon->set_status( $input->status->value ); |
| 53 | } |
| 54 | |
| 55 | $wc_coupon->save(); |
| 56 | |
| 57 | return CouponMapper::from_wc_coupon( $wc_coupon ); |
| 58 | } |
| 59 | } |
| 60 |