1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
<?php
namespace SIW\API;
abstract class Endpoint {
protected $namespace = 'siw';
protected $version = 'v1';
protected $resource;
protected $methods;
protected $callback;
protected $script;
protected $script_deps = [];
protected $permission_callback = 'verify_nonce';
protected $parameters;
protected $script_parameters;
protected $args;
public static function init() {
$self = new static();
$self->set_parameters();
$self->set_args();
add_action( 'rest_api_init', [ $self, 'register_route' ] );
$self->set_script_parameters();
add_action( 'wp_enqueue_scripts', [ $self, 'enqueue_script' ] );
}
public function register_route() {
register_rest_route( "{$this->namespace}/{$this->version}", $this->resource, [
[
'methods' => $this->methods,
'callback' => [ $this, $this->callback ],
'args' => $this->args,
'permission_callback' => [ $this, $this->permission_callback ],
],
] );
}
protected function set_args() {
$parameters = $this->parameters;
foreach ( $parameters as $parameter => $required ) {
$args[ $parameter ] = [
'required' => $required,
'validate_callback' => [ $this, "validate_{$parameter}"],
'sanitize_callback' => [ $this, "sanitize_{$parameter}"],
];
}
$this->args = $args;
}
abstract protected function set_parameters();
protected function set_script_parameters() {}
public function verify_nonce( \WP_REST_Request $request ) {
$nonce = $request->get_header( 'x_wp_nonce' );
return wp_verify_nonce( $nonce, 'wp_rest' );
}
public function enqueue_script() {
wp_register_script( "siw-api-{$this->script}", SIW_ASSETS_URL . "js/api/siw-{$this->script}.js", $this->script_deps, SIW_PLUGIN_VERSION, true );
$script_parameters = wp_parse_args(
$this->script_parameters,
[
'nonce' => wp_create_nonce( 'wp_rest' ),
'url' => get_rest_url( null, "/{$this->namespace}/{$this->version}/{$this->resource}"),
]
);
wp_localize_script( "siw-api-{$this->script}", "siw_api_{$this->script}", $script_parameters );
wp_enqueue_script( "siw-api-{$this->script}" );
}
}