| 1 |
<?php |
| 2 |
|
| 3 |
namespace Code_Snippets\REST_API; |
| 4 |
|
| 5 |
use WP_REST_Request; |
| 6 |
use function Code_Snippets\code_snippets; |
| 7 |
use const Code_Snippets\REST_API_NAMESPACE; |
| 8 |
|
| 9 |
/** |
| 10 |
* Base class for REST API controllers. |
| 11 |
*/ |
| 12 |
abstract class REST_Controller { |
| 13 |
|
| 14 |
/** |
| 15 |
* The version of the REST API this controller belongs to. |
| 16 |
* |
| 17 |
* @var string |
| 18 |
*/ |
| 19 |
public const VERSION = 0; |
| 20 |
|
| 21 |
/** |
| 22 |
* The base route for this controller, relative to the REST API namespace and version. |
| 23 |
* |
| 24 |
* @var string |
| 25 |
*/ |
| 26 |
public const BASE_ROUTE = ''; |
| 27 |
|
| 28 |
/** |
| 29 |
* The namespace of this controller's route. |
| 30 |
* |
| 31 |
* @var string |
| 32 |
*/ |
| 33 |
protected string $namespace; |
| 34 |
|
| 35 |
/** |
| 36 |
* Class constructor. |
| 37 |
*/ |
| 38 |
public function __construct() { |
| 39 |
assert( ! empty( static::VERSION ), get_class( $this ) . '::VERSION must be set' ); |
| 40 |
assert( ! empty( static::BASE_ROUTE ), get_class( $this ) . '::BASE_ROUTE must be set' ); |
| 41 |
|
| 42 |
$this->namespace = REST_API_NAMESPACE . static::VERSION; |
| 43 |
add_action( 'rest_api_init', [ $this, 'register_routes' ] ); |
| 44 |
} |
| 45 |
|
| 46 |
/** |
| 47 |
* Retrieve this controller's REST API base path, including namespace. |
| 48 |
* |
| 49 |
* @return string |
| 50 |
*/ |
| 51 |
public static function get_base_route(): string { |
| 52 |
return REST_API_NAMESPACE . static::VERSION . '/' . static::BASE_ROUTE; |
| 53 |
} |
| 54 |
|
| 55 |
/** |
| 56 |
* Register REST routes. |
| 57 |
*/ |
| 58 |
abstract public function register_routes(); |
| 59 |
|
| 60 |
/** |
| 61 |
* Default permission callback for this controller's routes. |
| 62 |
* |
| 63 |
* @param WP_REST_Request $request Full data about the request. |
| 64 |
* |
| 65 |
* @return bool |
| 66 |
*/ |
| 67 |
abstract public function permission_callback( WP_REST_Request $request ): bool; |
| 68 |
} |
| 69 |
|