PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, March 1, 2022

[FIXED] Get version of Composer package(s) in PHP, without using the command line

 March 01, 2022     composer-php, php     No comments   

Issue

Is there a way to get the version for a package installed with Composer, and which is currently used by an application, without invoking composer show -i or anything similar?

I want to determinate the versions currently used by the application and and show an alert if some packages need to be updated, and eventually auto update.


Solution

For the current task, I think the appropriate solution will be the following.

Composer creates a installed.json file under vendor/composer, which contains all the information about the installed packages, as they are defined.

The file looks something similar to this.

[
    {
        "name": "vendor_X/package_Y",
        "version": "1.0.0",
        "version_normalized": "1.1.0.0",
        "source": {},
        "dist": {},
        "require": {},
        "require-dev": {},
        other data about the package
    },
    {"..other package's data..": ""},
    {"...": ""}
]

A simple solution will be using the following code.

$data = array();
$packages = json_decode(file_get_contents('../vendor/composer/installed.json'));
 // Assuming that the project root is one level above the web root.
foreach ($packages as $package) {
    $data[$package['name']] = $package['version'];
}
    
// Make a cURL request to packagist.org to get the package data
// https://packagist.org/packages/vendor_X/package_Y.json
// The output is something like the following
/*
{
    "package": {
        "name": "omnipay/dummy",
        "versions": {
            "dev-master": {},
            "v1.1.0": {},
            "v1.0.0": {}
        },
        "type": "library",
    }
}
*/

$packagist = json_decode($packagist_reponse_as_json);
if (strcmp($data['vendor_X/package_Y'], $packagist['package']['versions'][1]) < 0) {
  // Fire a composer update, send email alert, show notification, or call the president.
}

The solution above is the simplest and a little ugly, but it shows the key points, namely, where to get local versions for packages and how to get the package versions from Composer.
A more practical solution should employ caching and should not be done during normal application operation; a better solution would be using a cron job.



Answered By - DaGhostman Dimitrov
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing