| 1 |
<?php |
| 2 |
/** |
| 3 |
* Handle the settings API. |
| 4 |
* |
| 5 |
* @link https://bootstrapped.ventures |
| 6 |
* @since 1.0.0 |
| 7 |
* |
| 8 |
* @package BV_Settings |
| 9 |
* @author Brecht Vandersmissen <brecht@bootstrapped.ventures> |
| 10 |
*/ |
| 11 |
|
| 12 |
class BV_API { |
| 13 |
private $bvs; |
| 14 |
|
| 15 |
/** |
| 16 |
* Store main instance and initialize. |
| 17 |
* |
| 18 |
* @since 1.0.0 |
| 19 |
*/ |
| 20 |
public function __construct( $bvs ) { |
| 21 |
$this->bvs = $bvs; |
| 22 |
$this->init(); |
| 23 |
} |
| 24 |
|
| 25 |
/** |
| 26 |
* Register actions and filters. |
| 27 |
* |
| 28 |
* @since 1.0.0 |
| 29 |
*/ |
| 30 |
private function init() { |
| 31 |
add_action( 'rest_api_init', array( $this, 'api_register_data' ) ); |
| 32 |
} |
| 33 |
|
| 34 |
/** |
| 35 |
* Register data for the REST API. |
| 36 |
* |
| 37 |
* @since 1.0.0 |
| 38 |
*/ |
| 39 |
public function api_register_data() { |
| 40 |
if ( function_exists( 'register_rest_field' ) ) { // Prevent issue with Jetpack. |
| 41 |
register_rest_route( 'bv-settings/v1', '/' . $this->bvs->atts['uid'], array( |
| 42 |
'callback' => array( $this, 'api_get_settings' ), |
| 43 |
'methods' => 'GET', |
| 44 |
'permission_callback' => array( $this, 'api_required_permissions' ), |
| 45 |
)); |
| 46 |
register_rest_route( 'bv-settings/v1', '/' . $this->bvs->atts['uid'], array( |
| 47 |
'callback' => array( $this, 'api_update_settings' ), |
| 48 |
'methods' => 'POST', |
| 49 |
'permission_callback' => array( $this, 'api_required_permissions' ), |
| 50 |
)); |
| 51 |
} |
| 52 |
} |
| 53 |
|
| 54 |
/** |
| 55 |
* Required permissions for the API. |
| 56 |
* |
| 57 |
* @since 1.0.0 |
| 58 |
*/ |
| 59 |
public function api_required_permissions() { |
| 60 |
return current_user_can( $this->bvs->atts['required_capability'] ); |
| 61 |
} |
| 62 |
|
| 63 |
/** |
| 64 |
* Handle get settings call to the REST API. |
| 65 |
* |
| 66 |
* @since 1.0.0 |
| 67 |
* @param WP_REST_Request $request Current request. |
| 68 |
*/ |
| 69 |
public function api_get_settings( $request ) { |
| 70 |
return $this->bvs->get_settings_with_defaults(); |
| 71 |
} |
| 72 |
|
| 73 |
/** |
| 74 |
* Handle update settings call to the REST API. |
| 75 |
* |
| 76 |
* @since 1.0.0 |
| 77 |
* @param WP_REST_Request $request Current request. |
| 78 |
*/ |
| 79 |
public function api_update_settings( $request ) { |
| 80 |
$params = $request->get_params(); |
| 81 |
$settings = isset( $params['settings'] ) ? $params['settings'] : array(); |
| 82 |
return $this->bvs->update_settings( $settings ); |
| 83 |
} |
| 84 |
} |
| 85 |
|