Skip to content

Commit

Permalink
refactor: Simplify the sorting in the requirement builder (#1327)
Browse files Browse the repository at this point in the history
- Move sorting the extensions into a dedicated explicit method for
  better re-usability.
- Provide directly the whole sorted data set rather than a partially
  sorted one.
  • Loading branch information
theofidry authored Mar 10, 2024
1 parent ca6a34e commit 131c795
Showing 1 changed file with 24 additions and 14 deletions.
38 changes: 24 additions & 14 deletions src/RequirementChecker/RequirementsBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

use KevinGH\Box\Composer\Package\Extension;
use function array_diff_key;
use function array_map;
use function array_unique;
use function natsort;
use function strnatcmp;
Expand Down Expand Up @@ -53,9 +54,7 @@ public function build(): Requirements
$requirements = $this->predefinedRequirements;

foreach ($this->getSortedRequiredExtensions() as $extensionName => $sources) {
$sortedDistinctSources = self::createSortedDistinctList($sources);

foreach ($sortedDistinctSources as $source) {
foreach ($sources as $source) {
$requirements[] = Requirement::forRequiredExtension(
$extensionName,
$source,
Expand All @@ -64,9 +63,7 @@ public function build(): Requirements
}

foreach ($this->getSortedConflictedExtensions() as $extensionName => $sources) {
$sortedDistinctSources = self::createSortedDistinctList($sources);

foreach ($sortedDistinctSources as $source) {
foreach ($sources as $source) {
$requirements[] = Requirement::forConflictingExtension(
$extensionName,
$source,
Expand All @@ -82,23 +79,36 @@ public function build(): Requirements
*/
private function getSortedRequiredExtensions(): array
{
$extensions = array_diff_key(
$this->requiredExtensions,
$this->providedExtensions,
return array_map(
self::createSortedDistinctList(...),
self::sortByExtensionName(
array_diff_key(
$this->requiredExtensions,
$this->providedExtensions,
),
),
);

uksort($extensions, strnatcmp(...));

return $extensions;
}

/**
* @return array<string, list<string>>
*/
private function getSortedConflictedExtensions(): array
{
$extensions = $this->conflictingExtensions;
return array_map(
self::createSortedDistinctList(...),
self::sortByExtensionName($this->conflictingExtensions),
);
}

/**
* @template T
*
* @param array<string, T> $extensions
* @return array<string, T>
*/
private static function sortByExtensionName(array $extensions): array
{
uksort($extensions, strnatcmp(...));

return $extensions;
Expand Down

0 comments on commit 131c795

Please sign in to comment.