DeleteProduct.php
58 lines
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace Automattic\WooCommerce\Api\Mutations\Products; |
| 6 | |
| 7 | use Automattic\WooCommerce\Api\ApiException; |
| 8 | use Automattic\WooCommerce\Api\Attributes\Description; |
| 9 | use Automattic\WooCommerce\Api\Attributes\RequiredCapability; |
| 10 | |
| 11 | /** |
| 12 | * Mutation to delete a product. |
| 13 | * |
| 14 | * Demonstrates: mutation returning bool. |
| 15 | */ |
| 16 | #[Description( 'Delete a product.' )] |
| 17 | #[RequiredCapability( 'manage_woocommerce' )] |
| 18 | class DeleteProduct { |
| 19 | /** |
| 20 | * Execute the mutation. |
| 21 | * |
| 22 | * @param int $id The product ID. |
| 23 | * @param bool $force Whether to permanently delete (bypass trash). |
| 24 | * @return bool Whether the product was deleted. |
| 25 | * @throws ApiException When the product is not found. |
| 26 | */ |
| 27 | public function execute( |
| 28 | #[Description( 'The ID of the product to delete.' )] |
| 29 | int $id, |
| 30 | #[Description( 'Whether to permanently delete the product (bypass trash).' )] |
| 31 | bool $force = false, |
| 32 | ): bool { |
| 33 | $wc_product = wc_get_product( $id ); |
| 34 | |
| 35 | if ( ! $wc_product instanceof \WC_Product ) { |
| 36 | throw new ApiException( 'Product not found.', 'NOT_FOUND', status_code: 404 ); |
| 37 | } |
| 38 | |
| 39 | // Capture the raw return value. A `(bool)` cast would coerce |
| 40 | // filter-originated `WP_Error` objects to `true`, reporting failure |
| 41 | // as success; we need to detect that case explicitly and surface |
| 42 | // the underlying error instead. |
| 43 | $deleted = $wc_product->delete( $force ); |
| 44 | |
| 45 | // phpcs:disable WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Not HTML; serialized as JSON. |
| 46 | if ( $deleted instanceof \WP_Error ) { |
| 47 | throw new ApiException( |
| 48 | $deleted->get_error_message(), |
| 49 | 'INTERNAL_ERROR', |
| 50 | status_code: 500, |
| 51 | ); |
| 52 | } |
| 53 | // phpcs:enable WordPress.Security.EscapeOutput.ExceptionNotEscaped |
| 54 | |
| 55 | return true === $deleted; |
| 56 | } |
| 57 | } |
| 58 |