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