88 lines
2.0 KiB
PHP
88 lines
2.0 KiB
PHP
<?php
|
|
/**
|
|
* REST settings controller.
|
|
*
|
|
* @package LogoSoup
|
|
*/
|
|
|
|
namespace LogoSoup\REST;
|
|
|
|
use LogoSoup\Settings;
|
|
use WP_Error;
|
|
use WP_REST_Request;
|
|
use WP_REST_Response;
|
|
use WP_REST_Server;
|
|
|
|
/**
|
|
* REST API for plugin settings.
|
|
*/
|
|
class Settings_Controller {
|
|
/**
|
|
* Register routes.
|
|
*
|
|
* @return void
|
|
*/
|
|
public static function register_routes() {
|
|
register_rest_route(
|
|
'logo-soup/v1',
|
|
'/settings',
|
|
array(
|
|
array(
|
|
'methods' => WP_REST_Server::READABLE,
|
|
'callback' => array( __CLASS__, 'get_item' ),
|
|
'permission_callback' => array( __CLASS__, 'permissions_check' ),
|
|
),
|
|
array(
|
|
'methods' => WP_REST_Server::EDITABLE,
|
|
'callback' => array( __CLASS__, 'update_item' ),
|
|
'permission_callback' => array( __CLASS__, 'permissions_check' ),
|
|
),
|
|
)
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Check permissions.
|
|
*
|
|
* @param WP_REST_Request $request Request object.
|
|
* @return true|WP_Error
|
|
*/
|
|
public static function permissions_check( WP_REST_Request $request ) {
|
|
if ( ! current_user_can( 'manage_options' ) ) {
|
|
return new WP_Error( 'logo_soup_forbidden', __( 'You are not allowed to manage Logo Soup settings.', 'logo-soup' ), array( 'status' => 403 ) );
|
|
}
|
|
|
|
if ( 'GET' !== $request->get_method() ) {
|
|
$nonce = $request->get_header( 'X-WP-Nonce' );
|
|
|
|
if ( ! wp_verify_nonce( $nonce, 'wp_rest' ) ) {
|
|
return new WP_Error( 'logo_soup_bad_nonce', __( 'Invalid REST nonce.', 'logo-soup' ), array( 'status' => 403 ) );
|
|
}
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
/**
|
|
* Get settings.
|
|
*
|
|
* @return WP_REST_Response
|
|
*/
|
|
public static function get_item() {
|
|
return new WP_REST_Response( Settings::get(), 200 );
|
|
}
|
|
|
|
/**
|
|
* Update settings.
|
|
*
|
|
* @param WP_REST_Request $request Request.
|
|
* @return WP_REST_Response
|
|
*/
|
|
public static function update_item( WP_REST_Request $request ) {
|
|
$updated = Settings::sanitize( $request->get_json_params() );
|
|
update_option( 'logo_soup_settings', $updated );
|
|
|
|
return new WP_REST_Response( $updated, 200 );
|
|
}
|
|
}
|