| 1 |
<?php |
| 2 |
namespace Booktics\Admin; |
| 3 |
|
| 4 |
use Booktics\Contracts\Hookable_Service_Contract; |
| 5 |
use WP_REST_Response; |
| 6 |
|
| 7 |
/** |
| 8 |
* RestPermissionMessage class. |
| 9 |
* |
| 10 |
* @package Booktics/Rest_Permission_Message |
| 11 |
*/ |
| 12 |
class Rest_Permission_Message implements Hookable_Service_Contract { |
| 13 |
/** |
| 14 |
* Register hooks |
| 15 |
* |
| 16 |
* @return void |
| 17 |
*/ |
| 18 |
public function register() { |
| 19 |
add_filter( 'rest_request_after_callbacks', array( $this, 'modify_rest_permission_message' ), 10, 3 ); |
| 20 |
} |
| 21 |
|
| 22 |
/** |
| 23 |
* Modify permission error message |
| 24 |
* |
| 25 |
* @return void |
| 26 |
*/ |
| 27 |
public function modify_rest_permission_message( $response, $handler, $request ) { |
| 28 |
|
| 29 |
$namespace = $request->get_route(); |
| 30 |
|
| 31 |
if ( strpos( $namespace, '/booktics' ) !== 0 ) { |
| 32 |
return $response; |
| 33 |
} |
| 34 |
|
| 35 |
if ( is_wp_error( $response ) ) { |
| 36 |
$error_data = $response->get_error_data(); |
| 37 |
$status = isset( $error_data['status'] ) ? $error_data['status'] : 401; |
| 38 |
|
| 39 |
return new WP_REST_Response( |
| 40 |
array( |
| 41 |
'success' => 0, |
| 42 |
'message' => __( 'Unauthorized user', 'booktics' ), |
| 43 |
'error' => array( |
| 44 |
'code' => $response->get_error_code(), |
| 45 |
'type' => 'permission_error', |
| 46 |
'details' => $response->get_error_message(), |
| 47 |
), |
| 48 |
), $status |
| 49 |
); |
| 50 |
} |
| 51 |
|
| 52 |
return $response; |
| 53 |
} |
| 54 |
} |
| 55 |
|