| 1 |
<?php |
| 2 |
|
| 3 |
/** |
| 4 |
* API router |
| 5 |
*/ |
| 6 |
|
| 7 |
namespace Extendify; |
| 8 |
|
| 9 |
defined('ABSPATH') || die('No direct access.'); |
| 10 |
|
| 11 |
/** |
| 12 |
* Simple router for the REST Endpoints |
| 13 |
*/ |
| 14 |
|
| 15 |
class ApiRouter extends \WP_REST_Controller |
| 16 |
{ |
| 17 |
/** |
| 18 |
* The class instance. |
| 19 |
* |
| 20 |
* @var self|null |
| 21 |
*/ |
| 22 |
protected static $instance = null; |
| 23 |
|
| 24 |
/** |
| 25 |
* Check the authorization of the request |
| 26 |
* |
| 27 |
* @return boolean |
| 28 |
*/ |
| 29 |
public function checkPermission() |
| 30 |
{ |
| 31 |
// Check for the nonce on the server (used by WP REST). |
| 32 |
if ( |
| 33 |
isset($_SERVER['HTTP_X_WP_NONCE']) |
| 34 |
&& \wp_verify_nonce(sanitize_text_field(wp_unslash($_SERVER['HTTP_X_WP_NONCE'])), 'wp_rest') |
| 35 |
) { |
| 36 |
return \current_user_can(Config::$requiredCapability); |
| 37 |
} |
| 38 |
|
| 39 |
return false; |
| 40 |
} |
| 41 |
|
| 42 |
/** |
| 43 |
* Register dynamic routes |
| 44 |
* |
| 45 |
* @param string $namespace - The api name space. |
| 46 |
* @param string $endpoint - The endpoint. |
| 47 |
* @param function $callback - The callback to run. |
| 48 |
* |
| 49 |
* @return void |
| 50 |
*/ |
| 51 |
public function getHandler($namespace, $endpoint, $callback) |
| 52 |
{ |
| 53 |
\register_rest_route($namespace, $endpoint, [ |
| 54 |
'methods' => 'GET', |
| 55 |
'callback' => $callback, |
| 56 |
'permission_callback' => [$this, 'checkPermission'], |
| 57 |
]); |
| 58 |
} |
| 59 |
|
| 60 |
/** |
| 61 |
* The post handler |
| 62 |
* |
| 63 |
* @param string $namespace - The api name space. |
| 64 |
* @param string $endpoint - The endpoint. |
| 65 |
* @param string $callback - The callback to run. |
| 66 |
* |
| 67 |
* @return void |
| 68 |
*/ |
| 69 |
public function postHandler($namespace, $endpoint, $callback) |
| 70 |
{ |
| 71 |
\register_rest_route($namespace, $endpoint, [ |
| 72 |
'methods' => 'POST', |
| 73 |
'callback' => $callback, |
| 74 |
'permission_callback' => [$this, 'checkPermission'], |
| 75 |
]); |
| 76 |
} |
| 77 |
|
| 78 |
/** |
| 79 |
* The caller |
| 80 |
* |
| 81 |
* @param string $name - The name of the method to call. |
| 82 |
* @param array $arguments - The arguments to pass in. |
| 83 |
* |
| 84 |
* @return mixed |
| 85 |
*/ |
| 86 |
public static function __callStatic($name, array $arguments) |
| 87 |
{ |
| 88 |
$name = "{$name}Handler"; |
| 89 |
if (is_null(self::$instance)) { |
| 90 |
self::$instance = new static(); |
| 91 |
} |
| 92 |
|
| 93 |
$r = self::$instance; |
| 94 |
return $r->$name(Config::$slug . '/' . Config::$apiVersion, ...$arguments); |
| 95 |
} |
| 96 |
} |
| 97 |
|