rezen/proxyz

一个库,便于更改原生PHP函数的行为

1.10 2021-07-22 18:37 UTC

This package is auto-updated.

Last update: 2024-09-23 03:27:07 UTC


README

Latest Stable Version

如果您正在尝试测试PHP应用程序并想覆盖 file_get_contents 的响应,那么您将遇到很多乐趣(好吧,所以并不是很有趣)。实际上,任何与状态相关部分交互的函数都令人烦恼。PHP中有许多函数(不是对象)位于全局命名空间中,使得测试变得困难。另外,如果您正在编写WordPress插件,您将使用全局命名空间中的函数,而这些函数您无法覆盖。为了减轻一些痛苦,您需要的是方法代理。方法代理将允许您轻松地覆盖或监视全局命名空间中函数的行为。

安装

composer require rezen/proxyz

示例

在您的应用程序中,在初始化和配置事物的地方添加包装器

// Wrap around the file_get_contents method
\Proxyz\addWrapper('file_get_contents', function($args, $fn) {
    if ($args[0] === "config.json") {
        return "{}";
    }
    return call_user_func_array($fn, $args);
});

// Force curl to pin the ip down
\Proxyz\addOverride('curl_init', function($url=null) {
    if (is_null($url)) {
        return curl_init($url);
    }

    $host = parse_url($url, PHP_URL_HOST);
    $ip = gethostbyname($host);

    if (in_array($ip, ['127.0.0.1', '169.254.169.254'])) {
        throw new \Exception("Requests to internal IPs are not allowed");
    }
    $resource = curl_init($url);
    curl_setopt($resource, CURLOPT_RESOLVE, [
        "{$host}:443:{$ip}",
        "{$host}:80:{$ip}",
    ]);
    return $resource;
});

在您需要覆盖 file_get_contents 的地方,导入命名空间函数。

use function \Proxyz\Php\Filesystem\file_get_contents;
use function \Proxyz\Php\Curl\{curl_init, curl_setopt, curl_exec};

$config = file_get_contents("config.json");

需要时覆盖类!

\Proxyz\addOverride(\SplFileInfo::class, \Sample\Dance::class);
$instance = \Proxyz\newInstance(\SplFileInfo::class, [$first]);
\Sample\Dance::class === get_class($instance);

测试

composer install
# Unit tests
./vendor/bin/phpunit  -d memory_limit=1024M --testdox ./test/tests/ 

# Performance of functions
php test/performance.php 

待办事项

  • 代码重写器,用于检测原生函数并添加 use 导入
  • 改进WordPress引用
    • 目前约20+个函数有变量引用
      • ag --php '\&\$' --ignore *class* --nofilename | awk '$1=$1' | grep '^function' | grep '_' | grep -v 'tion _' | grep -v sodium | cut -d ' ' -f2 | cut -d'(' -f1 | sort | uniq
      • 函数
        • add_comment_to_entry
        • crypto_generichash_final
        • crypto_generichash_update
        • feed_start_element
        • get_page_hierarchy
        • merge_originals_with
        • merge_with
        • recurse_dirsize
        • separate_comments
        • translate_entry
        • update_page_cache
        • update_post_cache
        • update_post_caches
        • wp_add_id3_tag_data
        • wp_cache_get
        • wp_get_post_revision
        • wp_getimagesize
        • wp_handle_sideload
        • wp_handle_upload
        • wp_handle_upload_error
        • wp_kses_attr_check
        • wp_parse_str