Added API/Endpoint abstract class

- (re)Added Endpoints folder to both API and Router
- fixed syntax in namespaces
- xhr.responseJSON is returned to the fail()
- fixed Router endpoints (view in browser, cron,...)
This commit is contained in:
Jonathan Labreuille
2016-08-02 17:08:43 +02:00
parent ed30d8f639
commit 2e88d7cce0
40 changed files with 99 additions and 111 deletions

View File

@ -36,19 +36,19 @@ class API {
function setupAdmin() {
if($this->checkToken() === false) {
$this->errorResponse(
(new ErrorResponse(
array('unauthorized' => __('This request is not authorized.')),
array(),
APIResponse::STATUS_UNAUTHORIZED
)->send();
Response::STATUS_UNAUTHORIZED
))->send();
}
if($this->checkPermissions() === false) {
$this->errorResponse(
(new ErrorResponse(
array('forbidden' => __('You do not have the required permissions.')),
array(),
APIResponse::STATUS_FORBIDDEN
)->send();
Response::STATUS_FORBIDDEN
))->send();
}
$this->processRoute();
@ -56,9 +56,9 @@ class API {
function setupPublic() {
if($this->checkToken() === false) {
$response = new APIErrorResponse(array(
$response = new ErrorResponse(array(
'unauthorized' => __('This request is not authorized.')
), APIResponse::STATUS_UNAUTHORIZED);
), Response::STATUS_UNAUTHORIZED);
$response->send();
}
@ -67,7 +67,7 @@ class API {
function processRoute() {
$class = ucfirst($_POST['endpoint']);
$endpoint = __NAMESPACE__ . "\\" . $class;
$endpoint = __NAMESPACE__ . "\\Endpoints\\" . $class;
$method = $_POST['method'];
$doing_ajax = (bool)(defined('DOING_AJAX') && DOING_AJAX);
@ -101,9 +101,7 @@ class API {
wp_send_json($response);
}
} catch(\Exception $e) {
$this->errorResponse(array(
$e->getMessage()
))->send();
(new ErrorResponse(array($e->getMessage())))->send();
}
}
@ -125,22 +123,4 @@ class API {
wp_verify_nonce($_POST['token'], 'mailpoet_token')
);
}
function successResponse(
$data = array(), $meta = array(), $status = APIResponse::STATUS_OK
) {
return new APISuccessResponse($data, $meta, $status);
}
function errorResponse(
$errors = array(), $meta = array(), $status = APIResponse::STATUS_NOT_FOUND
) {
return new APIErrorResponse($errors, $meta, $status);
}
function badRequest($errors = array(), $meta = array()) {
return new APIErrorResponse($errors, $meta, APIResponse::STATUS_BAD_REQUEST);
}
}