← All changes
|
backend/src/Controllers/Template/GetTemplateController.php
+70
-0
0.6.1
→
1.5
View file →
| @@ -1,0 +1,70 @@ | ||
| 1 | +<?php | |
| 2 | + | |
| 3 | +/** | |
| 4 | + * @copyright © Melograno Venture Studio. All rights reserved. | |
| 5 | + * @licence See COPYING.md for license details. | |
| 6 | + */ | |
| 7 | + | |
| 8 | +namespace IvyForms\Controllers\Template; | |
| 9 | + | |
| 10 | +use IvyForms\Common\Exceptions\ForbiddenException; | |
| 11 | +use IvyForms\Common\Exceptions\InvalidArgumentException; | |
| 12 | +use IvyForms\Common\Sanitizer\Sanitizer; | |
| 13 | +use IvyForms\Controllers\Controller; | |
| 14 | +use IvyForms\Services\Template\TemplateService; | |
| 15 | +use WP_REST_Request; | |
| 16 | +use WP_REST_Response; | |
| 17 | +use IvyForms\Services\Translations\BackendStrings; | |
| 18 | + | |
| 19 | +/** | |
| 20 | + * Class GetTemplateController | |
| 21 | + * | |
| 22 | + * @package IvyForms\Controllers\Template | |
| 23 | + */ | |
| 24 | +class GetTemplateController extends Controller | |
| 25 | +{ | |
| 26 | + private TemplateService $templateService; | |
| 27 | + | |
| 28 | + public function __construct(TemplateService $templateService) | |
| 29 | + { | |
| 30 | + $this->templateService = $templateService; | |
| 31 | + } | |
| 32 | + | |
| 33 | + /** | |
| 34 | + * @param WP_REST_Request<array<string, mixed>> $data | |
| 35 | + * @return WP_REST_Response | |
| 36 | + * @throws ForbiddenException | |
| 37 | + * @throws InvalidArgumentException | |
| 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 | + // TODO Add validation for template_id with Sanitizer | |
| 45 | + //$templateId = Sanitizer::sanitizeText($data->get_param('id')); | |
| 46 | + $templateId = sanitize_text_field($data->get_param('id') ?? ''); | |
| 47 | + | |
| 48 | + if (empty($templateId)) { | |
| 49 | + throw new InvalidArgumentException( | |
| 50 | + BackendStrings::getTemplateStrings()['required_template_id'] | |
| 51 | + ); | |
| 52 | + } | |
| 53 | + | |
| 54 | + $template = $this->templateService->getTemplateById($templateId); | |
| 55 | + | |
| 56 | + if (!$template) { | |
| 57 | + throw new InvalidArgumentException( | |
| 58 | + BackendStrings::getTemplateStrings()['template_not_found'] | |
| 59 | + ); | |
| 60 | + } | |
| 61 | + | |
| 62 | + // Apply the same field layout rules used on form create (one field per row by default). | |
| 63 | + $template['form_data'] = $this->templateService->getFormDataFromTemplate($templateId); | |
| 64 | + | |
| 65 | + return new WP_REST_Response([ | |
| 66 | + 'success' => true, | |
| 67 | + 'data' => $template | |
| 68 | + ], 200); | |
| 69 | + } | |
| 70 | +} | |