class-wc-product-usage.php
93 lines
| 1 | <?php |
| 2 | /** |
| 3 | * WooCommerce Product Usage. |
| 4 | * |
| 5 | * This class defines method to be used by Woo extensions to control product usage based on subscription status. |
| 6 | * |
| 7 | * @package WooCommerce\ProductUsage |
| 8 | */ |
| 9 | |
| 10 | declare( strict_types = 1 ); |
| 11 | |
| 12 | |
| 13 | if ( ! defined( 'ABSPATH' ) ) { |
| 14 | exit; |
| 15 | } |
| 16 | |
| 17 | /** |
| 18 | * Product usagee |
| 19 | */ |
| 20 | class WC_Product_Usage { |
| 21 | /** |
| 22 | * Load Product Usage class. |
| 23 | * |
| 24 | * @since 9.3.0 |
| 25 | */ |
| 26 | public static function load() { |
| 27 | self::includes(); |
| 28 | } |
| 29 | |
| 30 | /** |
| 31 | * Include support files. |
| 32 | * |
| 33 | * @since 9.3.0 |
| 34 | */ |
| 35 | protected static function includes() { |
| 36 | require_once WC_ABSPATH . 'includes/product-usage/class-wc-product-usage-rule-set.php'; |
| 37 | } |
| 38 | |
| 39 | /** |
| 40 | * Get product usage rule if it needs to be applied to the given product id. |
| 41 | * |
| 42 | * @param int $product_id product id to get feature restriction rules. |
| 43 | * @since 9.3.0 |
| 44 | */ |
| 45 | public static function get_rules_for_product( int $product_id ): ?WC_Product_Usage_Rule_Set { |
| 46 | $rules = self::get_product_usage_restriction_rule( $product_id ); |
| 47 | if ( null === $rules ) { |
| 48 | return null; |
| 49 | } |
| 50 | |
| 51 | // When there is no subscription for the product, restrict usage. |
| 52 | if ( ! WC_Helper::has_product_subscription( $product_id ) ) { |
| 53 | return new WC_Product_Usage_Rule_Set( $rules ); |
| 54 | } |
| 55 | |
| 56 | $subscriptions = wp_list_filter( WC_Helper::get_installed_subscriptions(), array( 'product_id' => $product_id ) ); |
| 57 | if ( empty( $subscriptions ) ) { |
| 58 | return new WC_Product_Usage_Rule_Set( $rules ); |
| 59 | } |
| 60 | |
| 61 | // Product should only have a single connected subscription on current store. |
| 62 | $product_subscription = current( $subscriptions ); |
| 63 | if ( $product_subscription['expired'] ) { |
| 64 | return new WC_Product_Usage_Rule_Set( $rules ); |
| 65 | } |
| 66 | |
| 67 | return null; |
| 68 | } |
| 69 | |
| 70 | /** |
| 71 | * Get the product usage rule for a product. |
| 72 | * |
| 73 | * @param int $product_id product id to get feature restriction rules. |
| 74 | * @return array|null |
| 75 | * @since 9.3.0 |
| 76 | */ |
| 77 | private static function get_product_usage_restriction_rule( int $product_id ): ?array { |
| 78 | try { |
| 79 | $rules = WC_Helper::get_product_usage_notice_rules(); |
| 80 | } catch ( Exception $e ) { |
| 81 | return null; |
| 82 | } |
| 83 | |
| 84 | if ( empty( $rules['restricted_products'][ $product_id ] ) ) { |
| 85 | return null; |
| 86 | } |
| 87 | |
| 88 | return $rules['restricted_products'][ $product_id ]; |
| 89 | } |
| 90 | } |
| 91 | |
| 92 | WC_Product_Usage::load(); |
| 93 |