| 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\Entry; |
| 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\Exceptions\ValidationException; |
| 18 |
use IvyForms\Common\Sanitizer\Sanitizer; |
| 19 |
use IvyForms\Controllers\Controller; |
| 20 |
use IvyForms\Factory\Entry\EntryFactory; |
| 21 |
use IvyForms\Services\Entry\EntryService; |
| 22 |
use IvyForms\Services\Translations\BackendStrings; |
| 23 |
use WP_REST_Request; |
| 24 |
use WP_REST_Response; |
| 25 |
|
| 26 |
class SearchEntriesController extends Controller |
| 27 |
{ |
| 28 |
private EntryService $entryService; |
| 29 |
|
| 30 |
public function __construct( |
| 31 |
EntryService $entryService |
| 32 |
) { |
| 33 |
$this->entryService = $entryService; |
| 34 |
} |
| 35 |
|
| 36 |
/** |
| 37 |
* @param WP_REST_Request $data |
| 38 |
* |
| 39 |
* @return WP_REST_Response |
| 40 |
* @throws ForbiddenException |
| 41 |
* @throws InvalidArgumentException |
| 42 |
* @throws ValidationException |
| 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 searchEntries method |
| 53 |
$entriesArr = $this->entryService->getEntryManager()->searchEntries($params); |
| 54 |
|
| 55 |
// Map the data to Entry entities |
| 56 |
$entries = array_map(function ($entryData) { |
| 57 |
$entryEntity = EntryFactory::create($entryData); |
| 58 |
return $entryEntity->toArray(); |
| 59 |
}, $entriesArr['data']); |
| 60 |
|
| 61 |
$filterCount = $this->entryService->getEntryManager()->getFilterCount($params); |
| 62 |
// Pass `true` to retrieve raw field values for the result table. |
| 63 |
$entryFields = $this->entryService->getEntryFieldManager()->getEntryFields($entriesArr['data'], true); |
| 64 |
$formIdToName = $entriesArr['formIdToName'] ?? []; |
| 65 |
|
| 66 |
// Return the response with data and meta |
| 67 |
return new WP_REST_Response([ |
| 68 |
'message' => BackendStrings::getCommonStrings()['ok'], |
| 69 |
'data' => [ |
| 70 |
'data' => $entries, |
| 71 |
'meta' => $entriesArr['meta'] ?? [], |
| 72 |
'filterCount' => $filterCount, |
| 73 |
'entryFields' => $entryFields, |
| 74 |
'formIdToName' => $formIdToName, |
| 75 |
], |
| 76 |
], 200); |
| 77 |
} |
| 78 |
} |
| 79 |
|