GetCoupon.php
47 lines
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace Automattic\WooCommerce\Api\Queries\Coupons; |
| 6 | |
| 7 | use Automattic\WooCommerce\Api\Attributes\Description; |
| 8 | use Automattic\WooCommerce\Api\Attributes\Name; |
| 9 | use Automattic\WooCommerce\Api\Attributes\RequiredCapability; |
| 10 | use Automattic\WooCommerce\Api\Types\Coupons\Coupon; |
| 11 | use Automattic\WooCommerce\Api\Utils\Coupons\CouponMapper; |
| 12 | |
| 13 | #[Name( 'coupon' )] |
| 14 | #[Description( 'Retrieve a single coupon by ID or code. Exactly one of the two arguments must be provided.' )] |
| 15 | /** |
| 16 | * Query to retrieve a single coupon. |
| 17 | */ |
| 18 | #[RequiredCapability( 'read_private_shop_coupons' )] |
| 19 | class GetCoupon { |
| 20 | /** |
| 21 | * Retrieve a coupon by ID or code. |
| 22 | * |
| 23 | * @param ?int $id The coupon ID. |
| 24 | * @param ?string $code The coupon code. |
| 25 | * @return ?Coupon |
| 26 | * @throws \InvalidArgumentException When neither or both arguments are provided. |
| 27 | */ |
| 28 | public function execute( |
| 29 | #[Description( 'The ID of the coupon to retrieve.' )] |
| 30 | ?int $id = null, |
| 31 | #[Description( 'The coupon code to look up.' )] |
| 32 | ?string $code = null, |
| 33 | ): ?Coupon { |
| 34 | if ( ( null === $id ) === ( null === $code ) ) { |
| 35 | throw new \InvalidArgumentException( 'Exactly one of "id" or "code" must be provided.' ); |
| 36 | } |
| 37 | |
| 38 | $wc_coupon = new \WC_Coupon( $id ?? $code ); |
| 39 | |
| 40 | if ( ! $wc_coupon->get_id() ) { |
| 41 | return null; |
| 42 | } |
| 43 | |
| 44 | return CouponMapper::from_wc_coupon( $wc_coupon ); |
| 45 | } |
| 46 | } |
| 47 |