在Composer中使用变量

时间:2018-12-31 16:59:46

标签: php composer-php

在我的composer.json文件中,我有以下内容:

"repositories": [        
    {
        "type": "package",
        "package": {
            "name": "aaemnnosttv/wordpress-core-phpunit-includes",
            "type": "wordpress-tests-core",
            "version": "5.0.2",
            "source": {
                "type": "svn",
                "url": "https://develop.svn.wordpress.org/",
                "reference": "tags/5.0.2/tests/phpunit/includes/"
            },
            "require": {
                "aaemnnosttv/wordpress-tests-core-installer": "~0.1"
            }
        }
    }
],
"require": {
    "aaemnnosttv/wordpress-core-phpunit-includes": "5.0.2"
}

不幸的是,我不得不重复说明软件包的版本。一次在“版本”行中,一次在“参考”行中,一次在“ aaemnnosttv / wordpress-core-phpunit-includes”行中。

有没有一种方法可以使用composer变量,这样我就不必重复自己了?

1 个答案:

答案 0 :(得分:1)

composer文件为json,并且 JSON不允许变量引用。

但是由于您在问题中使用PHP标记,我建议使用一个示例来处理它,也许它可以为您提供帮助。

创建php文件以设置作曲家环境的数组。

$variable = "aaemnnosttv/wordpress-core-phpunit-includes";
$version = "5.0.2";
$composer = [
    "repositories" => [
        [
            "type" => "package",
            "package" => [
                "name" => $variable
                // whatever is in
            ]
        ]
    ],
    "require"=>[
            $variable => $version
    ]
];

然后将数组另存为json在 composer.json 文件中。

file_put_contents('compose.josn', json_encode($composer));

如果您只想编辑作曲家文件,则必须阅读并进行编辑:

$composer = json_decode(file_get_contents('compose.josn', true));

$variable = "aaemnnosttv/wordpress-core-phpunit-includes";
$version = "5.0.2";
$composer["repositories"][0]["package"]["name"] = $variable;
$composer["require"][$variable] = $version;