formService = $formService; $this->fieldService = $fieldService; $this->notificationService = $notificationService; $this->confirmationService = $confirmationService; $this->templateService = $templateService; } /** * @param WP_REST_Request> $data * * @return WP_REST_Response * * @throws QueryExecutionException * @throws InvalidArgumentException * @throws ValidationException * @throws ForbiddenException */ public function handle(WP_REST_Request $data): WP_REST_Response { Sanitizer::verifyNonce($data->get_header('X-WP-Nonce')); // Check if the form data is provided if (empty($data->get_params())) { throw new InvalidArgumentException( BackendStrings::getExceptionStrings()['invalid_request_data'] ); } // TODO Add validation for template_id with Sanitizer //$templateId = Sanitizer::sanitizeText($data->get_param('id')); $templateId = sanitize_text_field($data->get_param('template_id')); if (empty($templateId)) { throw new InvalidArgumentException( BackendStrings::getTemplateStrings()['template_not_found'] ); } $formData = $this->templateService->getFormDataFromTemplate($templateId); $params = Sanitizer::sanitizeFormData($formData); $form = FormFactory::create($params); $formId = $this->formService->createForm($form); if (!$formId) { throw new QueryExecutionException( BackendStrings::getAllFormsStrings()['failed_to_create_form'] ); } $adminEmail = get_option('admin_email'); $defaultNotification = [ 'formId' => $formId, 'name' => BackendStrings::getAllFormsStrings()['admin_notification_email'], 'sender' => $adminEmail, 'receiver' => $adminEmail, 'enabled' => 1, 'subject' => $params['name'], 'message' => '{all_data}', 'smartLogic' => 0, ]; $notification = NotificationFactory::create($defaultNotification); $notificationId = $this->notificationService->createNotification($notification); if (!$notificationId) { throw new QueryExecutionException( BackendStrings::getSettingsFormBuilderStrings()['failed_to_create_default_notification'] ); } $notification->setId($notificationId); $defaultConfirmation = [ 'formId' => $formId, 'type' => 'successMessage', 'enabled' => 1, 'showForm' => 0, 'message' => BackendStrings::getAllFormsStrings()['thanks_reaching'], 'url' => '', 'page' => '', ]; $confirmation = ConfirmationFactory::create($defaultConfirmation); $confirmationId = $this->confirmationService->createConfirmation($confirmation); if (!$confirmationId) { throw new QueryExecutionException( BackendStrings::getSettingsFormBuilderStrings()['failed_to_create_confirmation'] ); } $confirmation->setId($confirmationId); // Save form fields if (!empty($params['fields'])) { foreach ($params['fields'] as $fieldData) { $fieldData['formId'] = $fieldData['formId'] ?? $formId; $field = FieldFactory::create($fieldData); $this->fieldService->addField($field); } } $form->setId($formId); return new WP_REST_Response([ 'message' => BackendStrings::getCommonStrings()['ok'], 'data' => array_merge($form->toArray(), ['confirmationId' => $confirmationId]) ], 200); } }