| 1 |
<?php |
| 2 |
/** |
| 3 |
* REST API LP Widget. |
| 4 |
* |
| 5 |
* @author Nhamdv <daonham95@gmail.com> |
| 6 |
*/ |
| 7 |
|
| 8 |
class LP_REST_Widgets_Controller extends LP_Abstract_REST_Controller { |
| 9 |
public function __construct() { |
| 10 |
$this->namespace = 'lp/v1'; |
| 11 |
$this->rest_base = 'widgets'; |
| 12 |
|
| 13 |
parent::__construct(); |
| 14 |
} |
| 15 |
|
| 16 |
public function register_routes() { |
| 17 |
$this->routes = array( |
| 18 |
'api' => array( |
| 19 |
array( |
| 20 |
'methods' => WP_REST_Server::CREATABLE, |
| 21 |
'callback' => array( $this, 'get_content_widgets' ), |
| 22 |
'permission_callback' => '__return_true', |
| 23 |
), |
| 24 |
), |
| 25 |
); |
| 26 |
|
| 27 |
parent::register_routes(); |
| 28 |
} |
| 29 |
|
| 30 |
public function get_content_widgets( WP_REST_Request $request ) { |
| 31 |
global $wp_widget_factory; |
| 32 |
|
| 33 |
$response = new LP_REST_Response(); |
| 34 |
$response->data = ''; |
| 35 |
|
| 36 |
try { |
| 37 |
$params = $request->get_params(); |
| 38 |
$widget_id = $params['widget'] ?? false; // LP_Widget. |
| 39 |
$instance = $params['instance'] ?? false; |
| 40 |
$hash = $params['hash'] ?? false; |
| 41 |
|
| 42 |
if ( empty( $widget_id ) || empty( $instance ) || empty( $hash ) ) { |
| 43 |
throw new Exception( 'Error: No params!' ); |
| 44 |
} |
| 45 |
|
| 46 |
$widget_object = $wp_widget_factory->get_widget_object( $widget_id ); |
| 47 |
|
| 48 |
if ( ! method_exists( $widget_object, 'lp_rest_api_content' ) ) { |
| 49 |
throw new Exception( 'Error: No method lp_rest_api_content!' ); |
| 50 |
} |
| 51 |
|
| 52 |
$serialized_instance = base64_decode( $instance ); |
| 53 |
|
| 54 |
if ( ! hash_equals( wp_hash( $serialized_instance ), $hash ) ) { |
| 55 |
throw new Exception( 'The provided instance is malformed.' ); |
| 56 |
} |
| 57 |
|
| 58 |
$instance = unserialize( $serialized_instance ); |
| 59 |
|
| 60 |
unset( $params['instance'] ); |
| 61 |
unset( $params['hash'] ); |
| 62 |
|
| 63 |
$data = $widget_object->lp_rest_api_content( $instance, $params ); // LP_Widget->lp_rest_api_content. |
| 64 |
|
| 65 |
if ( is_wp_error( $data ) ) { |
| 66 |
throw new Exception( $data->get_error_message() ); |
| 67 |
} |
| 68 |
|
| 69 |
$response->status = 'success'; |
| 70 |
$response->data = $data; |
| 71 |
} catch ( Throwable $th ) { |
| 72 |
$response->status = 'error'; |
| 73 |
$response->message = $th->getMessage(); |
| 74 |
} |
| 75 |
|
| 76 |
return rest_ensure_response( $response ); |
| 77 |
} |
| 78 |
} |
| 79 |
|