函数文档

_preload_old_requests_classes_and_interfaces()

💡 云策文档标注

概述

此函数用于在WordPress升级过程中,预加载旧版Requests库的类和接口到内存中,以防止因文件删除或替换导致的致命错误。它通过检查版本和文件存在性,确保兼容性和稳定性。

关键要点

  • 预加载旧版Requests类和接口,避免升级时因代码缺失或不兼容引发致命错误。
  • 仅当WordPress版本为4.6及以上时执行预加载,因为Requests库从4.6版本引入。
  • 函数参数$to指定旧WordPress安装的路径,用于定位Requests文件。
  • 通过遍历$_old_requests_files数组,跳过非类/接口文件、已加载项和缺失文件,使用require_once加载有效文件。

代码示例

function _preload_old_requests_classes_and_interfaces( $to ) {
    global $_old_requests_files, $wp_filesystem, $wp_version;

    if ( version_compare( $wp_version, '4.6', '<' ) ) {
        return;
    }

    foreach ( $_old_requests_files as $name => $file ) {
        if ( is_int( $name ) ) {
            continue;
        }

        if ( class_exists( $name ) || interface_exists( $name ) ) {
            continue;
        }

        if ( ! $wp_filesystem->is_file( $to . $file ) ) {
            continue;
        }

        require_once $to . $file;
    }
}

注意事项

  • 此函数在WordPress 6.2.0版本中引入,主要用于update_core()函数中,以支持核心升级过程。
  • 预加载依赖于全局变量$_old_requests_files,该数组应包含旧Requests库的类和接口文件列表。
  • 确保$wp_filesystem已正确初始化,以便检查文件是否存在。

📄 原文内容

Preloads old Requests classes and interfaces.

Description

This function preloads the old Requests code into memory before the upgrade process deletes the files. Why? Requests code is loaded into memory via an autoloader, meaning when a class or interface is needed If a request is in process, Requests could attempt to access code. If the file is not there, a fatal error could occur. If the file was replaced, the new code is not compatible with the old, resulting in a fatal error. Preloading ensures the code is in memory before the code is updated.

Parameters

$tostringrequired
Path to old WordPress installation.

Source

function _preload_old_requests_classes_and_interfaces( $to ) {
	global $_old_requests_files, $wp_filesystem, $wp_version;

	/*
	 * Requests was introduced in WordPress 4.6.
	 *
	 * Skip preloading if the website was previously using
	 * an earlier version of WordPress.
	 */
	if ( version_compare( $wp_version, '4.6', '<' ) ) {
		return;
	}

	if ( ! defined( 'REQUESTS_SILENCE_PSR0_DEPRECATIONS' ) ) {
		define( 'REQUESTS_SILENCE_PSR0_DEPRECATIONS', true );
	}

	foreach ( $_old_requests_files as $name => $file ) {
		// Skip files that aren't interfaces or classes.
		if ( is_int( $name ) ) {
			continue;
		}

		// Skip if it's already loaded.
		if ( class_exists( $name ) || interface_exists( $name ) ) {
			continue;
		}

		// Skip if the file is missing.
		if ( ! $wp_filesystem->is_file( $to . $file ) ) {
			continue;
		}

		require_once $to . $file;
	}
}

Changelog

Version Description
6.2.0 Introduced.