get_method()`) until 0.6 separates the keys. */ final class SettingsController extends Controller { public function __construct(private Store $store) {} public function routes(): array { return [ ['path' => '/settings', 'methods' => 'GET', 'callback' => [$this, 'show'], 'capability' => 'manage_options', 'args' => ['reveal' => ['type' => 'boolean', 'default' => false]]], ['path' => '/settings', 'methods' => 'PUT', 'callback' => [$this, 'update'], 'capability' => 'manage_options'], ['path' => '/settings/schema', 'methods' => 'GET', 'callback' => [$this, 'schema'], 'capability' => 'manage_options'], ]; } public function show(\WP_REST_Request $request): \WP_REST_Response { if ((bool) $request->get_param('reveal') && current_user_can('manage_options')) { $response = new \WP_REST_Response($this->store->all()); $response->header('Cache-Control', 'no-store'); return $response; } return new \WP_REST_Response($this->masked($this->store->all())); } public function update(\WP_REST_Request $request): \WP_REST_Response|\WP_Error { $input = array_intersect_key($request->get_params(), Schema::fields()); if ($input === []) { return Errors::badRequest(__('No settings were sent. Send a JSON body of dotted keys, e.g. {"models.temperature": 0.7}.', 'alpaca-bot')); } $this->store->replace($input); return new \WP_REST_Response($this->masked($this->store->all())); } /** * Schema::sections() and Schema::fields() as data: the `sanitize` callables are dropped (they * are server-side and would only serialise as a class name), a secret field is flagged * `secret` so a form renders it as a password input and knows the mask applies, and the mask * itself is named so the client compares against the same string this controller does. */ public function schema(\WP_REST_Request $request): \WP_REST_Response { $fields = []; foreach (Schema::fields() as $key => $field) { unset($field['sanitize']); if (in_array($key, Schema::SECRETS, true)) { $field['secret'] = true; } $fields[$key] = $field; } return new \WP_REST_Response(['sections' => Schema::sections(), 'fields' => $fields, 'mask' => Schema::MASK]); } /** * @param array $settings * @return array */ private function masked(array $settings): array { foreach (Schema::SECRETS as $key) { if (($settings[$key] ?? '') !== '') { $settings[$key] = Schema::MASK; } } return $settings; } }