Lines 88.23% 15 / 17
Methods 88.88% 8 / 9
Classes 0.00% 0 / 1
Name Lines Methods CRAP
 findOrCreateSlotState 100.00% 1 / 1 100.00% 1 / 1 1
 forgetSlotState 100.00% 1 / 1 100.00% 1 / 1 1
 findSlotState 100.00% 1 / 1 100.00% 1 / 1 1
 findHandleForWorker 100.00% 1 / 1 100.00% 1 / 1 1
 listSlotStates 100.00% 3 / 3 100.00% 1 / 1 1
 listLiveHandles 100.00% 6 / 6 100.00% 1 / 1 4
 broadcast 0.00% 0 / 2 0.00% 0 / 1 6
 countSpawnedSlots 100.00% 1 / 1 100.00% 1 / 1 1
 countLiveWorkers 100.00% 1 / 1 100.00% 1 / 1 1
10final class WorkerSlotRegistry
11{
12    /** @var array<int, WorkerSlotState> */
13    private array $states = [];
14
15    public function findOrCreateSlotState(WorkerSlot $slot, WorkerPoolListener $listener): WorkerSlotState
16    {
17        return $this->states[$slot->workerId->value] ??= new WorkerSlotState($slot, $listener);
18    }
19
20    public function forgetSlotState(WorkerId $workerId): void
21    {
22        unset($this->states[$workerId->value]);
23    }
24
25    public function findSlotState(WorkerId $workerId): ?WorkerSlotState
26    {
27        return $this->states[$workerId->value] ?? null;
28    }
29
30    public function findHandleForWorker(WorkerId $workerId): ?WorkerHandle
31    {
32        return $this->findSlotState($workerId)?->handle;
33    }
34
35    /** @return list<WorkerSlotState> */
36    public function listSlotStates(): array
37    {
38        $states = $this->states;
39        ksort($states);
40
41        return array_values($states);
42    }
43
44    /** @return list<WorkerHandle> */
45    public function listLiveHandles(): array
46    {
47        $live = [];
48
49        foreach ($this->states as $state) {
50            $handle = $state->handle;
51
52            if ($handle !== null && !$handle->isTerminated()) {
53                $live[] = $handle;
54            }
55        }
56
57        return $live;
58    }
59
60    public function broadcast(BrokerMessage $message): void
61    {
62        foreach ($this->listLiveHandles() as $handle) {
63            $handle->send($message);
64        }
65    }
66
67    public function countSpawnedSlots(): int
68    {
69        return \count(array_filter($this->states, static fn(WorkerSlotState $state): bool => $state->handle !== null));
70    }
71
72    public function countLiveWorkers(): int
73    {
74        return \count($this->listLiveHandles());
75    }
76}