<?php
|
namespace JVBase\rest\routes;
|
|
use JVBase\JVB;
|
use JVBase\rest\RestRouteManager;
|
use JVBase\managers\Cache;
|
use JVBase\meta\MetaManager;
|
use JVBase\meta\MetaSanitizer;
|
use WP_REST_Request;
|
use WP_REST_Response;
|
use WP_Error;
|
use Exception;
|
|
if (!defined('ABSPATH')) {
|
exit; // Exit if accessed directly
|
}
|
|
class OptionsRoutes extends RestRouteManager
|
{
|
|
public function __construct()
|
{
|
parent::__construct();
|
$this->action = 'dash-';
|
add_filter(BASE.'handle_bulk_operation', [$this, 'processOperation'], 10, 3);
|
}
|
|
public function registerRoutes()
|
{
|
register_rest_route($this->namespace, '/options', [
|
[
|
'methods' => 'POST',
|
'callback' => [$this, 'saveOptions'],
|
'permission_callback' => [$this, 'checkPermission']
|
]
|
]);
|
}
|
|
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 new WP_REST_Response([
|
'success' => 'false',
|
'message' => 'User cannot modify options'
|
]);
|
}
|
unset($data['user']);
|
$operationID = $data['id'];
|
unset($data['id']);
|
$queue = JVB()->queue();
|
$queue->queueOperation(
|
'update_options',
|
$user,
|
$data,
|
[
|
'operation_id' =>$operationID,
|
'priority' => 'high',
|
]
|
);
|
|
|
return new WP_REST_Response([
|
'success' => 'true',
|
'message' => 'Probably'
|
]);
|
}
|
|
|
/**
|
* @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 = new MetaManager(null, 'options');
|
$fields = jvbGetFields('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
|
];
|
}
|
}
|