formService = $formService; $this->fieldService = $fieldService; } /** * @param WP_REST_Request $data * * @return WP_REST_Response * * @throws QueryExecutionException * @throws InvalidArgumentException * @throws NotFoundException * @throws ValidationException * @throws 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 ID is provided if (empty($data->get_params())) { throw new InvalidArgumentException('Invalid request data.'); } $formId = Sanitizer::sanitizeId($data->get_param('id')) ; // Retrieve the original form $originalForm = $this->formService->getFormById($formId); // Duplicate the form's parameters, excluding the ID $newFormData = $originalForm->toArray(); unset($newFormData['id']); // Exclude the ID $newFormData['name'] .= ' (Copy)'; // Append "(Copy)" to the name $newForm = FormFactory::create($newFormData); // Save the new form to the database $newFormId = $this->formService->createForm($newForm); if (!$newFormId) { throw new QueryExecutionException('Failed to duplicate form.'); } // Retrieve and duplicate the fields associated with the original form $originalFields = $this->fieldService->getAllFields($formId); if (!empty($originalFields)) { foreach ($originalFields as $field) { $fieldData = $field->toArray(); $fieldData['formId'] = $newFormId; // Link to the new form unset($fieldData['id']); // Exclude the field ID $newField = FieldFactory::create($fieldData); $this->fieldService->addField($newField); } } // Set the new form ID $newForm->setId($newFormId); return new WP_REST_Response([ 'message' => 'OK', 'data' => $newForm->toArray() ], 200); } }