从composer script/composer API获取包安装路径

Jul*_*tré 4 composer-php

从Composer安装此软件包后,我想复制一个位于软件包内的文件.

实际上,我希望在安装或更新Composer中的软件包后,将一些可能位于下载软件包中的文件复制到另一个目录中.我使用脚本,使用post-package-install和post-package-update命令,但是我找不到如何获取安装路径.

这是我目前的脚本:

use Composer\Script\PackageEvent;

class MyScript {

public static function copyFiles(PackageEvent $event)
{
    $package = $event->getOperation()->getPackage();

    $originDir = $package->someFunctionToFind(); #Here, I should retrieve the install dir

    if (file_exists($originDir) && is_dir($originDir)) {
        //copy files from $originDir to a new location
    } 

}
}
Run Code Online (Sandbox Code Playgroud)

有谁知道如何从PackageEvent类(参数中提供)获取已安装/更新的软件包的安装目录?

注意 :

我尝试$event->getOperation()->getPackage->targetDir()但是这不提供安装路径,而是提供在composer.json中定义的包targetDir

Jul*_*tré 7

我可以使用Composer\Installation\InstallationManager :: getInstallPath方法获取安装路径.

理论答案:

use Composer\Script\PackageEvent;

class MyScript {

public static function copyFiles(PackageEvent $event)
{
    $package = $event->getOperation()->getPackage();
    $installationManager = $event->getComposer()->getInstallationManager();

    $originDir = $installationManager->getInstallPath($package);

    if (file_exists($originDir) && is_dir($originDir)) {
        //copy files from $originDir to a new location
    } 

}
}
Run Code Online (Sandbox Code Playgroud)

但这个答案是理论上的,因为我没有找到一个解决方案来调试我的代码而没有真正安装一个软件包(这很痛苦:我应该删除一个软件包,并重新安装它以检查我的代码).

所以我切换到post-install-cmd和post-update-cmd,然后我变成了:

use Composer\Script\CommandEvent; #the event is different !

class MyScript {

public static function copyFiles(CommandEvent $event)
{
    // wet get ALL installed packages
    $packages = $event->getComposer()->getRepositoryManager()
          ->getLocalRepository()->getPackages();
    $installationManager = $event->getComposer()->getInstallationManager();

    foreach ($packages as $package) {
         $installPath = $installationManager->getInstallPath($package);
         //do my process here
    }
}
}
Run Code Online (Sandbox Code Playgroud)

不要忘记将命令添加到composer.json:

"scripts": {

        "post-install-cmd": [
            "MyScript::copyFiles"
        ],
        "post-update-cmd": [
            "MyScript::copyFiles"
        ]
}
Run Code Online (Sandbox Code Playgroud)

为了调试代码,我不得不运行composer.phar run-script post-install-cmd.

注意:此代码应与psr4一起使用.对于psr0,可能需要添加$ package-> targetDir()以获取正确的安装路径.随意评论或改进我的答案.

  • 非常感谢您发布此信息,我已经搜索了好几天,试图整理Composer API文档。 (2认同)