John Davidson

composer php - Parsing package versions with wildcards for comparison in PHP

0 comments
Message:


I am trying to compare the package version such as ^6.1||^6.2||^6.3 using \Composer\Semver\VersionParser but am not getting the expected result.


I am breaking down the version like so


            $currentVersion = '6.3';
$requiredPackage = '^6.1||^6.2||^6.3';
$compatibleVersions = explode('||', $requiredPackage);
$lowestSupported = ltrim(current($compatibleVersions), '^');
$highestSupported = ltrim(end($compatibleVersions), '^');

$parser = new VersionParser();
$lowestSupported = $parser->normalize($lowestSupported);
$highestSupported = $parser->normalize($highestSupported);

$isLower = version_compare($currentVersion, $lowestSupported, '<');
$isHigher = version_compare($currentVersion, $highestSupported, '>');

if ($isLower || $isHigher) {
return false;
}

This works fine for cases where $currentVersion is 6.3, but I think it would fail for 6.3.4.0 because although ^6.3 matches the package, but since VersionParser normalizes the version 6.3 as 6.3.0.0 instead, and it cannot parse the ^6.3 correctly to allow 6.3.4.0.


Any ideas?



My Answer:
One way to handle this issue is to manually check if the current version falls within the range specified by the required package version. Here's an example of how you can do this:

php
$currentVersion = '6.3.4.0';
$requiredPackage = '^6.1||^6.2||^6.3';
$compatibleVersions = explode('||', $requiredPackage);

foreach ($compatibleVersions as $version) {
$version = ltrim($version, '^');
$parsedVersion = $parser->normalize($version);

if (version_compare($currentVersion, $parsedVersion, '>=') && version_compare($currentVersion, $parsedVersion, '<')) {
return true;
}
}

return false;


In this code snippet, we loop through each compatible version in the required package and manually compare the current version with the normalized version of each compatible version. If the current version falls within the range specified by any of the compatible versions, we return true. Otherwise, we return false.

This approach should handle cases where the current version has additional version segments (e.g., 6.3.4.0) and still correctly determine if it matches the required package version.

Rate this post

4 of 5 based on 8751 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us