| 1 |
<?php |
| 2 |
|
| 3 |
if ( ! defined( 'ABSPATH' ) ) { |
| 4 |
// Exit if accessed directly. |
| 5 |
exit; |
| 6 |
} |
| 7 |
|
| 8 |
if ( ! class_exists( 'Qi_Blocks_Rest_API' ) ) { |
| 9 |
/** |
| 10 |
* Rest API class with configuration |
| 11 |
*/ |
| 12 |
class Qi_Blocks_Rest_API { |
| 13 |
private static $instance; |
| 14 |
private $namespace; |
| 15 |
|
| 16 |
public function __construct() { |
| 17 |
// Init variables. |
| 18 |
$this->set_namespace( 'qi-blocks/v1' ); |
| 19 |
|
| 20 |
// Localize main editor js script with additional variables. |
| 21 |
add_filter( 'qi_blocks_filter_localize_main_editor_js', array( $this, 'localize_script' ) ); |
| 22 |
|
| 23 |
// Function that register Rest API routes. |
| 24 |
add_action( 'rest_api_init', array( $this, 'register_rest_api_route' ) ); |
| 25 |
} |
| 26 |
|
| 27 |
/** |
| 28 |
* Module class instance |
| 29 |
* |
| 30 |
* @return Qi_Blocks_Rest_API |
| 31 |
*/ |
| 32 |
public static function get_instance() { |
| 33 |
if ( is_null( self::$instance ) ) { |
| 34 |
self::$instance = new self(); |
| 35 |
} |
| 36 |
|
| 37 |
return self::$instance; |
| 38 |
} |
| 39 |
|
| 40 |
public function get_namespace() { |
| 41 |
return $this->namespace; |
| 42 |
} |
| 43 |
|
| 44 |
public function set_namespace( $namespace ) { |
| 45 |
$this->namespace = $namespace; |
| 46 |
} |
| 47 |
|
| 48 |
public function localize_script( $global ) { |
| 49 |
$global['restUrl'] = esc_url_raw( rest_url() ); |
| 50 |
$global['restNonce'] = wp_create_nonce( 'wp_rest' ); |
| 51 |
|
| 52 |
return apply_filters( 'qi_blocks_filter_localize_main_editor_js_rest_api', $global, $this->get_namespace() ); |
| 53 |
} |
| 54 |
|
| 55 |
public function register_rest_api_route() { |
| 56 |
$routes = apply_filters( 'qi_blocks_filter_rest_api_routes', array() ); |
| 57 |
|
| 58 |
if ( ! empty( $routes ) ) { |
| 59 |
foreach ( $routes as $route ) { |
| 60 |
$permission_callback = isset( $route['permission_callback'] ) && ! empty( $route['permission_callback'] ) ? $route['permission_callback'] : '__return_true'; |
| 61 |
|
| 62 |
register_rest_route( |
| 63 |
$this->get_namespace(), |
| 64 |
esc_attr( $route['route'] ), |
| 65 |
array( |
| 66 |
'methods' => $route['methods'], |
| 67 |
'callback' => $route['callback'], |
| 68 |
'permission_callback' => $permission_callback, |
| 69 |
'args' => $route['args'] ?? array(), |
| 70 |
) |
| 71 |
); |
| 72 |
} |
| 73 |
} |
| 74 |
} |
| 75 |
} |
| 76 |
|
| 77 |
Qi_Blocks_Rest_API::get_instance(); |
| 78 |
} |
| 79 |
|