| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
namespace Yatra\Controllers; |
| 6 |
|
| 7 |
use WP_REST_Request; |
| 8 |
use WP_REST_Response; |
| 9 |
use WP_REST_Server; |
| 10 |
use Yatra\Services\NoticeService; |
| 11 |
|
| 12 |
defined('ABSPATH') || exit; |
| 13 |
|
| 14 |
final class NoticeController extends BaseController |
| 15 |
{ |
| 16 |
/** |
| 17 |
* @var string |
| 18 |
*/ |
| 19 |
protected string $rest_base = 'notices'; |
| 20 |
|
| 21 |
/** |
| 22 |
* Admin-notice dismissal — gated on the umbrella admin-access |
| 23 |
* cap so any team member who can see the Yatra admin can dismiss |
| 24 |
* the notices they see. The legacy `manage_yatra` cap was never |
| 25 |
* registered anywhere, so the previous OR-arm did nothing in |
| 26 |
* practice. WP admins pass via the Team module's admin-fallback |
| 27 |
* filter. |
| 28 |
*/ |
| 29 |
public function check_permission(?\WP_REST_Request $request = null): bool |
| 30 |
{ |
| 31 |
return current_user_can('yatra_access_admin'); |
| 32 |
} |
| 33 |
|
| 34 |
public function register_routes(): void |
| 35 |
{ |
| 36 |
register_rest_route($this->namespace, '/' . $this->rest_base, [ |
| 37 |
[ |
| 38 |
'methods' => WP_REST_Server::READABLE, |
| 39 |
'callback' => [$this, 'index'], |
| 40 |
'permission_callback' => [$this, 'check_permission'], |
| 41 |
], |
| 42 |
]); |
| 43 |
|
| 44 |
register_rest_route($this->namespace, '/' . $this->rest_base . '/(?P<id>[a-z0-9_\\-]+)/dismiss', [ |
| 45 |
[ |
| 46 |
'methods' => WP_REST_Server::CREATABLE, |
| 47 |
'callback' => [$this, 'dismiss'], |
| 48 |
'permission_callback' => [$this, 'check_permission'], |
| 49 |
'args' => [ |
| 50 |
'id' => [ |
| 51 |
'required' => true, |
| 52 |
'type' => 'string', |
| 53 |
], |
| 54 |
], |
| 55 |
], |
| 56 |
]); |
| 57 |
} |
| 58 |
|
| 59 |
public function index(WP_REST_Request $request): WP_REST_Response |
| 60 |
{ |
| 61 |
return rest_ensure_response([ |
| 62 |
'success' => true, |
| 63 |
'data' => NoticeService::getActiveNoticesForCurrentUser(), |
| 64 |
]); |
| 65 |
} |
| 66 |
|
| 67 |
public function dismiss(WP_REST_Request $request): WP_REST_Response |
| 68 |
{ |
| 69 |
$id = sanitize_key((string) $request->get_param('id')); |
| 70 |
$result = NoticeService::dismissForCurrentUser($id); |
| 71 |
if ($result === true) { |
| 72 |
return rest_ensure_response(['success' => true]); |
| 73 |
} |
| 74 |
|
| 75 |
$response = rest_ensure_response([ |
| 76 |
'success' => false, |
| 77 |
'code' => $result->get_error_code(), |
| 78 |
'message' => $result->get_error_message(), |
| 79 |
]); |
| 80 |
$response->set_status((int) ($result->get_error_data()['status'] ?? 400)); |
| 81 |
return $response; |
| 82 |
} |
| 83 |
} |
| 84 |
|
| 85 |
|