> $endpoints Endpoints: methods, callback, permission, args. */ protected function route( string $path, array $endpoints ): void { $list = array(); foreach ( $endpoints as $endpoint ) { $callback = $endpoint['callback']; $list[] = array( 'methods' => $endpoint['methods'], 'callback' => static fn( WP_REST_Request $request ) => self::run( $callback, $request ), 'permission_callback' => $endpoint['permission'], 'args' => $endpoint['args'] ?? array(), ); } register_rest_route( self::NAMESPACE, $path, $list ); } /** * Call a callback and turn what it throws into an error response. * * @param callable $callback Callback. * @param WP_REST_Request $request Request. * @return WP_REST_Response|WP_Error */ private static function run( callable $callback, WP_REST_Request $request ) { try { $result = $callback( $request ); return $result instanceof WP_REST_Response || $result instanceof WP_Error ? $result : rest_ensure_response( $result ); } catch ( BookingException $e ) { return $e->to_error(); } catch ( InvalidArgumentException $e ) { return new WP_Error( 'schedulereed_invalid', $e->getMessage(), array( 'status' => 400 ) ); } } /** * A JSON body or the request's parameters. * * @param WP_REST_Request $request Request. * @return array */ protected static function body( WP_REST_Request $request ): array { $json = $request->get_json_params(); return is_array( $json ) ? $json : $request->get_params(); } public function can_manage(): bool { return Capabilities::can_manage(); } public function can_desk(): bool { return Capabilities::can_desk(); } public function can_settings(): bool { return Capabilities::can_settings(); } public function can_enter(): bool { return Capabilities::can_enter(); } /** * A path argument that must be a positive whole number. * * @return array> */ protected static function id_arg(): array { return array( 'id' => array( 'type' => 'integer', 'required' => true, 'minimum' => 1, ), ); } /** * Limit how often one visitor may call a public route. * * @param string $bucket What is being limited. * @param int $limit Calls per window. * @param int $window Seconds. * @throws \ScheduleReed\Booking\BookingException When over the limit. */ protected static function throttle( string $bucket, int $limit, int $window = MINUTE_IN_SECONDS ): void { if ( Capabilities::can_enter() ) { return; } $ip = isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : ''; $key = 'schedulereed_rl_' . md5( $bucket . '|' . $ip ); $n = (int) get_transient( $key ); if ( $n >= $limit ) { // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Returned as JSON. throw new BookingException( 'schedulereed_slow_down', __( 'Too many tries. Please wait a minute and try again.', 'schedulereed' ), 429 ); } set_transient( $key, $n + 1, $window ); } }