| 1 |
<?php |
| 2 |
|
| 3 |
namespace IvyForms\Controllers\Notification; |
| 4 |
|
| 5 |
use IvyForms\Common\Exceptions\ForbiddenException; |
| 6 |
use IvyForms\Common\Exceptions\InvalidArgumentException; |
| 7 |
use IvyForms\Controllers\Controller; |
| 8 |
use IvyForms\Common\Sanitizer\Sanitizer; |
| 9 |
use IvyForms\Services\Notification\NotificationService; |
| 10 |
use IvyForms\Services\Permissions\PermissionResourceResolver; |
| 11 |
use IvyForms\Services\Permissions\RoutePermissionService; |
| 12 |
use IvyForms\Services\Translations\BackendStrings; |
| 13 |
use WP_REST_Request; |
| 14 |
use WP_REST_Response; |
| 15 |
|
| 16 |
/** |
| 17 |
* Class DeleteNotificationsController |
| 18 |
* |
| 19 |
* @package IvyForms\Controllers\Notification |
| 20 |
*/ |
| 21 |
class DeleteNotificationsController extends Controller |
| 22 |
{ |
| 23 |
private NotificationService $notificationService; |
| 24 |
|
| 25 |
private RoutePermissionService $routePermissionService; |
| 26 |
|
| 27 |
private PermissionResourceResolver $permissionResourceResolver; |
| 28 |
|
| 29 |
public function __construct( |
| 30 |
NotificationService $notificationService, |
| 31 |
RoutePermissionService $routePermissionService, |
| 32 |
PermissionResourceResolver $permissionResourceResolver |
| 33 |
) { |
| 34 |
$this->notificationService = $notificationService; |
| 35 |
$this->routePermissionService = $routePermissionService; |
| 36 |
$this->permissionResourceResolver = $permissionResourceResolver; |
| 37 |
} |
| 38 |
|
| 39 |
/** |
| 40 |
* @param WP_REST_Request $data |
| 41 |
* |
| 42 |
* @return WP_REST_Response |
| 43 |
* |
| 44 |
* @throws InvalidArgumentException |
| 45 |
* @throws ForbiddenException |
| 46 |
*/ |
| 47 |
public function handle(WP_REST_Request $data): WP_REST_Response |
| 48 |
{ |
| 49 |
Sanitizer::verifyNonce($data->get_header('X-WP-Nonce')); |
| 50 |
$notificationIds = Sanitizer::sanitizeIds($data->get_param('ids')); |
| 51 |
|
| 52 |
if (empty($notificationIds)) { |
| 53 |
throw new InvalidArgumentException( |
| 54 |
BackendStrings::getExceptionStrings()['notification_ids_required'] |
| 55 |
); |
| 56 |
} |
| 57 |
|
| 58 |
foreach ($notificationIds as $notificationId) { |
| 59 |
$formId = $this->permissionResourceResolver->formIdFromNotificationId((int) $notificationId); |
| 60 |
if ($formId === null || !$this->routePermissionService->canEditForms($formId)) { |
| 61 |
throw new ForbiddenException('forbidden'); |
| 62 |
} |
| 63 |
} |
| 64 |
|
| 65 |
$this->notificationService->deleteNotifications($notificationIds); |
| 66 |
|
| 67 |
return new WP_REST_Response([ |
| 68 |
'message' => BackendStrings::getCommonStrings()['ok'], |
| 69 |
'data' => [] |
| 70 |
], 200); |
| 71 |
} |
| 72 |
} |
| 73 |
|