| 1 |
<?php |
| 2 |
|
| 3 |
namespace IvyForms\Controllers\Form; |
| 4 |
|
| 5 |
use IvyForms\Common\Exceptions\ForbiddenException; |
| 6 |
use IvyForms\Common\Exceptions\InvalidArgumentException; |
| 7 |
use IvyForms\Common\Sanitizer\Sanitizer; |
| 8 |
use IvyForms\Controllers\Controller; |
| 9 |
use IvyForms\Services\Form\FormImportExportService; |
| 10 |
use IvyForms\Services\Translations\BackendStrings; |
| 11 |
use WP_REST_Request; |
| 12 |
use WP_REST_Response; |
| 13 |
|
| 14 |
class ExportFormController extends Controller |
| 15 |
{ |
| 16 |
private FormImportExportService $importExportService; |
| 17 |
|
| 18 |
public function __construct(FormImportExportService $importExportService) |
| 19 |
{ |
| 20 |
$this->importExportService = $importExportService; |
| 21 |
} |
| 22 |
|
| 23 |
/** |
| 24 |
* Handle the export request |
| 25 |
* |
| 26 |
* @param WP_REST_Request<array<string, mixed>> $data |
| 27 |
* @return WP_REST_Response |
| 28 |
* @throws ForbiddenException |
| 29 |
* @throws InvalidArgumentException |
| 30 |
*/ |
| 31 |
public function handle(WP_REST_Request $data): WP_REST_Response |
| 32 |
{ |
| 33 |
// Verify the nonce |
| 34 |
Sanitizer::verifyNonce($data->get_header('X-WP-Nonce')); |
| 35 |
|
| 36 |
// Get form IDs from request |
| 37 |
$formIds = $data->get_param('formIds'); |
| 38 |
|
| 39 |
if (empty($formIds)) { |
| 40 |
throw new InvalidArgumentException( |
| 41 |
BackendStrings::getExceptionStrings()['no_form_ids_for_export'] |
| 42 |
); |
| 43 |
} |
| 44 |
|
| 45 |
// Sanitize and validate form IDs |
| 46 |
$formIds = array_values(array_unique(array_filter( |
| 47 |
array_map('intval', (array) $formIds), |
| 48 |
static fn (int $id): bool => $id > 0 |
| 49 |
))); |
| 50 |
|
| 51 |
if ($formIds === []) { |
| 52 |
throw new InvalidArgumentException( |
| 53 |
BackendStrings::getExceptionStrings()['no_form_ids_for_export'] |
| 54 |
); |
| 55 |
} |
| 56 |
|
| 57 |
// Export forms using service |
| 58 |
$exportData = $this->importExportService->exportForms($formIds); |
| 59 |
|
| 60 |
return new WP_REST_Response([ |
| 61 |
'success' => true, |
| 62 |
'data' => $exportData, |
| 63 |
'message' => BackendStrings::getCommonStrings()['forms_exported_successfully'] |
| 64 |
], 200); |
| 65 |
} |
| 66 |
} |
| 67 |
|