Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an event / plugin for Composer

I developed a portable WebServer and I'm creating a portable console too, to use Composer.

I have a problem. I need to create a plugin to add additional behavior to Composer.

I need that when downloading any package with Composer, it edits the composer.json "scripts" of that package, so that it works on the portable console.

When downloading Laravel, for example:

Original composer.json:

{
    "name": "laravel/laravel",
    ...
    "scripts": {
        "post-root-package-install": [
            "php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        ...
    },
    ...
}

composer.json edited by the plugin:

{
    "name": "laravel/laravel",
    ...
    "scripts": {
        "post-root-package-install": [
            "F:/portable_php_path/php.exe -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        ...
    },
    ...
}
  • Note that a physical path has been generated for php.exe, because in the portable version it can be in any path.

(My question is for the creation of the composer plugin. I have no problem editing the composer.json with PHP.)

I read the tutorial for creating a plugin on the composer site, but I was confused. (https://getcomposer.org/doc/articles/plugins.md)

If there is another way to do that, it's also interesting. I accept other suggestions and ideas.

Thanks to anyone who can help.

[Sorry my bad english]

like image 315
GilCarvalhoDev Avatar asked Jul 26 '17 18:07

GilCarvalhoDev


People also ask

What is a Composer plugin?

A plugin is a regular Composer package which ships its code as part of the package and may also depend on further packages.

How do I create a Composer JSON file?

To configure Composer for your PHP app json file specifies required packages. Verify that a composer. json file is present in the root of your git repository. Run composer install (on your local machine) to install the required packages and generate a composer.


1 Answers

I think you can have a plugin implements PluginInterface and EventSubscriberInterface

public static function getSubscribedEvents()
{
    return [
        'post-package-install' => 'onPostPackageInstall'
        // hook  post-package-install using onPostPackageInstall method
    ];
}

public function onPostPackageInstall(\Composer\Installer\PackageEvent $event)
{
    $vendorDir = $event->getComposer()->getConfig()->get('vendor-dir') . '/';

    /** @var InstallOperation $item */
    foreach ($event->getOperations() as $item) {

        $packageInstalled = $item->getPackage()->getName();
        // do any thing with the package name like `laravel/laravel`
        //You can now edit the composer.json file 

        echo $vendorDir . $packageInstalled . '/composer.json';

    }

}
like image 128
aristotll Avatar answered Sep 19 '22 17:09

aristotll