DeleteCoupon.php
61 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\Types\Coupons\DeleteCouponResult; |
| 11 | |
| 12 | /** |
| 13 | * Mutation to delete a coupon. |
| 14 | */ |
| 15 | #[Description( 'Delete a coupon.' )] |
| 16 | #[RequiredCapability( 'manage_woocommerce' )] |
| 17 | class DeleteCoupon { |
| 18 | /** |
| 19 | * Execute the mutation. |
| 20 | * |
| 21 | * @param int $id The coupon ID. |
| 22 | * @param bool $force Whether to permanently delete. |
| 23 | * @return DeleteCouponResult |
| 24 | * @throws ApiException When the coupon is not found. |
| 25 | */ |
| 26 | public function execute( |
| 27 | #[Description( 'The ID of the coupon to delete.' )] |
| 28 | int $id, |
| 29 | #[Description( 'Whether to permanently delete the coupon (bypass trash).' )] |
| 30 | bool $force = false, |
| 31 | ): DeleteCouponResult { |
| 32 | $wc_coupon = new \WC_Coupon( $id ); |
| 33 | |
| 34 | if ( ! $wc_coupon->get_id() ) { |
| 35 | throw new ApiException( 'Coupon not found.', 'NOT_FOUND', status_code: 404 ); |
| 36 | } |
| 37 | |
| 38 | // Capture the raw return value. A `(bool)` cast would coerce |
| 39 | // filter-originated `WP_Error` objects to `true`, reporting failure |
| 40 | // as success; we need to detect that case explicitly and surface |
| 41 | // the underlying error instead. |
| 42 | $deleted = $wc_coupon->delete( $force ); |
| 43 | |
| 44 | // phpcs:disable WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Not HTML; serialized as JSON. |
| 45 | if ( $deleted instanceof \WP_Error ) { |
| 46 | throw new ApiException( |
| 47 | $deleted->get_error_message(), |
| 48 | 'INTERNAL_ERROR', |
| 49 | status_code: 500, |
| 50 | ); |
| 51 | } |
| 52 | // phpcs:enable WordPress.Security.EscapeOutput.ExceptionNotEscaped |
| 53 | |
| 54 | $result = new DeleteCouponResult(); |
| 55 | $result->id = $id; |
| 56 | $result->deleted = true === $deleted; |
| 57 | |
| 58 | return $result; |
| 59 | } |
| 60 | } |
| 61 |