woocommerce
/
packages
/
email-editor
/
src
/
Integrations
/
WooCommerce
/
class-coupon-code-generator.php
Renderer
1 month ago
class-coupon-code-generator.php
2 months ago
class-initializer.php
2 months ago
class-coupon-code-generator.php
214 lines
| 1 | <?php |
| 2 | /** |
| 3 | * This file is part of the WooCommerce Email Editor package. |
| 4 | * |
| 5 | * @package Automattic\WooCommerce\EmailEditor |
| 6 | */ |
| 7 | |
| 8 | declare( strict_types = 1 ); |
| 9 | namespace Automattic\WooCommerce\EmailEditor\Integrations\WooCommerce; |
| 10 | |
| 11 | use Automattic\WooCommerce\EmailEditor\Engine\Renderer\ContentRenderer\Rendering_Context; |
| 12 | use Automattic\WooCommerce\EmailEditor\Integrations\WooCommerce\Renderer\Blocks\Coupon_Code; |
| 13 | |
| 14 | /** |
| 15 | * Generates WooCommerce coupons at email send time for the coupon-code block. |
| 16 | * |
| 17 | * Hooks into the woocommerce_coupon_code_block_auto_generate filter to create |
| 18 | * a WC_Coupon from block attributes. This provides baseline auto-generation |
| 19 | * that works without any additional plugins (e.g. MailPoet). |
| 20 | * |
| 21 | * Integrators like MailPoet can hook the same filter at a higher priority |
| 22 | * to add features like per-subscriber restriction or coupon persistence. |
| 23 | */ |
| 24 | class Coupon_Code_Generator { |
| 25 | |
| 26 | /** |
| 27 | * Maximum number of retries for generating a unique coupon code. |
| 28 | */ |
| 29 | const MAX_CODE_RETRIES = 5; |
| 30 | |
| 31 | /** |
| 32 | * Initialize the generator by registering the filter hook. |
| 33 | */ |
| 34 | public function init(): void { |
| 35 | add_filter( 'woocommerce_coupon_code_block_auto_generate', array( $this, 'generate_coupon' ), 10, 3 ); |
| 36 | } |
| 37 | |
| 38 | /** |
| 39 | * Generate a WooCommerce coupon from block attributes. |
| 40 | * |
| 41 | * @param string $coupon_code The coupon code (empty if not yet generated). |
| 42 | * @param array $attrs Block attributes. |
| 43 | * @param Rendering_Context $rendering_context The rendering context. |
| 44 | * @return string The generated coupon code, or empty string on failure. |
| 45 | */ |
| 46 | public function generate_coupon( string $coupon_code, array $attrs, Rendering_Context $rendering_context ): string { |
| 47 | if ( ! empty( $coupon_code ) ) { |
| 48 | return $coupon_code; |
| 49 | } |
| 50 | |
| 51 | if ( $rendering_context->get( 'is_user_preview' ) ) { |
| 52 | return Coupon_Code::COUPON_CODE_PLACEHOLDER; |
| 53 | } |
| 54 | |
| 55 | if ( ! function_exists( 'wc_get_coupon_types' ) || ! class_exists( 'WC_Coupon' ) ) { |
| 56 | return ''; |
| 57 | } |
| 58 | |
| 59 | try { |
| 60 | $coupon = new \WC_Coupon(); |
| 61 | $coupon->set_code( $this->generate_unique_code() ); |
| 62 | |
| 63 | $discount_type = $this->validate_discount_type( $attrs['discountType'] ?? 'percent' ); |
| 64 | $coupon->set_discount_type( $discount_type ); |
| 65 | |
| 66 | if ( isset( $attrs['amount'] ) ) { |
| 67 | $coupon->set_amount( (float) $attrs['amount'] ); |
| 68 | } |
| 69 | |
| 70 | if ( ! empty( $attrs['expiryDay'] ) ) { |
| 71 | $expiration = time() + ( (int) $attrs['expiryDay'] * DAY_IN_SECONDS ); |
| 72 | $coupon->set_date_expires( $expiration ); |
| 73 | } |
| 74 | |
| 75 | $coupon->set_free_shipping( ! empty( $attrs['freeShipping'] ) ); |
| 76 | |
| 77 | $coupon->set_minimum_amount( (float) ( $attrs['minimumAmount'] ?? 0 ) ); |
| 78 | $coupon->set_maximum_amount( (float) ( $attrs['maximumAmount'] ?? 0 ) ); |
| 79 | $coupon->set_individual_use( ! empty( $attrs['individualUse'] ) ); |
| 80 | $coupon->set_exclude_sale_items( ! empty( $attrs['excludeSaleItems'] ) ); |
| 81 | |
| 82 | $coupon->set_product_ids( $this->extract_ids( $attrs['productIds'] ?? array() ) ); |
| 83 | $coupon->set_excluded_product_ids( $this->extract_ids( $attrs['excludedProductIds'] ?? array() ) ); |
| 84 | $coupon->set_product_categories( $this->extract_ids( $attrs['productCategoryIds'] ?? array() ) ); |
| 85 | $coupon->set_excluded_product_categories( $this->extract_ids( $attrs['excludedProductCategoryIds'] ?? array() ) ); |
| 86 | |
| 87 | $email_restrictions = $this->parse_email_restrictions( $attrs['emailRestrictions'] ?? '' ); |
| 88 | |
| 89 | $recipient = $rendering_context->get_recipient_email(); |
| 90 | if ( $recipient && is_email( $recipient ) ) { |
| 91 | $email_restrictions[] = $recipient; |
| 92 | } |
| 93 | |
| 94 | $coupon->set_email_restrictions( array_unique( $email_restrictions ) ); |
| 95 | |
| 96 | $usage_limit = $attrs['usageLimit'] ?? 0; |
| 97 | $usage_limit_per_user = $attrs['usageLimitPerUser'] ?? 0; |
| 98 | $coupon->set_usage_limit( is_numeric( $usage_limit ) ? (int) $usage_limit : 0 ); |
| 99 | $coupon->set_usage_limit_per_user( is_numeric( $usage_limit_per_user ) ? (int) $usage_limit_per_user : 0 ); |
| 100 | |
| 101 | $coupon->set_description( |
| 102 | __( 'Auto-generated coupon by WooCommerce Email Editor', 'woocommerce' ) |
| 103 | ); |
| 104 | |
| 105 | $coupon->save(); |
| 106 | |
| 107 | return $coupon->get_code(); |
| 108 | } catch ( \Exception $e ) { |
| 109 | wc_get_logger()->error( |
| 110 | 'Coupon auto-generation failed: ' . $e->getMessage(), |
| 111 | array( 'source' => 'email-editor-coupon-generator' ) |
| 112 | ); |
| 113 | return ''; |
| 114 | } |
| 115 | } |
| 116 | |
| 117 | /** |
| 118 | * Parse and validate email restrictions string. |
| 119 | * |
| 120 | * @param mixed $raw Raw email restrictions value (comma-separated string). |
| 121 | * @return array Array of valid email addresses. |
| 122 | */ |
| 123 | private function parse_email_restrictions( $raw ): array { |
| 124 | if ( ! is_string( $raw ) || '' === $raw ) { |
| 125 | return array(); |
| 126 | } |
| 127 | |
| 128 | $emails = array_map( 'trim', explode( ',', $raw ) ); |
| 129 | |
| 130 | return array_values( |
| 131 | array_filter( |
| 132 | $emails, |
| 133 | function ( string $email ): bool { |
| 134 | return (bool) is_email( $email ); |
| 135 | } |
| 136 | ) |
| 137 | ); |
| 138 | } |
| 139 | |
| 140 | /** |
| 141 | * Validate discount type against WooCommerce's registered types. |
| 142 | * |
| 143 | * @param string $type The discount type to validate. |
| 144 | * @return string A valid discount type. |
| 145 | */ |
| 146 | private function validate_discount_type( string $type ): string { |
| 147 | $valid_types = array_keys( wc_get_coupon_types() ); |
| 148 | return in_array( $type, $valid_types, true ) ? $type : 'percent'; |
| 149 | } |
| 150 | |
| 151 | /** |
| 152 | * Generate a unique random coupon code, retrying on collision. |
| 153 | * |
| 154 | * @return string A unique coupon code. |
| 155 | * @throws \RuntimeException When a unique code cannot be generated after max retries. |
| 156 | */ |
| 157 | private function generate_unique_code(): string { |
| 158 | for ( $i = 0; $i < self::MAX_CODE_RETRIES; $i++ ) { |
| 159 | $code = $this->generate_random_code(); |
| 160 | $existing = wc_get_coupon_id_by_code( $code ); |
| 161 | if ( ! $existing ) { |
| 162 | return $code; |
| 163 | } |
| 164 | } |
| 165 | // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- exception message, not rendered output. |
| 166 | throw new \RuntimeException( 'Failed to generate a unique coupon code.' ); |
| 167 | } |
| 168 | |
| 169 | /** |
| 170 | * Generate a random coupon code in XXXX-XXXXXX-XXXX format. |
| 171 | * |
| 172 | * @return string |
| 173 | */ |
| 174 | private function generate_random_code(): string { |
| 175 | $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; |
| 176 | $length = strlen( $characters ) - 1; |
| 177 | |
| 178 | $segment1 = ''; |
| 179 | $segment2 = ''; |
| 180 | $segment3 = ''; |
| 181 | |
| 182 | for ( $i = 0; $i < 4; $i++ ) { |
| 183 | $segment1 .= $characters[ random_int( 0, $length ) ]; |
| 184 | } |
| 185 | for ( $i = 0; $i < 6; $i++ ) { |
| 186 | $segment2 .= $characters[ random_int( 0, $length ) ]; |
| 187 | } |
| 188 | for ( $i = 0; $i < 4; $i++ ) { |
| 189 | $segment3 .= $characters[ random_int( 0, $length ) ]; |
| 190 | } |
| 191 | |
| 192 | return $segment1 . '-' . $segment2 . '-' . $segment3; |
| 193 | } |
| 194 | |
| 195 | /** |
| 196 | * Extract integer IDs from an array of {id, title} objects. |
| 197 | * |
| 198 | * @param array $items Array of items with 'id' key. |
| 199 | * @return array Array of integer IDs. |
| 200 | */ |
| 201 | private function extract_ids( array $items ): array { |
| 202 | return array_map( |
| 203 | function ( $item ): int { |
| 204 | if ( ! is_array( $item ) ) { |
| 205 | return 0; |
| 206 | } |
| 207 | $id = $item['id'] ?? 0; |
| 208 | return is_numeric( $id ) ? (int) $id : 0; |
| 209 | }, |
| 210 | $items |
| 211 | ); |
| 212 | } |
| 213 | } |
| 214 |