Lines 100.00% 13 / 13
Functions and Methods 100.00% 2 / 2
Classes and Traits 100.00% 1 / 1
Name Lines Functions and Methods CRAP Classes and Traits
ControlTargetResolver 100.00% 13 / 13 100.00% 2 / 2 6 100.00% 1 / 1
 resolveTarget 100.00% 10 / 10 100.00% 1 / 1 4
 loadControlConfig 100.00% 3 / 3 100.00% 1 / 1 2
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\Runtime\Control\Client;
6
7use Closure;
8use Stewart\Contracts\Exception\StewartException;
9use Stewart\Runtime\Config\ControlAddress;
10use Stewart\Runtime\Config\ControlConfig;
11use Stewart\Runtime\Exception\ControlError;
12use Stewart\Runtime\Exception\ControlException;
13
14final readonly class ControlTargetResolver
15{
16    /**
17     * @param Closure(): ControlConfig $settings
18     * @throws ControlException
19     */
20    public function resolveTarget(?string $address, ?string $token, Closure $settings): ControlTarget
21    {
22        if ($address !== null && $token !== null) {
23            return new ControlTarget(ControlAddress::parse($address)->toConnectableAddress(), $token);
24        }
25
26        $control = $this->loadControlConfig($settings);
27
28        $resolvedAddress = $address === null
29            ? ($control->listen ?? throw ControlException::createForReason(ControlError::ControlDisabled))
30            : ControlAddress::parse($address);
31
32        $resolvedToken = $token
33            ?? $control->token
34            ?? throw ControlException::createForReason(ControlError::TokenMissing);
35
36        return new ControlTarget($resolvedAddress->toConnectableAddress(), $resolvedToken);
37    }
38
39    /**
40     * @param Closure(): ControlConfig $settings
41     * @throws ControlException
42     */
43    private function loadControlConfig(Closure $settings): ControlConfig
44    {
45        try {
46            return $settings();
47        } catch (StewartException $e) {
48            throw ControlException::createForReason(ControlError::ConfigUnavailable, $e);
49        }
50    }
51}