| 1 |
<?php |
| 2 |
|
| 3 |
/** |
| 4 |
* @copyright © Melograno Venture Studio. All rights reserved. |
| 5 |
* @licence See LICENCE.md for license details. |
| 6 |
*/ |
| 7 |
|
| 8 |
namespace IvyForms\Controllers\Ai; |
| 9 |
|
| 10 |
use IvyForms\Common\Exceptions\InvalidArgumentException; |
| 11 |
use IvyForms\Common\Exceptions\QueryExecutionException; |
| 12 |
use IvyForms\Common\Exceptions\ServiceUnavailableException; |
| 13 |
use IvyForms\Common\Exceptions\ValidationException; |
| 14 |
use IvyForms\Common\Sanitizer\Sanitizer; |
| 15 |
use IvyForms\Controllers\Controller; |
| 16 |
use IvyForms\Services\Ai\AiFormGenerationService; |
| 17 |
use IvyForms\Services\Translations\BackendStrings; |
| 18 |
use WP_REST_Request; |
| 19 |
use WP_REST_Response; |
| 20 |
|
| 21 |
/** |
| 22 |
* Handles single-pass AI form generation from a prompt. |
| 23 |
*/ |
| 24 |
class GenerateFormController extends Controller |
| 25 |
{ |
| 26 |
private AiFormGenerationService $aiFormGenerationService; |
| 27 |
|
| 28 |
public function __construct(AiFormGenerationService $aiFormGenerationService) |
| 29 |
{ |
| 30 |
$this->aiFormGenerationService = $aiFormGenerationService; |
| 31 |
} |
| 32 |
|
| 33 |
/** |
| 34 |
* @param WP_REST_Request<array<string, mixed>> $data |
| 35 |
* |
| 36 |
* @return WP_REST_Response |
| 37 |
* |
| 38 |
* @throws InvalidArgumentException |
| 39 |
* @throws QueryExecutionException |
| 40 |
* @throws ServiceUnavailableException |
| 41 |
* @throws ValidationException |
| 42 |
*/ |
| 43 |
public function handle(WP_REST_Request $data): WP_REST_Response |
| 44 |
{ |
| 45 |
Sanitizer::verifyNonce($data->get_header('X-WP-Nonce')); |
| 46 |
|
| 47 |
$prompt = sanitize_textarea_field((string) ($data->get_param('prompt') ?? '')); |
| 48 |
if ($prompt === '') { |
| 49 |
throw new InvalidArgumentException( |
| 50 |
BackendStrings::getAiStrings()['ai_prompt_required'] |
| 51 |
); |
| 52 |
} |
| 53 |
|
| 54 |
$form = $this->aiFormGenerationService->generateAndCreateForm($prompt); |
| 55 |
|
| 56 |
return new WP_REST_Response($form, 200); |
| 57 |
} |
| 58 |
} |
| 59 |
|