action = $args['action']; $this->guest = $args['guest'] ?? false; $this->nonce_name = $args['nonce_name'] ?? '_wpnonce'; $this->nonce_action = $args['nonce_action'] ?? $this->action; $this->capability = $args['capability'] ?? null; $this->requestKey = $args['request_key'] ?? null; // Default Action add_action('wp_ajax_'.$this->action, [$this, 'run']); // Gust Action if ($this->guest) add_action('wp_ajax_nopriv_'.$this->action, [$this, 'run']); } public function run(): void { // Nonce is not valid if (!$this->nonce_check()) $this->response([ 'success' => 0, 'message' => esc_html__('Security nonce is invalid.', 'daytidy'), 'code' => 'NONCE_IS_INVALID', ]); // Current User is not Permitted if ($this->capability and !current_user_can($this->capability)) $this->response([ 'success' => 0, 'message' => esc_html__("You cannot access this section.", 'daytidy'), 'code' => 'NO_ACCESS' ]); // Perform Ajax Handler if ($this instanceof Interfaces\AjaxHandler) { // Prepare Data $data = $this->requestKey ? ($_REQUEST[$this->requestKey] ?? []) : $_REQUEST; if (!is_array($data)) $this->response([ 'success' => 0, 'message' => esc_html__('Invalid request data.', 'daytidy'), 'code' => 'INVALID_REQUEST_DATA', ]); if (!$this->requestKey) unset($data['action'], $data[$this->nonce_name]); $data = Input::sanitize(wp_unslash($data)); // Validate Request $validation = $this->validate($data); // Validation Failed if (!$validation->validRequest()) { $errors = array_unique($validation->errors()); $message = Html::listify($errors, count($errors) > 1 ? 'ol' : 'ul'); $result = AjaxResult::failure($message); } else { // Do the Action $result = $this->perform($data); } // Response $this->response($result->response()); } // Response $this->response([ 'success' => 0, 'message' => esc_html__("Unknown error.", 'daytidy'), 'code' => 'UNKNOWN_ERROR' ]); } /** * @param mixed[] $data * @return void */ protected function response(array $data): void { wp_send_json($data); } }