| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
namespace Metricool\Features\AdminNotices; |
| 6 |
|
| 7 |
if (!defined('ABSPATH')) { |
| 8 |
exit; |
| 9 |
} |
| 10 |
|
| 11 |
use Metricool\Support\Helpers\Storage; |
| 12 |
use Metricool\Traits\HasRestAccess; |
| 13 |
use Metricool\Traits\HasAllowlistControl; |
| 14 |
|
| 15 |
class AdminNoticesEndpoints |
| 16 |
{ |
| 17 |
use HasRestAccess; |
| 18 |
use HasAllowlistControl; |
| 19 |
|
| 20 |
private AdminNoticesRepository $repository; |
| 21 |
|
| 22 |
public function __construct(AdminNoticesRepository $repository) |
| 23 |
{ |
| 24 |
$this->repository = $repository; |
| 25 |
} |
| 26 |
|
| 27 |
public function register(): void |
| 28 |
{ |
| 29 |
add_filter('metricool_rest_routes', [$this, 'addRestRoutes']); |
| 30 |
} |
| 31 |
|
| 32 |
public function addRestRoutes(array $routes): array |
| 33 |
{ |
| 34 |
$routes['/admin-notices/(?P<notice_id>[\w-]+)'] = [ |
| 35 |
'methods' => 'POST', |
| 36 |
'callback' => [$this, 'handleNoticeAction'], |
| 37 |
'args' => [ |
| 38 |
'notice_id' => [ |
| 39 |
'required' => true, |
| 40 |
'type' => 'string', |
| 41 |
'sanitize_callback' => 'sanitize_text_field', |
| 42 |
], |
| 43 |
'action' => [ |
| 44 |
'required' => true, |
| 45 |
'type' => 'string', |
| 46 |
'enum' => [AbstractAdminNotice::DISMISS_NOTICE_ACTION, AbstractAdminNotice::SNOOZE_NOTICE_ACTION], |
| 47 |
], |
| 48 |
], |
| 49 |
]; |
| 50 |
|
| 51 |
return $routes; |
| 52 |
} |
| 53 |
|
| 54 |
public function handleNoticeAction(\WP_REST_Request $wpRestRequest): \WP_REST_Response |
| 55 |
{ |
| 56 |
$request = new Storage( |
| 57 |
$wpRestRequest->get_params() |
| 58 |
); |
| 59 |
|
| 60 |
$noticeId = $request->getString('notice_id'); |
| 61 |
$action = $request->getString('action'); |
| 62 |
|
| 63 |
$notice = $this->repository->find($noticeId); |
| 64 |
if ($notice === null) { |
| 65 |
return $this->sendHttpErrorResponse('Notice not found', null, 404); |
| 66 |
} |
| 67 |
|
| 68 |
if ($action === AbstractAdminNotice::DISMISS_NOTICE_ACTION) { |
| 69 |
$notice->dismiss(); |
| 70 |
} |
| 71 |
|
| 72 |
if ($action === AbstractAdminNotice::SNOOZE_NOTICE_ACTION) { |
| 73 |
$notice->snooze(); |
| 74 |
} |
| 75 |
|
| 76 |
return $this->sendHttpResponse(['success' => true]); |
| 77 |
} |
| 78 |
} |
| 79 |
|