Skip to content

Commit

Permalink
Sort packages with the same weight alphabetically to have a completel…
Browse files Browse the repository at this point in the history
…y stable sort not dependent on input order, fixes #10614
  • Loading branch information
Seldaek committed Mar 15, 2022
1 parent d679532 commit 58934c6
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 24 deletions.
35 changes: 11 additions & 24 deletions src/Composer/Util/PackageSorter.php
Expand Up @@ -67,39 +67,26 @@ public static function sortPackages(array $packages)
return $weight;
};

$weightList = array();
$weightedPackages = array();

foreach ($packages as $index => $package) {
$weight = $computeImportance($package->getName());
$weightList[$index] = $weight;
$name = $package->getName();
$weight = $computeImportance($name);
$weightedPackages[] = array('name' => $name, 'weight' => $weight, 'index' => $index);
}

$stable_sort = function (&$array) {
static $transform, $restore;

$i = 0;

if (!$transform) {
$transform = function (&$v, $k) use (&$i) {
$v = array($v, ++$i, $k, $v);
};

$restore = function (&$v) {
$v = $v[3];
};
usort($weightedPackages, function ($a, $b) {
if ($a['weight'] !== $b['weight']) {
return $a['weight'] - $b['weight'];
}

array_walk($array, $transform);
asort($array);
array_walk($array, $restore);
};

$stable_sort($weightList);
return strnatcasecmp($a['name'], $b['name']);
});

$sortedPackages = array();

foreach (array_keys($weightList) as $index) {
$sortedPackages[] = $packages[$index];
foreach ($weightedPackages as $pkg) {
$sortedPackages[] = $packages[$pkg['index']];
}

return $sortedPackages;
Expand Down
14 changes: 14 additions & 0 deletions tests/Composer/Test/Util/PackageSorterTest.php
Expand Up @@ -99,6 +99,20 @@ public function sortingOrdersDependenciesHigherThanPackageDataProvider()
'foo/bar6',
),
),
'equal weight sorted alphabetically' => array(
array(
$this->createPackage('foo/bar10', array('foo/dep')),
$this->createPackage('foo/bar2', array('foo/dep')),
$this->createPackage('foo/baz', array('foo/dep')),
$this->createPackage('foo/dep', array()),
),
array(
'foo/dep',
'foo/bar2',
'foo/bar10',
'foo/baz',
),
),
);
}

Expand Down

0 comments on commit 58934c6

Please sign in to comment.