| 1 |
<?php namespace TierPricingTable\Addons\TaxSettings\API; |
| 2 |
|
| 3 |
class TaxSettingsEndpoints { |
| 4 |
|
| 5 |
const OPTION_KEY = '_tpt_role_tax_settings'; |
| 6 |
|
| 7 |
public function __construct() { |
| 8 |
add_action( 'rest_api_init', array( $this, 'registerEndpoints' ) ); |
| 9 |
} |
| 10 |
|
| 11 |
public function registerEndpoints() { |
| 12 |
register_rest_route( 'tier-pricing-table/v1', '/tax-settings', array( |
| 13 |
'methods' => \WP_REST_Server::READABLE, |
| 14 |
'callback' => array( $this, 'getSettings' ), |
| 15 |
'permission_callback' => array( $this, 'checkPermission' ), |
| 16 |
) ); |
| 17 |
|
| 18 |
register_rest_route( 'tier-pricing-table/v1', '/tax-settings', array( |
| 19 |
'methods' => \WP_REST_Server::EDITABLE, |
| 20 |
'callback' => array( $this, 'updateSettings' ), |
| 21 |
'permission_callback' => array( $this, 'checkPermission' ), |
| 22 |
) ); |
| 23 |
} |
| 24 |
|
| 25 |
public function getSettings( \WP_REST_Request $request ) { |
| 26 |
$settings = get_option( self::OPTION_KEY, array() ); |
| 27 |
|
| 28 |
return rest_ensure_response( $settings ); |
| 29 |
} |
| 30 |
|
| 31 |
public function updateSettings( \WP_REST_Request $request ) { |
| 32 |
$params = $request->get_json_params(); |
| 33 |
|
| 34 |
// Sanitize input |
| 35 |
$sanitized_settings = array(); |
| 36 |
|
| 37 |
if ( is_array( $params ) ) { |
| 38 |
foreach ( $params as $role => $data ) { |
| 39 |
if ( is_array( $data ) ) { |
| 40 |
$sanitized_settings[ sanitize_key( $role ) ] = array( |
| 41 |
'tax_exempt' => isset( $data['tax_exempt'] ) ? (bool) $data['tax_exempt'] : false, |
| 42 |
'tax_class' => isset( $data['tax_class'] ) ? sanitize_text_field( $data['tax_class'] ) : 'default', |
| 43 |
'display_shop' => isset( $data['display_shop'] ) ? sanitize_text_field( $data['display_shop'] ) : 'default', |
| 44 |
'display_cart' => isset( $data['display_cart'] ) ? sanitize_text_field( $data['display_cart'] ) : 'default', |
| 45 |
'prices_include_tax' => isset( $data['prices_include_tax'] ) ? sanitize_text_field( $data['prices_include_tax'] ) : 'default', |
| 46 |
'price_suffix' => isset( $data['price_suffix'] ) ? sanitize_text_field( $data['price_suffix'] ) : '', |
| 47 |
); |
| 48 |
} |
| 49 |
} |
| 50 |
} |
| 51 |
|
| 52 |
update_option( self::OPTION_KEY, $sanitized_settings ); |
| 53 |
|
| 54 |
return rest_ensure_response( $sanitized_settings ); |
| 55 |
} |
| 56 |
|
| 57 |
public function checkPermission() { |
| 58 |
return current_user_can( 'manage_woocommerce' ); |
| 59 |
} |
| 60 |
} |
| 61 |
|