| 1 |
<?php |
| 2 |
|
| 3 |
namespace TierPricingTable\Services\API; |
| 4 |
|
| 5 |
use TierPricingTable\Addons\RoleBasedPricing\RoleBasedPriceManager; |
| 6 |
use TierPricingTable\Addons\RoleBasedPricing\RoleBasedPricingRule; |
| 7 |
use TierPricingTable\PriceManager; |
| 8 |
use WC_Product; |
| 9 |
class WooCommerceRESTAPIService { |
| 10 |
public function __construct() { |
| 11 |
add_action( 'rest_api_init', function () { |
| 12 |
$supportedAPIProductTypes = apply_filters( 'tiered_pricing_table/api/supported_product_types', array('product', 'product_variation') ); |
| 13 |
foreach ( $supportedAPIProductTypes as $productType ) { |
| 14 |
register_rest_field( $productType, 'tiered_pricing_type', array( |
| 15 |
'get_callback' => function ( $product ) { |
| 16 |
return PriceManager::getPricingType( $product['id'] ); |
| 17 |
}, |
| 18 |
'update_callback' => function ( $value, WC_Product $object ) { |
| 19 |
if ( in_array( $value, array('fixed', 'percentage') ) ) { |
| 20 |
PriceManager::updatePriceRulesType( $object->get_id(), $value ); |
| 21 |
} |
| 22 |
}, |
| 23 |
'schema' => array( |
| 24 |
'description' => __( 'Tiered Pricing type. can be either "percentage" or "fixed"', 'tier-pricing-table' ), |
| 25 |
'type' => 'string', |
| 26 |
'context' => array('view', 'edit'), |
| 27 |
), |
| 28 |
) ); |
| 29 |
register_rest_field( $productType, 'tiered_pricing_fixed_rules', array( |
| 30 |
'get_callback' => function ( $product ) { |
| 31 |
return PriceManager::getFixedPriceRules( $product['id'], 'edit' ); |
| 32 |
}, |
| 33 |
'update_callback' => function ( $value, WC_Product $object ) { |
| 34 |
update_post_meta( $object->get_id(), '_fixed_price_rules', $value ); |
| 35 |
}, |
| 36 |
'schema' => array( |
| 37 |
'description' => __( 'Tiered Pricing fixed rules. The format is the following: "quantity:price". For example, "10:20,5:40" means 10$ per piece if users buy 20pcs and 5$ per piece if users buy 40pcs', 'tier-pricing-table' ), |
| 38 |
'type' => 'object', |
| 39 |
'context' => array('view', 'edit'), |
| 40 |
), |
| 41 |
) ); |
| 42 |
} |
| 43 |
} ); |
| 44 |
} |
| 45 |
|
| 46 |
protected function decodeRules( $data ) : array { |
| 47 |
$rules = ( is_array( $data ) ? $data : explode( ',', $data ) ); |
| 48 |
$data = array(); |
| 49 |
if ( $rules ) { |
| 50 |
foreach ( $rules as $rule ) { |
| 51 |
$rule = explode( ':', $rule ); |
| 52 |
if ( isset( $rule[0] ) && isset( $rule[1] ) ) { |
| 53 |
$data[intval( $rule[0] )] = $rule[1]; |
| 54 |
} |
| 55 |
} |
| 56 |
} |
| 57 |
$data = array_filter( $data ); |
| 58 |
return ( !empty( $data ) ? $data : array() ); |
| 59 |
} |
| 60 |
|
| 61 |
} |
| 62 |
|