| 1 |
<?php |
| 2 |
|
| 3 |
namespace ShopEngine\Base; |
| 4 |
|
| 5 |
defined('ABSPATH') || exit; |
| 6 |
|
| 7 |
abstract class Api { |
| 8 |
|
| 9 |
public $prefix = ''; |
| 10 |
public $param = ''; |
| 11 |
public $request = null; |
| 12 |
public $only_admin = false; |
| 13 |
|
| 14 |
abstract public function config(); |
| 15 |
|
| 16 |
public function __construct() { |
| 17 |
$this->config(); |
| 18 |
$this->init(); |
| 19 |
} |
| 20 |
|
| 21 |
|
| 22 |
public function init() { |
| 23 |
add_action('rest_api_init', function() { |
| 24 |
register_rest_route(untrailingslashit(\ShopEngine::SHOPENGINE_PREFIX.'/v1/' . $this->prefix), '/(?P<action>\w+)/' . ltrim($this->param, '/'), array( |
| 25 |
'methods' => \WP_REST_Server::ALLMETHODS, |
| 26 |
'callback' => [$this, 'action'], |
| 27 |
'permission_callback' => function() { |
| 28 |
if($this->only_admin) { |
| 29 |
return current_user_can('edit_others_posts'); |
| 30 |
} |
| 31 |
return true; |
| 32 |
}, |
| 33 |
)); |
| 34 |
}); |
| 35 |
} |
| 36 |
|
| 37 |
|
| 38 |
public function action($request) { |
| 39 |
$this->request = $request; |
| 40 |
$action_class = strtolower($this->request->get_method()) . '_' . sanitize_key($this->request['action']); |
| 41 |
|
| 42 |
if(method_exists($this, $action_class)) { |
| 43 |
return $this->{$action_class}(); |
| 44 |
} |
| 45 |
} |
| 46 |
|
| 47 |
} |