6

I wonder if there is a way to get the composer.json version from a controller with Symfony. My composer.json looks like:

{
    "name": "myProject",
    "version": "0.0.0",
    "description": "myProject description",
    "license": "AGPL-3.0",
    "type": "project",
    "require": {
        "php": "^7.1.3",
        ...
    }
}

I can't find any reference to this.

PS: I'm using Symfony 4.

1
  • What have you tried so far? Where are you stuck? Usually, this is a common JSON file which can be parsed like any other
    – Nico Haase
    Commented Dec 11, 2020 at 19:57

5 Answers 5

7

You can do something like this:

$filename = $this->getParameter('%app.kernel_dir%') . '/../composer.json';
$composerData = json_decode(file_get_contents($filename), true);

$version = $composerData['version'];

The variable should then containv the value 0.0.0 from your example.

This assumes that your controller extends the base Controller to access the %app.kernel_dir% parameter. If not, you could just as well use the relative path from your controller or something else to determine the location of the composer.json

3

Without packages, with Composer you can use $version = \Composer\InstalledVersions::getPrettyVersion('package/package-name')

2

You can use the PackageVersions library and its relative PrettyPackageVersions.

They provide a single class API to get the currently installed version of your Composer dependencies, for example:

use PackageVersions\Versions;
use Jean85\PrettyVersions;

// Will output "1.0.0@0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33"
echo Versions::getVersion('myvendor/mypackage');

// Will output "1.0.0"
echo (string) PrettyVersions::getVersion('myvendor/mypackage');
2

Reffering Salam answer, you can also get own project (named root package in composer world) version stored in composer.json by:

$version = \Composer\InstalledVersions::getRootPackage()['version'];

or for prettier print:

$version = \Composer\InstalledVersions::getRootPackage()['pretty_version'];
1

In Symfony 6 u have to do the following 3 Steps:

  1. Create global Variable in packages/twig.yaml and reference a Service as Value

twig:
    globals:
        composer_version: '@App\Helper\ComposerVersion'

  1. Create (Service) App\Helper\ComposerVersion:

namespace App\Helper;

use Composer\InstalledVersions;

class ComposerVersion
{
    public static function getVersion(): string
    {
        return InstalledVersions::getRootPackage()['pretty_version'];
    }

    public function __toString(): string
    {
        return self::getVersion();
    }
}

  1. Use in twig Template:

<div>{{ composer_version }}</div>

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.