函数文档

wp_doc_link_parse()

💡 云策文档标注

概述

wp_doc_link_parse() 是一个 WordPress 函数,用于解析内容字符串并提取其中的函数名。它通过 PHP 的 token_get_all() 函数分析代码令牌,返回一个函数名数组。

关键要点

  • 参数:接受一个必需的字符串参数 $content,表示要解析的内容。
  • 返回值:返回一个字符串数组,包含从内容中提取的函数名。
  • 依赖:需要 PHP 的 token_get_all() 函数可用,否则返回空数组。
  • 过滤钩子:提供 apply_filters('documentation_ignore_functions', $ignore_functions) 钩子,允许过滤要忽略的函数和类。
  • 版本历史:自 WordPress 2.8.0 版本引入。

代码示例

function wp_doc_link_parse( $content ) {
    if ( ! is_string( $content ) || empty( $content ) ) {
        return array();
    }

    if ( ! function_exists( 'token_get_all' ) ) {
        return array();
    }

    $tokens           = token_get_all( $content );
    $count            = count( $tokens );
    $functions        = array();
    $ignore_functions = array();

    for ( $t = 0; $t < $count; $t++ ) {
        // 令牌处理逻辑(此处省略具体代码)
    }

    return $functions;
}

注意事项

  • 如果输入内容不是字符串或为空,函数直接返回空数组。
  • 函数内部使用 token_get_all() 进行令牌分析,确保 PHP 环境支持此函数。
  • 可以通过 apply_filters('documentation_ignore_functions', $ignore_functions) 钩子自定义忽略的函数列表。

📄 原文内容

Parameters

$contentstringrequired

Return

string[] Array of function names.

Source

function wp_doc_link_parse( $content ) {
	if ( ! is_string( $content ) || empty( $content ) ) {
		return array();
	}

	if ( ! function_exists( 'token_get_all' ) ) {
		return array();
	}

	$tokens           = token_get_all( $content );
	$count            = count( $tokens );
	$functions        = array();
	$ignore_functions = array();

	for ( $t = 0; $t < $count - 2; $t++ ) {
		if ( ! is_array( $tokens[ $t ] ) ) {
			continue;
		}

		if ( T_STRING === $tokens[ $t ][0] && ( '(' === $tokens[ $t + 1 ] || '(' === $tokens[ $t + 2 ] ) ) {
			// If it's a function or class defined locally, there's not going to be any docs available.
			if ( ( isset( $tokens[ $t - 2 ][1] ) && in_array( $tokens[ $t - 2 ][1], array( 'function', 'class' ), true ) )
				|| ( isset( $tokens[ $t - 2 ][0] ) && T_OBJECT_OPERATOR === $tokens[ $t - 1 ][0] )
			) {
				$ignore_functions[] = $tokens[ $t ][1];
			}

			// Add this to our stack of unique references.
			$functions[] = $tokens[ $t ][1];
		}
	}

	$functions = array_unique( $functions );
	sort( $functions );

	/**
	 * Filters the list of functions and classes to be ignored from the documentation lookup.
	 *
	 * @since 2.8.0
	 *
	 * @param string[] $ignore_functions Array of names of functions and classes to be ignored.
	 */
	$ignore_functions = apply_filters( 'documentation_ignore_functions', $ignore_functions );

	$ignore_functions = array_unique( $ignore_functions );

	$output = array();

	foreach ( $functions as $function ) {
		if ( in_array( $function, $ignore_functions, true ) ) {
			continue;
		}

		$output[] = $function;
	}

	return $output;
}

Hooks

apply_filters( ‘documentation_ignore_functions’, string[] $ignore_functions )

Filters the list of functions and classes to be ignored from the documentation lookup.

Changelog

Version Description
2.8.0 Introduced.