| 1 |
<?php |
| 2 |
|
| 3 |
/** |
| 4 |
* @copyright © Melograno Venture Studio. All rights reserved. |
| 5 |
*/ |
| 6 |
|
| 7 |
namespace IvyForms\Controllers\Permissions; |
| 8 |
|
| 9 |
// phpcs:disable PSR1.Files.SideEffects |
| 10 |
if (!defined('ABSPATH')) { |
| 11 |
exit; |
| 12 |
} |
| 13 |
|
| 14 |
use IvyForms\Common\Exceptions\ForbiddenException; |
| 15 |
use IvyForms\Common\Exceptions\ValidationException; |
| 16 |
use IvyForms\Common\Sanitizer\Sanitizer; |
| 17 |
use IvyForms\Controllers\Controller; |
| 18 |
use IvyForms\Repository\Permissions\AccessRulesRepository; |
| 19 |
use IvyForms\Services\Permissions\AccessRulesRoleCapabilitySynchronizer; |
| 20 |
use IvyForms\Services\Permissions\AccessRulesValidator; |
| 21 |
use IvyForms\Services\Translations\BackendStrings; |
| 22 |
use WP_REST_Request; |
| 23 |
use WP_REST_Response; |
| 24 |
|
| 25 |
class UpdateAccessRulesController extends Controller |
| 26 |
{ |
| 27 |
private AccessRulesRepository $accessRulesRepository; |
| 28 |
private AccessRulesValidator $accessRulesValidator; |
| 29 |
|
| 30 |
public function __construct( |
| 31 |
AccessRulesRepository $accessRulesRepository, |
| 32 |
AccessRulesValidator $accessRulesValidator |
| 33 |
) { |
| 34 |
$this->accessRulesRepository = $accessRulesRepository; |
| 35 |
$this->accessRulesValidator = $accessRulesValidator; |
| 36 |
} |
| 37 |
|
| 38 |
/** |
| 39 |
* @throws ForbiddenException |
| 40 |
* @throws ValidationException |
| 41 |
*/ |
| 42 |
public function handle(WP_REST_Request $data): WP_REST_Response |
| 43 |
{ |
| 44 |
Sanitizer::verifyNonce($data->get_header('X-WP-Nonce')); |
| 45 |
|
| 46 |
$body = $data->get_json_params(); |
| 47 |
if (!is_array($body) || !isset($body['rules']) || !is_array($body['rules'])) { |
| 48 |
throw new ValidationException( |
| 49 |
BackendStrings::getExceptionStrings()['rules_payload_required'] |
| 50 |
); |
| 51 |
} |
| 52 |
|
| 53 |
$normalized = $this->accessRulesValidator->validateAndNormalize($body['rules']); |
| 54 |
$previousUserIds = AccessRulesRoleCapabilitySynchronizer::extractUserIdsFromUserRules( |
| 55 |
$this->accessRulesRepository->getPayload()['rules'] |
| 56 |
); |
| 57 |
$this->accessRulesRepository->saveRules($normalized); |
| 58 |
AccessRulesRoleCapabilitySynchronizer::syncFromRules($normalized, $previousUserIds); |
| 59 |
|
| 60 |
return new WP_REST_Response( |
| 61 |
[ |
| 62 |
'message' => BackendStrings::getPermissionsStrings()['permissions_saved'], |
| 63 |
'rules' => $normalized, |
| 64 |
], |
| 65 |
200 |
| 66 |
); |
| 67 |
} |
| 68 |
} |
| 69 |
|