| 1 |
<?php |
| 2 |
|
| 3 |
namespace Booktics\Abstracts; |
| 4 |
|
| 5 |
if ( ! defined( 'ABSPATH' ) ) exit; |
| 6 |
|
| 7 |
use Booktics\Contracts\Hookable_Service_Contract; |
| 8 |
use Exception; |
| 9 |
use WP_Error; |
| 10 |
use WP_HTTP_Response; |
| 11 |
use WP_REST_Controller; |
| 12 |
|
| 13 |
/** |
| 14 |
* BaseRest Controller |
| 15 |
* |
| 16 |
* @package Booktics/Abstracts |
| 17 |
*/ |
| 18 |
abstract class Base_Rest_Controller extends WP_REST_Controller implements Hookable_Service_Contract { |
| 19 |
/** |
| 20 |
* Register routes |
| 21 |
* |
| 22 |
* @return void |
| 23 |
*/ |
| 24 |
public function register(): void { |
| 25 |
add_action( 'rest_api_init', array( $this, 'register_routes' ) ); |
| 26 |
} |
| 27 |
|
| 28 |
/** |
| 29 |
* Register all routes |
| 30 |
* |
| 31 |
* @return void |
| 32 |
*/ |
| 33 |
public function register_routes(): void { |
| 34 |
throw new Exception( 'Need to override register_routes method from child class' ); |
| 35 |
} |
| 36 |
|
| 37 |
/** |
| 38 |
* Send rest error |
| 39 |
* |
| 40 |
* @param string $message Error message |
| 41 |
* @param integer $status_code Error status code |
| 42 |
* |
| 43 |
* @return WP_HTTP_Response |
| 44 |
*/ |
| 45 |
public function error( $message, $status_code = 422, $type = '', $details = '' ) { |
| 46 |
$data = array( |
| 47 |
'success' => 0, |
| 48 |
'message' => $message, |
| 49 |
'error' => array( |
| 50 |
'code' => $status_code, |
| 51 |
'type' => $type, |
| 52 |
'details' => $details, |
| 53 |
), |
| 54 |
); |
| 55 |
|
| 56 |
return new WP_HTTP_Response( $data, $status_code ); |
| 57 |
} |
| 58 |
|
| 59 |
/** |
| 60 |
* Send rest response |
| 61 |
* |
| 62 |
* @param array $data Response data |
| 63 |
* |
| 64 |
* @return WP_HTTP_Response |
| 65 |
*/ |
| 66 |
public function response( $data, $message = '', $status_code = 200 ) { |
| 67 |
if ( ! $message ) { |
| 68 |
$message = __( 'Request was successful', 'booktics' ); |
| 69 |
} |
| 70 |
|
| 71 |
$data = array( |
| 72 |
'success' => 1, |
| 73 |
'message' => $message, |
| 74 |
'data' => $data, |
| 75 |
); |
| 76 |
|
| 77 |
return new WP_HTTP_Response( $data, $status_code ); |
| 78 |
} |
| 79 |
} |
| 80 |
|