← All changes
|
backend/src/Controllers/Notification/AddNotificationController.php
+71
-0
0.6.1
→
1.5.1
View file →
| @@ -1,0 +1,71 @@ | ||
| 1 | +<?php | |
| 2 | + | |
| 3 | +namespace IvyForms\Controllers\Notification; | |
| 4 | + | |
| 5 | +use IvyForms\Common\Exceptions\ForbiddenException; | |
| 6 | +use IvyForms\Common\Exceptions\InvalidArgumentException; | |
| 7 | +use IvyForms\Common\Exceptions\QueryExecutionException; | |
| 8 | +use IvyForms\Common\Sanitizer\Sanitizer; | |
| 9 | +use IvyForms\Controllers\Controller; | |
| 10 | +use IvyForms\Factory\Notification\NotificationFactory; | |
| 11 | +use IvyForms\Services\Notification\NotificationService; | |
| 12 | +use IvyForms\Services\Translations\BackendStrings; | |
| 13 | +use WP_REST_Request; | |
| 14 | +use WP_REST_Response; | |
| 15 | + | |
| 16 | +/** | |
| 17 | + * Class AddNotificationController | |
| 18 | + * | |
| 19 | + * @package IvyForms\Controllers\Notification | |
| 20 | + */ | |
| 21 | +class AddNotificationController extends Controller | |
| 22 | +{ | |
| 23 | + private NotificationService $notificationService; | |
| 24 | + | |
| 25 | + public function __construct(NotificationService $notificationService) | |
| 26 | + { | |
| 27 | + $this->notificationService = $notificationService; | |
| 28 | + } | |
| 29 | + | |
| 30 | + /** | |
| 31 | + * @param WP_REST_Request $data | |
| 32 | + * | |
| 33 | + * @return WP_REST_Response | |
| 34 | + * | |
| 35 | + * @throws QueryExecutionException | |
| 36 | + * @throws InvalidArgumentException | |
| 37 | + * @throws ForbiddenException | |
| 38 | + */ | |
| 39 | + public function handle(WP_REST_Request $data): WP_REST_Response | |
| 40 | + { | |
| 41 | + // Verify the nonce | |
| 42 | + Sanitizer::verifyNonce($data->get_header('X-WP-Nonce')); | |
| 43 | + | |
| 44 | + // Validate request data | |
| 45 | + if (empty($data->get_params())) { | |
| 46 | + throw new InvalidArgumentException( | |
| 47 | + BackendStrings::getExceptionStrings()['invalid_request_data'] | |
| 48 | + ); | |
| 49 | + } | |
| 50 | + | |
| 51 | + // Sanitize the input data | |
| 52 | + $params = Sanitizer::sanitizeNotificationData($data->get_params()); | |
| 53 | + | |
| 54 | + $notification = NotificationFactory::create($params); | |
| 55 | + | |
| 56 | + $notificationId = $this->notificationService->createNotification($notification); | |
| 57 | + | |
| 58 | + if (!$notificationId) { | |
| 59 | + throw new QueryExecutionException( | |
| 60 | + BackendStrings::getSettingsFormBuilderStrings()['failed_to_create_notification'] . '.' | |
| 61 | + ); | |
| 62 | + } | |
| 63 | + | |
| 64 | + $notification->setId($notificationId); | |
| 65 | + | |
| 66 | + return new WP_REST_Response([ | |
| 67 | + 'message' => BackendStrings::getCommonStrings()['ok'], | |
| 68 | + 'data' => $notification->toArray() | |
| 69 | + ], 200); | |
| 70 | + } | |
| 71 | +} | |