WP_Translation_File_PHP
云策文档标注
概述
WP_Translation_File_PHP 是 WordPress 中用于处理 PHP 翻译文件的类,继承自 WP_Translation_File,提供解析、导出和变量表示功能。
关键要点
- 类 WP_Translation_File_PHP 扩展自 WP_Translation_File,专门处理 PHP 格式的翻译文件。
- 包含三个主要方法:parse_file() 用于解析文件,export() 用于导出翻译内容为字符串,var_export() 用于生成可解析的变量表示。
- parse_file() 方法从文件中提取消息和头部信息,export() 方法合并头部和条目并输出,var_export() 方法优化数组输出为短语法。
代码示例
protected function parse_file() {
$this->parsed = true;
$result = include $this->file;
if ( ! $result || ! is_array( $result ) ) {
$this->error = 'Invalid data';
return;
}
if ( isset( $result['messages'] ) && is_array( $result['messages'] ) ) {
foreach ( $result['messages'] as $original => $translation ) {
$this->entries[ (string) $original ] = $translation;
}
unset( $result['messages'] );
}
$this->headers = array_change_key_case( $result );
}注意事项
- parse_file() 方法在文件无效或非数组时会设置错误信息。
- var_export() 方法使用短数组语法且无换行,以提高输出效率。
- 此类自 WordPress 6.5.0 版本引入。
原文内容
Class WP_Translation_File_PHP.
Methods
| Name | Description |
|---|---|
| WP_Translation_File_PHP::export | Exports translation contents as a string. |
| WP_Translation_File_PHP::parse_file | Parses the file. |
| WP_Translation_File_PHP::var_export | Outputs or returns a parsable string representation of a variable. |
Source
class WP_Translation_File_PHP extends WP_Translation_File {
/**
* Parses the file.
*
* @since 6.5.0
*/
protected function parse_file() {
$this->parsed = true;
$result = include $this->file;
if ( ! $result || ! is_array( $result ) ) {
$this->error = 'Invalid data';
return;
}
if ( isset( $result['messages'] ) && is_array( $result['messages'] ) ) {
foreach ( $result['messages'] as $original => $translation ) {
$this->entries[ (string) $original ] = $translation;
}
unset( $result['messages'] );
}
$this->headers = array_change_key_case( $result );
}
/**
* Exports translation contents as a string.
*
* @since 6.5.0
*
* @return string Translation file contents.
*/
public function export(): string {
$data = array_merge( $this->headers, array( 'messages' => $this->entries ) );
return 'var_export( $data ) . ';' . PHP_EOL;
}
/**
* Outputs or returns a parsable string representation of a variable.
*
* Like <a href="https://developer.wordpress.org/reference/functions/var_export/">var_export()</a> but "minified", using short array syntax
* and no newlines.
*
* @since 6.5.0
*
* @param mixed $value The variable you want to export.
* @return string The variable representation.
*/
private function var_export( $value ): string {
if ( ! is_array( $value ) ) {
return var_export( $value, true );
}
$entries = array();
$is_list = array_is_list( $value );
foreach ( $value as $key => $val ) {
$entries[] = $is_list ? $this->var_export( $val ) : var_export( $key, true ) . '=>' . $this->var_export( $val );
}
return '[' . implode( ',', $entries ) . ']';
}
}
Changelog
| Version | Description |
|---|---|
| 6.5.0 | Introduced. |