WP_URL_Pattern_Prefixer
云策文档标注
概述
WP_URL_Pattern_Prefixer 是一个用于为 URL 路径模式添加前缀的类,主要应用于推测性加载功能。它通过处理不同上下文(如 home、site 等)的基础路径,确保路径模式在子目录站点(如多站点网络或 WordPress 安装在子目录时)中正确工作。
关键要点
- 类 WP_URL_Pattern_Prefixer 用于前缀化 URL 路径模式,支持多种上下文(如 home、site、uploads 等)。
- 核心方法 prefix_path_pattern 根据给定上下文为路径模式添加前缀,并处理特殊字符(如 :、?、#)的转义。
- 提供静态方法 get_default_contexts 返回默认上下文映射,以及私有静态方法 escape_pattern_string 用于转义字符串以符合 URL 模式规范。
- 构造函数接受可选的上下文数组,若无提供则使用默认上下文,并自动应用转义和尾部斜杠处理。
- 在无效上下文时,prefix_path_pattern 方法会触发 _doing_it_wrong 警告并返回原始路径模式。
代码示例
// 示例:使用 WP_URL_Pattern_Prefixer 为路径模式添加前缀
$prefixer = new WP_URL_Pattern_Prefixer();
$pattern = '/example/path';
$prefixed_pattern = $prefixer->prefix_path_pattern($pattern, 'home');
// 输出:根据 home 上下文的基础路径前缀化后的模式注意事项
- 确保上下文字符串在 contexts 数组中定义,否则 prefix_path_pattern 会触发警告。
- 路径模式应仅包含路径部分,前缀添加时会自动处理尾部斜杠和特殊字符转义。
- 此类自 WordPress 6.8.0 版本引入,主要用于推测性加载功能,开发者需注意版本兼容性。
原文内容
Class for prefixing URL patterns.
Description
This class is intended primarily for use as part of the speculative loading feature.
Methods
| Name | Description |
|---|---|
| WP_URL_Pattern_Prefixer::__construct | Constructor. |
| WP_URL_Pattern_Prefixer::escape_pattern_string | Escapes a string for use in a URL pattern component. |
| WP_URL_Pattern_Prefixer::get_default_contexts | Returns the default contexts used by the class. |
| WP_URL_Pattern_Prefixer::prefix_path_pattern | Prefixes the given URL path pattern with the base path for the given context. |
Source
class WP_URL_Pattern_Prefixer {
/**
* Map of `$context_string => $base_path` pairs.
*
* @since 6.8.0
* @var array<string, string>
*/
private $contexts;
/**
* Constructor.
*
* @since 6.8.0
*
* @param array<string, string> $contexts Optional. Map of `$context_string => $base_path` pairs. Default is the
* contexts returned by the
* <a href="https://developer.wordpress.org/reference/classes/WP_URL_Pattern_Prefixer/get_default_contexts/">WP_URL_Pattern_Prefixer::get_default_contexts()</a> method.
*/
public function __construct( array $contexts = array() ) {
if ( count( $contexts ) > 0 ) {
$this->contexts = array_map(
static function ( string $str ): string {
return self::escape_pattern_string( trailingslashit( $str ) );
},
$contexts
);
} else {
$this->contexts = self::get_default_contexts();
}
}
/**
* Prefixes the given URL path pattern with the base path for the given context.
*
* This ensures that these path patterns work correctly on WordPress subdirectory sites, for example in a multisite
* network, or when WordPress itself is installed in a subdirectory of the hostname.
*
* The given URL path pattern is only prefixed if it does not already include the expected prefix.
*
* @since 6.8.0
*
* @param string $path_pattern URL pattern starting with the path segment.
* @param string $context Optional. Context to use for prefixing the path pattern. Default 'home'.
* @return string URL pattern, prefixed as necessary.
*/
public function prefix_path_pattern( string $path_pattern, string $context = 'home' ): string {
// If context path does not exist, the context is invalid.
if ( ! isset( $this->contexts[ $context ] ) ) {
_doing_it_wrong(
__FUNCTION__,
esc_html(
sprintf(
/* translators: %s: context string */
__( 'Invalid URL pattern context %s.' ),
$context
)
),
'6.8.0'
);
return $path_pattern;
}
/*
* In the event that the context path contains a :, ? or # (which can cause the URL pattern parser to switch to
* another state, though only the latter two should be percent encoded anyway), it additionally needs to be
* enclosed in grouping braces. The final forward slash (trailingslashit ensures there is one) affects the
* meaning of the * wildcard, so is left outside the braces.
*/
$context_path = $this->contexts[ $context ];
$escaped_context_path = $context_path;
if ( strcspn( $context_path, ':?#' ) !== strlen( $context_path ) ) {
$escaped_context_path = '{' . substr( $context_path, 0, -1 ) . '}/';
}
/*
* If the path already starts with the context path (including '/'), remove it first
* since it is about to be added back.
*/
if ( str_starts_with( $path_pattern, $context_path ) ) {
$path_pattern = substr( $path_pattern, strlen( $context_path ) );
}
return $escaped_context_path . ltrim( $path_pattern, '/' );
}
/**
* Returns the default contexts used by the class.
*
* @since 6.8.0
*
* @return array<string, string> Map of `$context_string => $base_path` pairs.
*/
public static function get_default_contexts(): array {
return array(
'home' => self::escape_pattern_string( trailingslashit( (string) wp_parse_url( home_url( '/' ), PHP_URL_PATH ) ) ),
'site' => self::escape_pattern_string( trailingslashit( (string) wp_parse_url( site_url( '/' ), PHP_URL_PATH ) ) ),
'uploads' => self::escape_pattern_string( trailingslashit( (string) wp_parse_url( wp_upload_dir( null, false )['baseurl'], PHP_URL_PATH ) ) ),
'content' => self::escape_pattern_string( trailingslashit( (string) wp_parse_url( content_url(), PHP_URL_PATH ) ) ),
'plugins' => self::escape_pattern_string( trailingslashit( (string) wp_parse_url( plugins_url(), PHP_URL_PATH ) ) ),
'template' => self::escape_pattern_string( trailingslashit( (string) wp_parse_url( get_stylesheet_directory_uri(), PHP_URL_PATH ) ) ),
'stylesheet' => self::escape_pattern_string( trailingslashit( (string) wp_parse_url( get_template_directory_uri(), PHP_URL_PATH ) ) ),
);
}
/**
* Escapes a string for use in a URL pattern component.
*
* @since 6.8.0
* @see https://urlpattern.spec.whatwg.org/#escape-a-pattern-string
*
* @param string $str String to be escaped.
* @return string String with backslashes added where required.
*/
private static function escape_pattern_string( string $str ): string {
return addcslashes( $str, '+*?:{}()\' );
}
}
Changelog
| Version | Description |
|---|---|
| 6.8.0 | Introduced. |