Phantom Watson
Phantom Watson

Reputation: 2717

How do you get the package name from a Composer event?

The Problem

I'm attempting to set up a post-update script with Composer that checks to see which package is being updated. However, I'm having trouble figuring out how to consistently get the package name from a Composer\Installer\PackageEvent.

Attempts to solve

The source code says that $packageEvent->getOperation->getReason() should return a string, but in my testing is actually returning an instance of Composer\DependencyResolver\GenericRule.

Calling Composer\DependencyResolver\Rule::getReasonData() sometimes returns a string (the package name), and sometimes returns Composer\Package\Link.

The following code mostly works to figure out the package's name:

$reasonData = $packageEvent->getOperation()->getReason()->getReasonData();
$packageName = is_string($reasonData) ? $reasonData : $reasonData->getTarget();

except sometimes $packageEvent->getOperation()->getReason() returns null.

The Question

How do you consistently get the package name from a Composer PackageEvent?

Bonus Points

How do you get the name of the package being installed/updated/etc. from all of the Composer event classes?

Upvotes: 2

Views: 1082

Answers (1)

Phantom Watson
Phantom Watson

Reputation: 2717

My mistake! Composer operations still have access to packages, just through different methods, which depend on whether the operation is an InstallOperation or an UpdateOperation. The following works:

/**
 * Returns the package name associated with $event
 *
 * @param PackageEvent $event Package event
 * @return string
 */
public static function getPackageName(PackageEvent $event)
{
    /** @var InstallOperation|UpdateOperation $operation */
    $operation = $event->getOperation();

    $package = method_exists($operation, 'getPackage')
        ? $operation->getPackage()
        : $operation->getInitialPackage();

    return $package->getName();
}

Upvotes: 4

Related Questions