Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Return package version dynamically from Composer 2
<?php
declare(strict_types=1);
namespace MyNamespace;
use Composer\InstalledVersions;
/**
* Simple class to return package version from Composer 2
*
* Replace PACKAGE constant with your Composer package name
*/
final class Version
{
const PACKAGE = 'your-organisation/package-name';
/**
* Return current version of package
*
* Requires Composer 2, or returns null if not found
*
* @return string|null
*/
public static function getVersion(): ?string
{
if (class_exists('\Composer\InstalledVersions')) {
if (InstalledVersions::isInstalled(self::PACKAGE)) {
return InstalledVersions::getPrettyVersion(self::PACKAGE);
}
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment