| 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\Settings; |
| 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\Settings\SettingsService; |
| 20 |
use IvyForms\Services\Translations\BackendStrings; |
| 21 |
use WP_REST_Request; |
| 22 |
use WP_REST_Response; |
| 23 |
|
| 24 |
/** |
| 25 |
* Class UpdateSettingController |
| 26 |
* |
| 27 |
* @package IvyForms\Controllers\Settings |
| 28 |
*/ |
| 29 |
class UpdateSettingController extends Controller |
| 30 |
{ |
| 31 |
private SettingsService $settingsService; |
| 32 |
|
| 33 |
public function __construct( |
| 34 |
SettingsService $settingsService |
| 35 |
) { |
| 36 |
$this->settingsService = $settingsService; |
| 37 |
} |
| 38 |
|
| 39 |
/** |
| 40 |
* @param WP_REST_Request $data |
| 41 |
* |
| 42 |
* @return WP_REST_Response |
| 43 |
* |
| 44 |
* @throws InvalidArgumentException |
| 45 |
* @throws ForbiddenException |
| 46 |
*/ |
| 47 |
public function handle(WP_REST_Request $data): WP_REST_Response |
| 48 |
{ |
| 49 |
// Verify the nonce |
| 50 |
Sanitizer::verifyNonce($data->get_header('X-WP-Nonce')); |
| 51 |
|
| 52 |
// Check if settings parameters are provided |
| 53 |
if (empty($data->get_params())) { |
| 54 |
throw new InvalidArgumentException( |
| 55 |
BackendStrings::getCommonStrings()['invalid_request_data'] |
| 56 |
); |
| 57 |
} |
| 58 |
|
| 59 |
$settingsCategory = Sanitizer::sanitizeText($data->get_params()['settingsCategory']); |
| 60 |
$settingsOption = Sanitizer::sanitizeText($data->get_params()['settingsOption']); |
| 61 |
$settingsValue = Sanitizer::sanitizeSettingsFields($data->get_params()['settingsValue']); |
| 62 |
|
| 63 |
if (empty($settingsCategory) || empty($settingsOption)) { |
| 64 |
throw new InvalidArgumentException( |
| 65 |
BackendStrings::getSettingsStrings()['settings_category_or_option_missing'] |
| 66 |
); |
| 67 |
} |
| 68 |
|
| 69 |
// Update the setting |
| 70 |
$this->settingsService->setSetting($settingsCategory, $settingsOption, $settingsValue); |
| 71 |
|
| 72 |
return new WP_REST_Response([ |
| 73 |
'message' => BackendStrings::getSettingsStrings()['settings_option_updated'], |
| 74 |
'data' => [ |
| 75 |
'value' => $this->settingsService->getSetting($settingsCategory, $settingsOption), |
| 76 |
] |
| 77 |
], 200); |
| 78 |
} |
| 79 |
} |
| 80 |
|