UpdateProduct.php
73 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 | use Automattic\WooCommerce\Api\Attributes\ReturnType; |
| 11 | use Automattic\WooCommerce\Api\InputTypes\Products\UpdateProductInput; |
| 12 | use Automattic\WooCommerce\Api\Interfaces\Product; |
| 13 | use Automattic\WooCommerce\Api\Utils\Products\ProductMapper; |
| 14 | |
| 15 | /** |
| 16 | * Mutation to update an existing product. |
| 17 | */ |
| 18 | #[Description( 'Update an existing product.' )] |
| 19 | #[RequiredCapability( 'manage_woocommerce' )] |
| 20 | class UpdateProduct { |
| 21 | /** |
| 22 | * Execute the mutation. |
| 23 | * |
| 24 | * @param UpdateProductInput $input The fields to update. |
| 25 | * @return object |
| 26 | * @throws ApiException When the product is not found. |
| 27 | */ |
| 28 | #[ReturnType( Product::class )] |
| 29 | public function execute( |
| 30 | #[Description( 'The fields to update.' )] |
| 31 | UpdateProductInput $input, |
| 32 | ): object { |
| 33 | $wc_product = wc_get_product( $input->id ); |
| 34 | |
| 35 | if ( ! $wc_product instanceof \WC_Product ) { |
| 36 | throw new ApiException( 'Product not found.', 'NOT_FOUND', status_code: 404 ); |
| 37 | } |
| 38 | |
| 39 | foreach ( array( 'name', 'slug', 'sku', 'description', 'short_description', 'manage_stock', 'stock_quantity' ) as $field ) { |
| 40 | if ( $input->was_provided( $field ) ) { |
| 41 | $wc_product->{"set_{$field}"}( $input->$field ); |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | foreach ( array( 'regular_price', 'sale_price' ) as $field ) { |
| 46 | if ( $input->was_provided( $field ) ) { |
| 47 | $wc_product->{"set_{$field}"}( null !== $input->$field ? (string) $input->$field : '' ); |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | // Nullable enum: only invoke the setter when the client supplied a |
| 52 | // non-null value. An explicit null means "ignore this field" here — |
| 53 | // WC_Product's set_status doesn't accept null and would fall back |
| 54 | // to a default, silently overwriting whatever is already on the |
| 55 | // product. |
| 56 | if ( $input->was_provided( 'status' ) && null !== $input->status ) { |
| 57 | $wc_product->set_status( $input->status->value ); |
| 58 | } |
| 59 | |
| 60 | if ( $input->was_provided( 'dimensions' ) ) { |
| 61 | foreach ( array( 'length', 'width', 'height', 'weight' ) as $field ) { |
| 62 | if ( $input->dimensions->was_provided( $field ) ) { |
| 63 | $wc_product->{"set_{$field}"}( null !== $input->dimensions->$field ? (string) $input->dimensions->$field : '' ); |
| 64 | } |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | $wc_product->save(); |
| 69 | |
| 70 | return ProductMapper::from_wc_product( $wc_product ); |
| 71 | } |
| 72 | } |
| 73 |