formService = $formService; $this->fieldService = $fieldService; } /** * @param WP_REST_Request $data * * @return WP_REST_Response * * @throws QueryExecutionException * @throws InvalidArgumentException|ValidationException|ForbiddenException */ public function handle(WP_REST_Request $data): WP_REST_Response { // Verify the nonce Sanitizer::verifyNonce($data->get_header('X-WP-Nonce')); // Check if the form data is provided if (empty($data->get_params())) { throw new InvalidArgumentException('Invalid request data.'); } // Sanitize the update data $params = Sanitizer::sanitizeFormData($data->get_params()); $form = FormFactory::create($params); $formId = $form->getId(); $this->formService->updateForm($formId, $form); if (!$form->getId()) { throw new QueryExecutionException(BackendStrings::getAllFormsStrings()['failed_to_update_form'] . '.'); } // refactor by sending delete fields as array and delete it with one query $existingFields = $this->fieldService->getAllFields($formId); $existingFieldIds = array_map(fn($field) => $field->getId(), $existingFields); $submittedFieldIds = []; if (!empty($params['fields'])) { foreach ($params['fields'] as $fieldData) { $fieldData['formId'] = $fieldData['formId'] ?? $formId; $field = FieldFactory::create($fieldData); $fieldId = $field->getId(); if ($fieldId === 0) { // Add new field $newField = $this->fieldService->addField($field); $submittedFieldIds[] = $newField; continue; } // Update existing field $this->fieldService->updateField($fieldId, $field); $submittedFieldIds[] = $fieldId; } } // Delete fields that are not in the submitted data foreach ($existingFieldIds as $existingId) { if (!in_array($existingId, $submittedFieldIds, true)) { $this->fieldService->deleteField($existingId); } } return new WP_REST_Response([ 'message' => BackendStrings::getCommonStrings()['ok'], 'data' => $form->toArray() ], 200); } }