| 1 |
<?php |
| 2 |
|
| 3 |
namespace WPConsole\Core\UserSettings; |
| 4 |
|
| 5 |
use Exception; |
| 6 |
use WPConsole\Traits\RESTResponseError; |
| 7 |
use WP_REST_Controller; |
| 8 |
use WP_REST_Server; |
| 9 |
|
| 10 |
class RestController extends WP_REST_Controller { |
| 11 |
|
| 12 |
use RESTResponseError; |
| 13 |
|
| 14 |
/** |
| 15 |
* Endpoint namespace |
| 16 |
* |
| 17 |
* @since 2.0.0 |
| 18 |
* |
| 19 |
* @var string |
| 20 |
*/ |
| 21 |
protected $namespace = 'wp-console/v1'; |
| 22 |
|
| 23 |
/** |
| 24 |
* Route name |
| 25 |
* |
| 26 |
* @since 2.0.0 |
| 27 |
* |
| 28 |
* @var string |
| 29 |
*/ |
| 30 |
protected $base = 'user-settings'; |
| 31 |
|
| 32 |
/** |
| 33 |
* Class constructor |
| 34 |
* |
| 35 |
* @since 2.0.0 |
| 36 |
* |
| 37 |
* @return void |
| 38 |
*/ |
| 39 |
public function __construct() { |
| 40 |
$this->register_routes(); |
| 41 |
} |
| 42 |
|
| 43 |
/** |
| 44 |
* Register REST routes |
| 45 |
* |
| 46 |
* @since 2.0.0 |
| 47 |
* |
| 48 |
* @return void |
| 49 |
*/ |
| 50 |
public function register_routes() { |
| 51 |
register_rest_route( $this->namespace, '/' . $this->base, [ |
| 52 |
[ |
| 53 |
'methods' => WP_REST_Server::EDITABLE, |
| 54 |
'callback' => [ $this, 'update_item' ], |
| 55 |
'permission_callback' => [ $this, 'can_manage_options' ], |
| 56 |
'args' => $this->get_endpoint_args_for_item_schema( WP_REST_Server::CREATABLE ), |
| 57 |
], |
| 58 |
|
| 59 |
'schema' => [ $this, 'get_public_item_schema' ], |
| 60 |
] ); |
| 61 |
} |
| 62 |
|
| 63 |
/** |
| 64 |
* Check if current user has manage_options capability |
| 65 |
* |
| 66 |
* @since 2.0.0 |
| 67 |
* |
| 68 |
* @return bool |
| 69 |
*/ |
| 70 |
public function can_manage_options() { |
| 71 |
return current_user_can( 'manage_options' ); |
| 72 |
} |
| 73 |
|
| 74 |
/** |
| 75 |
* Update user settings |
| 76 |
* |
| 77 |
* @since 2.0.0 |
| 78 |
* |
| 79 |
* @param \WP_REST_Request $request |
| 80 |
* |
| 81 |
* @return \WP_REST_Response|\WP_Error |
| 82 |
*/ |
| 83 |
public function update_item( $request ) { |
| 84 |
try { |
| 85 |
$user_id = get_current_user_id(); |
| 86 |
$settings = wp_console()->user_settings->save( $user_id, $request->get_params() ); |
| 87 |
|
| 88 |
return rest_ensure_response( $settings ); |
| 89 |
|
| 90 |
} catch ( Exception $e ) { |
| 91 |
return $this->send_response_error( $e ); |
| 92 |
} |
| 93 |
} |
| 94 |
|
| 95 |
/** |
| 96 |
* Endpoint schema |
| 97 |
* |
| 98 |
* @since 2.0.0 |
| 99 |
* |
| 100 |
* @return array |
| 101 |
*/ |
| 102 |
public function get_item_schema() { |
| 103 |
$schema = [ |
| 104 |
'$schema' => 'http://json-schema.org/draft-04/schema#', |
| 105 |
'title' => 'wp-console-user-settings', |
| 106 |
'type' => 'object', |
| 107 |
'properties' => wp_console()->user_settings->get_settings_schema(), |
| 108 |
]; |
| 109 |
|
| 110 |
return $schema; |
| 111 |
} |
| 112 |
} |
| 113 |
|