<?php
|
namespace JVBase\rest\routes;
|
|
use JVBase\registrar\Registrar;
|
use JVBase\rest\PermissionHandler;
|
use JVBase\rest\Rest;
|
use JVBase\managers\Cache;
|
use JVBase\meta\Meta;
|
use JVBase\rest\Route;
|
use WP_REST_Request;
|
use WP_REST_Response;
|
use WP_Error;
|
|
if (!defined('ABSPATH')) {
|
exit; // Exit if accessed directly
|
}
|
|
class OptionsRoutes extends Rest
|
{
|
|
public function __construct()
|
{
|
parent::__construct();
|
add_filter(BASE.'handle_bulk_operation', [$this, 'processOperation'], 10, 3);
|
}
|
|
public function registerRoutes():void
|
{
|
Route::for('options')
|
->post([$this, 'saveOptions'])
|
->auth(PermissionHandler::combine(['user', ['actionNonce' => 'dash-']]))
|
->rateLimit(3)
|
->args([
|
'user' => 'int|required',
|
'id' => 'string|required',
|
])
|
->register();
|
}
|
|
public function saveOptions(WP_REST_Request $request):WP_REST_Response
|
{
|
$data = $request->get_params();
|
$user = $data['user'];
|
if ($user && !user_can($user, 'manage_options')) {
|
return $this->error('User Cannot modify options');
|
}
|
unset($data['user']);
|
$operationID = $data['id'];
|
unset($data['id']);
|
|
JVB()->queue()->queueOperation(
|
'update_options',
|
$user,
|
$data,
|
[
|
'operation_id' =>$operationID,
|
'priority' => 'high',
|
]
|
);
|
|
return $this->queued($operationID);
|
}
|
|
|
/**
|
* @param WP_Error|array $result
|
* @param object $operation
|
* @param array $data
|
*
|
* @return WP_Error|array
|
*/
|
public function processOperation(WP_Error|array $result, object $operation, array $data):array|WP_Error
|
{
|
if ($operation->type != 'update_options') {
|
return $result;
|
}
|
|
error_log('Saving changes: '.print_r($data, true));
|
$results = [
|
'errors' => [],
|
'success' => []
|
];
|
|
$meta = Meta::forOptions('options');
|
$fields = Registrar::getFieldsFor('options');
|
|
$allowedFields = array_filter($data,
|
function ($key) use ($fields) {
|
return array_key_exists($key, $fields);
|
}, ARRAY_FILTER_USE_KEY);
|
error_log('Setting fields: '.print_r($allowedFields, true));
|
$results = $meta->setAll($allowedFields);
|
// foreach ($data as $field => $value) {
|
// if (array_key_exists($field, $fields)) {
|
// $success = $meta->updateValue($field, $value);
|
// if ($success) {
|
// $results['success'][] = $field;
|
// } else {
|
// $results['errors'][] = $field;
|
// }
|
// }
|
// }
|
|
do_action('jvbOptionsRoute', $data);
|
|
$cache = Cache::for('options', 1800);
|
$cache->flush();
|
return [
|
'success' => true,
|
'result' => $results
|
];
|
}
|
}
|