PAYATHON 2026

如何将 composer fund 输出转换为 README 的 Markdown

技术老齐

结论

Composer 2.5.5 没有内置 Markdown 输出格式,也没有公开的 composer.json hook 可供 composer fund 注册新格式。建议这样处理:

  1. 使用 composer fund --format=json 获取结构化数据。
  2. 编写一个简单的 PHP 脚本,将数据转换成 Markdown。
  3. 在 README 中加入注释标记,让脚本只替换捐赠区域。
  4. 将更新命令放入 Composer Scripts 或 CI。

默认的 text 输出用于终端展示,层级依赖换行和缩进,不适合解析。以后显示格式稍有调整,解析脚本就可能失效。JSON 的字段关系明确,更适合自动处理。

在 README 中预留生成区域

在 README.md 中加入两个标记:

## Donate

以下链接来自当前项目依赖声明的 funding 信息。

<!-- composer-fund:start -->
运行更新命令后,此处将被自动替换。
<!-- composer-fund:end -->

脚本只替换两个注释之间的内容,不会改动 README 的其他部分。不要删除标记。找不到标记时,脚本应直接报错,避免自行推断插入位置。

编写转换脚本

创建 tools/update-funding.php:

<?php

declare(strict_types=1);

$readmePath = $argv[1] ?? 'README.md';

$json = stream_get_contents(STDIN);
if ($json === false || trim($json) === '') {
    fwrite(STDERR, "没有收到 composer fund 的 JSON 输出。\n");
    exit(1);
}

$funding = json_decode($json, true);

if (json_last_error() !== JSON_ERROR_NONE || !is_array($funding)) {
    fwrite(
        STDERR,
        "无法解析 composer fund JSON:" . json_last_error_msg() . "\n"
    );
    exit(1);
}

uksort($funding, 'strnatcasecmp');

$lines = [];

foreach ($funding as $vendor => $links) {
    if (!is_array($links) || $links === []) {
        continue;
    }

    uksort($links, 'strnatcasecmp');
    $vendorLines = [];

    foreach ($links as $url => $packages) {
        if (!is_string($url) || !is_array($packages)) {
            continue;
        }

        $scheme = strtolower((string) parse_url($url, PHP_URL_SCHEME));
        if ($scheme !== 'http' && $scheme !== 'https') {
            fwrite(STDERR, "跳过非 HTTP(S) funding URL:{$url}\n");
            continue;
        }

        $packages = array_values(array_unique(array_filter(
            $packages,
            static function ($package): bool {
                return is_string($package) && $package !== '';
            }
        )));

        usort($packages, 'strnatcasecmp');

        if ($packages === []) {
            continue;
        }

        $packageNames = array_map(
            static function (string $package): string {
                return '`' . str_replace('`', '\`', $package) . '`';
            },
            $packages
        );

        // 避免 URL 中的括号破坏 Markdown 链接语法。
        $markdownUrl = str_replace(
            ['\\', '(', ')'],
            ['\\\\', '\(', '\)'],
            $url
        );

        $vendorLines[] = sprintf(
            '- %s:[捐赠链接](%s)',
            implode(', ', $packageNames),
            $markdownUrl
        );
    }

    if ($vendorLines === []) {
        continue;
    }

    $lines[] = '### ' . $vendor;
    $lines[] = '';
    foreach ($vendorLines as $vendorLine) {
        $lines[] = $vendorLine;
    }
    $lines[] = '';
}

$generated = rtrim(implode("\n", $lines));

$readme = file_get_contents($readmePath);
if ($readme === false) {
    fwrite(STDERR, "无法读取 {$readmePath}。\n");
    exit(1);
}

$pattern = '/<!-- composer-fund:start -->.*?<!-- composer-fund:end -->/s';

$replacement = "<!-- composer-fund:start -->\n"
    . $generated
    . "\n<!-- composer-fund:end -->";

$count = 0;

$updated = preg_replace_callback(
    $pattern,
    static function () use ($replacement): string {
        return $replacement;
    },
    $readme,
    1,
    $count
);

if ($updated === null) {
    fwrite(STDERR, "替换 README funding 区域时发生错误。\n");
    exit(1);
}

if ($count !== 1) {
    fwrite(
        STDERR,
        "README 中必须存在一组 composer-fund:start/end 标记。\n"
    );
    exit(1);
}

if (file_put_contents($readmePath, $updated, LOCK_EX) === false) {
    fwrite(STDERR, "无法写入 {$readmePath}。\n");
    exit(1);
}

fwrite(STDOUT, "已更新 {$readmePath} 中的 funding 信息。\n");

运行命令:

composer fund --format=json --no-ansi --no-interaction \
  | php tools/update-funding.php README.md

生成结果大致如下:

### doctrine

- `inflector`, `lexer`:[捐赠链接](https://www.doctrine-project.org/sponsorship.html)
- `inflector`, `lexer`:[捐赠链接](https://www.patreon.com/phpdoctrine)
- `inflector`:[捐赠链接](https://tidelift.com/funding/github/packagist/doctrine%2Finflector)
- `lexer`:[捐赠链接](https://tidelift.com/funding/github/packagist/doctrine%2Flexer)

### guzzlehttp

- `uri-template`:[捐赠链接](https://github.com/sponsors/GrahamCampbell)
- `uri-template`:[捐赠链接](https://github.com/sponsors/Nyholm)
- `uri-template`:[捐赠链接](https://tidelift.com/funding/github/packagist/guzzlehttp/uri-template)

同一个依赖可能声明多个 funding URL,这些 URL 可能指向不同的捐赠平台,所以脚本会全部保留。

加入 Composer Scripts

可以把命令写入项目的 composer.json:

{
    "scripts": {
        "update-funding": "composer fund --format=json --no-ansi --no-interaction | php tools/update-funding.php README.md"
    }
}

之后执行:

composer update-funding

这里的 update-funding 由项目自行定义,不属于 Composer 内置命令。

如果运行环境找不到全局 composer,可以根据项目情况改用 Composer PHAR 的路径:

{
    "scripts": {
        "update-funding": "php composer.phar fund --format=json --no-ansi --no-interaction | php tools/update-funding.php README.md"
    }
}

在 GitLab CI 中检查 README 是否过期

让 CI 自动修改并提交 README,容易形成没有实际意义的提交循环。可以让 CI 重新生成内容,然后检查文件是否有差异:

check-funding-readme:
  image: composer:2
  script:
    - composer install --no-interaction --no-progress
    - composer fund --format=json --no-ansi --no-interaction | php tools/update-funding.php README.md
    - git diff --exit-code -- README.md

如果依赖的 funding 信息已经变化,但 README 尚未更新,git diff --exit-code 会使任务失败。开发者在本地运行 composer update-funding,再提交更新结果即可。

镜像、安装参数和缓存配置需要按项目现有的 GitLab CI 环境调整。

是否需要 Composer 插件或 hook

Composer 2.5.5 的 fund 命令只支持 text 和 json 两种格式,也没有公开配置项允许项目通过 composer.json 注册 markdown 格式。

虽然可以编写 Composer Plugin 或自定义 Composer Command,但这会增加依赖,并与 Composer 的内部命令实现耦合。这里仅需转换已有的 JSON,使用独立脚本更方便审查、测试和维护。

Composer 没有附带 “fund JSON 转 Markdown” 工具。第三方工具是否存在、目前是否仍在维护,需要结合当前生态另行核实。转换逻辑只有几十行,没有必要依赖未经确认的包装包。

注意事项

  • funding 信息来自依赖包声明,链接不一定始终有效。更新 README 时,可以人工抽查新增链接。
  • 不要解析 composer fund 的 text 输出,因为它不是供程序使用的稳定数据结构。
  • 生成脚本应拒绝 http 和 https 以外的协议,避免将异常链接写入 README。
  • 建议提交生成后的 Markdown,方便浏览仓库的人直接查看捐赠列表,无需安装 Composer。
  • 依赖较多时,完整列表可能使 README 过长。可以把生成区域放到 FUNDING.md,再从 README 链接过去。
  • funding 数据会随锁定的依赖版本变化。如需保证结果可复现,应在已经执行 composer install 且 composer.lock 状态明确的环境中生成。

备注:内容仅供参考。