Lines 100.00% 26 / 26
Methods 100.00% 2 / 2
Classes 100.00% 1 / 1
Name Lines Methods CRAP
 resolveCatalog 100.00% 23 / 23 100.00% 1 / 1 13
 assertSelectedAppsExist 100.00% 3 / 3 100.00% 1 / 1 3
14final readonly class AppCatalogResolver
15{
16    /** @throws ConfigurationException */
17    public function resolveCatalog(DiscoveryResult $discovered, AppOverrideCollection $overrides, int $workers, AppSelection $selection = new AppSelection()): AppCatalog
18    {
19        $knownIds = $discovered->apps->listAppIds();
20        $unmatchedOverrideIds = [];
21
22        $this->assertSelectedAppsExist('--only', $selection->onlyIds, $knownIds);
23        $this->assertSelectedAppsExist('--trace', $selection->tracedIds, $knownIds);
24
25        foreach ($overrides as $override) {
26            if ($knownIds->findFirstWhere(static fn(AppId $known): bool => $known->collidesWith($override->id)) === null) {
27                $unmatchedOverrideIds[] = $override->id;
28            }
29        }
30
31        $enabled = [];
32
33        foreach ($discovered->apps as $app) {
34            $override = $overrides->findMatchingApp($app->id);
35
36            if (!$selection->admitsApp($app->id, $override === null || $override->enabled)) {
37                continue;
38            }
39
40            $worker = $override?->worker;
41
42            if ($worker !== null && $workers > 0 && $worker >= $workers) {
43                throw ConfigurationException::workerIndexOutOfRange($app->id, $worker, $workers);
44            }
45
46            $enabled[] = new AppDefinition(
47                id: $app->id,
48                class: $app->class,
49                options: $override === null ? [] : $override->options,
50                worker: $worker,
51                startsPaused: $override !== null && $override->paused,
52                verbosity: new AppVerbosity($override?->logLevel, ($override !== null && $override->trace) || $selection->tracesApp($app->id)),
53            );
54        }
55
56        return new AppCatalog(AppDefinitionCollection::keyedByAppId($enabled), $knownIds, AppIdCollection::fromList($unmatchedOverrideIds));
57    }
58
59    /** @throws ConfigurationException */
60    private function assertSelectedAppsExist(string $option, ?AppIdCollection $selectedIds, AppIdCollection $knownIds): void
61    {
62        foreach ($selectedIds ?? [] as $selectedId) {
63            if (!$knownIds->containsId($selectedId)) {
64                throw ConfigurationException::appSelectionUnknown($option, $selectedId, $knownIds);
65            }
66        }
67    }
68}