语义化版本号的大小比较的调整(v2.0.0 < v2.0.0-h.1)
1、参考:https://www.shuijingwanwq.com/2022/11/02/7121/ 。现在由于存在一些特殊的版本号,其并不符合语义化 2.0 的规范。最终的需求如下:v2.0.0 < v2.0.0-h.1
2、实现 v2.0.0 < v2.0.0-h.1,在执行 version_compare 后,其结果为:bool(false),即 v2.0.0 不小于 v2.0.0-h.1。
var_dump(version_compare('v2.0.0', 'v2.0.0-h.1', '<'));
3、现有的代码实现如下
$directories = glob(module_path('ThemeStoreDB') . '/Resources/setting_migrations' . '/*', GLOB_ONLYDIR); $versions = array_map(fn($directory): string => pathinfo($directory)['basename'], $directories); $availableVersions = array_filter($versions, function ($v) use ($originalThemeVersionSemantic, $themeVersionSemantic) { return version_compare($v, $originalThemeVersionSemantic, '>') && version_compare($v, $themeVersionSemantic, '<='); }); usort($availableVersions, 'version_compare'); return $availableVersions;
4、最终得到的结果如下所示
Array ( [0] => v2.0.15-h.6 [1] => v2.0.15-rc.7 [2] => v2.0.15 [3] => v2.0.16-h.2 [4] => v2.0.16-h.3 [5] => v2.0.16 [6] => v2.0.17-h.0 [7] => v2.0.20-h.1 [8] => v2.0.20 )
5、期望的结果如下所示
Array ( [0] => v2.0.15-rc.7 [1] => v2.0.15 [2] => v2.0.15-h.6 [3] => v2.0.16-h.2 [4] => v2.0.16-h.3 [5] => v2.0.16 [6] => v2.0.17-h.0 [7] => v2.0.20 [8] => v2.0.20-h.1 )
6、当2个版本之间进行比较时,如果1个版本存在 -h.,1个版本不存在 -h.,而且两者剥离掉 – 之后的子字符串之后,主版本号(例:v2.0.15)相等,则存在 -h. 的版本更大。代码实现如下
$directories = glob(module_path('ThemeStoreDB') . '/Resources/setting_migrations' . '/*', GLOB_ONLYDIR); $versions = array_map(fn($directory): string => pathinfo($directory)['basename'], $directories); $specialVersionIdentifier = '-h.'; // 特殊版本标识 $version_compare = function ($v1, $v2) use ($specialVersionIdentifier) { if (Str::contains($v1, $specialVersionIdentifier) && !Str::contains($v2, $specialVersionIdentifier) && Str::before($v1, '-') == Str::before($v2, '-')) { return 1; } elseif (!Str::contains($v1, $specialVersionIdentifier) && Str::contains($v2, $specialVersionIdentifier) && Str::before($v1, '-') == Str::before($v2, '-')) { return -1; } else { return version_compare($v1, $v2); } }; usort($versions, $version_compare); print_r($versions); exit;
7、排序后的结果如下,符合预期。如图1
Array ( [0] => v2.0.15-rc.7 [1] => v2.0.15 [2] => v2.0.15-h.6 [3] => v2.0.16 [4] => v2.0.16-h.2 [5] => v2.0.16-h.3 [6] => v2.0.17-h.0 [7] => v2.0.20 [8] => v2.0.20-h.1 )
近期评论