| 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\Form; |
| 9 |
|
| 10 |
// phpcs:disable PSR1.Files.SideEffects |
| 11 |
if (!defined('ABSPATH')) { |
| 12 |
exit; // Exit if accessed directly |
| 13 |
} |
| 14 |
|
| 15 |
use IvyForms\Common\Exceptions\ForbiddenException; |
| 16 |
use IvyForms\Common\Exceptions\InvalidArgumentException; |
| 17 |
use IvyForms\Common\Sanitizer\Sanitizer; |
| 18 |
use IvyForms\Controllers\Controller; |
| 19 |
use IvyForms\Services\Entry\EntryService; |
| 20 |
use IvyForms\Services\Form\FormService; |
| 21 |
use IvyForms\Services\Translations\BackendStrings; |
| 22 |
use WP_REST_Request; |
| 23 |
use WP_REST_Response; |
| 24 |
|
| 25 |
class SearchFormsController extends Controller |
| 26 |
{ |
| 27 |
private FormService $formService; |
| 28 |
private EntryService $entryService; |
| 29 |
public function __construct( |
| 30 |
FormService $formService, |
| 31 |
EntryService $entryService |
| 32 |
) { |
| 33 |
$this->formService = $formService; |
| 34 |
$this->entryService = $entryService; |
| 35 |
} |
| 36 |
|
| 37 |
/** |
| 38 |
* @param WP_REST_Request $data |
| 39 |
* |
| 40 |
* @return WP_REST_Response |
| 41 |
* @throws ForbiddenException |
| 42 |
* @throws InvalidArgumentException |
| 43 |
*/ |
| 44 |
public function handle(WP_REST_Request $data): WP_REST_Response |
| 45 |
{ |
| 46 |
// Verify the nonce |
| 47 |
Sanitizer::verifyNonce($data->get_header('X-WP-Nonce')); |
| 48 |
|
| 49 |
// Sanitize the filtering data |
| 50 |
$params = Sanitizer::sanitizeSearchParams($data->get_query_params()); |
| 51 |
|
| 52 |
// Call the searchForms method |
| 53 |
$formsArr = $this->formService->searchForms($params); |
| 54 |
|
| 55 |
// Map the data to an array format |
| 56 |
$forms = array_map(fn($form) => (array) $form, $formsArr['data']); |
| 57 |
|
| 58 |
$filterCount = $this->formService->getFilterCount($params['shouldGetCount']); |
| 59 |
|
| 60 |
// Collect form IDs for entry count |
| 61 |
$formIds = array_column($forms, 'id'); |
| 62 |
$entryCounts = $this->entryService->getEntryManager()->getEntryCountByFormIds($formIds); |
| 63 |
|
| 64 |
// Return the response with data, meta, filterCount, and entryCounts |
| 65 |
return new WP_REST_Response([ |
| 66 |
'message' => BackendStrings::getCommonStrings()['ok'], |
| 67 |
'data' => [ |
| 68 |
'data' => $forms, |
| 69 |
'meta' => $formsArr['meta'], |
| 70 |
'filterCount' => $filterCount, |
| 71 |
'entryCounts' => $entryCounts, |
| 72 |
], |
| 73 |
], 200); |
| 74 |
} |
| 75 |
} |
| 76 |
|