rest_handle_options_request()
云策文档标注
概述
rest_handle_options_request() 是 WordPress REST API 中处理 OPTIONS 请求的函数,用于在服务器代码外部处理路由匹配,以提供路由帮助信息。
关键要点
- 函数用于处理 OPTIONS 请求,不遵循正常路由映射,在服务器代码外部执行。
- 接收参数:$response(当前响应或 null)、$handler(WP_REST_Server 实例)、$request(WP_REST_Request 实例)。
- 返回 WP_REST_Response 对象,包含修改后的响应或 null 以指示传递。
- 函数逻辑:检查响应非空或请求方法非 OPTIONS 时直接返回原响应;否则创建新 WP_REST_Response,遍历路由匹配并设置数据。
- 自 WordPress 4.4.0 版本引入。
代码示例
function rest_handle_options_request( $response, $handler, $request ) {
if ( ! empty( $response ) || $request->get_method() !== 'OPTIONS' ) {
return $response;
}
$response = new WP_REST_Response();
$data = array();
foreach ( $handler->get_routes() as $route => $endpoints ) {
$match = preg_match( '@^' . $route . '$@i', $request->get_route(), $matches );
if ( ! $match ) {
continue;
}
$args = array();
foreach ( $matches as $param => $value ) {
if ( ! is_int( $param ) ) {
$args[ $param ] = $value;
}
}
foreach ( $endpoints as $endpoint ) {
$request->set_url_params( $args );
$request->set_attributes( $endpoint );
}
$data = $handler->get_data_for_route( $route, $endpoints, 'help' );
$response->set_matched_route( $route );
break;
}
$response->set_data( $data );
return $response;
}
原文内容
Handles OPTIONS requests for the server.
Description
This is handled outside of the server code, as it doesn’t obey normal route mapping.
Parameters
$responsemixedrequired-
Current response, either response or
nullto indicate pass-through. $handlerWP_REST_Serverrequired-
ResponseHandler instance (usually WP_REST_Server).
$requestWP_REST_Requestrequired-
The request that was used to make current response.
Source
function rest_handle_options_request( $response, $handler, $request ) {
if ( ! empty( $response ) || $request->get_method() !== 'OPTIONS' ) {
return $response;
}
$response = new WP_REST_Response();
$data = array();
foreach ( $handler->get_routes() as $route => $endpoints ) {
$match = preg_match( '@^' . $route . '$@i', $request->get_route(), $matches );
if ( ! $match ) {
continue;
}
$args = array();
foreach ( $matches as $param => $value ) {
if ( ! is_int( $param ) ) {
$args[ $param ] = $value;
}
}
foreach ( $endpoints as $endpoint ) {
$request->set_url_params( $args );
$request->set_attributes( $endpoint );
}
$data = $handler->get_data_for_route( $route, $endpoints, 'help' );
$response->set_matched_route( $route );
break;
}
$response->set_data( $data );
return $response;
}
Changelog
| Version | Description |
|---|---|
| 4.4.0 | Introduced. |