user1406347
user1406347

Reputation: 73

Composer, Read package version number programmatically

For a Symfony based console application, I need to read the it's version number from it's composer file (not branch alias), programmatically.

Manually, I can use the composer show -s to get the root package information, but there does not seem to be any command to to get the clean version of my package.

The purpose is to automatically display the installed package version, when running the application, without having to deal with *.txt files or other file-based ways that contain a semantic version number.

Sadly I am not familiar with composer's architecture, so I have no idea what components I can use to achieve this.

Any ideas or perhaps already made packages that solves is mostly welcome.

Upvotes: 2

Views: 1990

Answers (2)

Rafael Ortega Bueno
Rafael Ortega Bueno

Reputation: 147

Install Composer in your project

composer require composer/composer --dev

example.php

<?php
// Include Composer Autoload
require __DIR__ . '/vendor/autoload.php';

use Composer\Factory;
use Composer\IO\NullIO;

$composer = Factory::create(new NullIo(), './composer.json', false);
$localRepo = $composer->getRepositoryManager()->getLocalRepository();

foreach ($localRepo->getPackages() as $package) {
    echo $package->getName() . PHP_EOL;
    echo $package->getVersion() . PHP_EOL;
    echo $package->getType() . PHP_EOL;
    // ...
}

Upvotes: 5

Cerlin
Cerlin

Reputation: 6722

I know its kinda late reply but you can read the info from a JSON file which is written by composer.

the file is located at vendor/composer/installed.json.

Read the JSON, parse it, and get the info you want.

This package does that some what.

Upvotes: 4

Related Questions