CreateCoupon.php
50 lines
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace Automattic\WooCommerce\Api\Mutations\Coupons; |
| 6 | |
| 7 | use Automattic\WooCommerce\Api\Attributes\Description; |
| 8 | use Automattic\WooCommerce\Api\Attributes\RequiredCapability; |
| 9 | use Automattic\WooCommerce\Api\InputTypes\Coupons\CreateCouponInput; |
| 10 | use Automattic\WooCommerce\Api\Utils\Coupons\CouponMapper; |
| 11 | use Automattic\WooCommerce\Api\Types\Coupons\Coupon; |
| 12 | |
| 13 | /** |
| 14 | * Mutation to create a new coupon. |
| 15 | */ |
| 16 | #[Description( 'Create a new coupon.' )] |
| 17 | #[RequiredCapability( 'manage_woocommerce' )] |
| 18 | class CreateCoupon { |
| 19 | /** |
| 20 | * Execute the mutation. |
| 21 | * |
| 22 | * @param CreateCouponInput $input The coupon creation data. |
| 23 | * @return Coupon |
| 24 | */ |
| 25 | public function execute( |
| 26 | #[Description( 'Data for the new coupon.' )] |
| 27 | CreateCouponInput $input, |
| 28 | ): Coupon { |
| 29 | $wc_coupon = new \WC_Coupon(); |
| 30 | $wc_coupon->set_code( $input->code ); |
| 31 | |
| 32 | foreach ( array( '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 ) { |
| 33 | if ( null !== $input->$field ) { |
| 34 | $wc_coupon->{"set_{$field}"}( $input->$field ); |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | if ( null !== $input->discount_type ) { |
| 39 | $wc_coupon->set_discount_type( $input->discount_type->value ); |
| 40 | } |
| 41 | if ( null !== $input->status ) { |
| 42 | $wc_coupon->set_status( $input->status->value ); |
| 43 | } |
| 44 | |
| 45 | $wc_coupon->save(); |
| 46 | |
| 47 | return CouponMapper::from_wc_coupon( $wc_coupon ); |
| 48 | } |
| 49 | } |
| 50 |