Lines 93.75% 60 / 64
Functions and Methods 75.00% 6 / 8
Classes and Traits 0.00% 0 / 1
Name Lines Functions and Methods CRAP Classes and Traits
AppOptionResolver 93.75% 60 / 64 75.00% 6 / 8 34.28 0.00% 0 / 1
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 resolveOptionArguments 100.00% 27 / 27 100.00% 1 / 1 8
 listConstructorParameters 100.00% 4 / 4 100.00% 1 / 1 2
 needsExplicitValue 100.00% 5 / 5 100.00% 1 / 1 5
 hasAutowiringAttribute 100.00% 3 / 3 100.00% 1 / 1 3
 namesAService 40.00% 2 / 5 0.00% 0 / 1 7.46
 coerceToParameterType 100.00% 14 / 14 100.00% 1 / 1 8
 escapeParameterPlaceholders 80.00% 4 / 5 0.00% 0 / 1 3.07
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\Runtime\Container;
6
7use ReflectionAttribute;
8use ReflectionClass;
9use ReflectionIntersectionType;
10use ReflectionNamedType;
11use ReflectionParameter;
12use ReflectionType;
13use ReflectionUnionType;
14use Stewart\Runtime\Config\BooleanSpelling;
15use Stewart\Runtime\Exception\ContainerError;
16use Stewart\Runtime\Exception\ContainerException;
17use Stewart\Runtime\Ipc\WorkerApp;
18use Stewart\Support\Text\OptionNameMatcher;
19use Symfony\Component\DependencyInjection\Attribute\Autowire;
20use Symfony\Component\DependencyInjection\Attribute\AutowireDecorated;
21use Symfony\Component\DependencyInjection\Attribute\Lazy;
22
23final readonly class AppOptionResolver
24{
25    private const array COERCIBLE_TYPES = ['bool', 'int', 'float'];
26
27    public function __construct(private OptionNameMatcher $optionNames) {}
28
29    /**
30     * @return array<string, mixed>
31     * @throws ContainerException
32     */
33    public function resolveOptionArguments(WorkerApp $app): array
34    {
35        if (!class_exists($app->class)) {
36            throw ContainerException::createForReason(ContainerError::AppClassMissing, appId: $app->id->value, class: $app->class);
37        }
38
39        $parameters = $this->listConstructorParameters($app->class);
40        $arguments = [];
41        $optionsByParameter = [];
42
43        foreach ($app->options as $option => $value) {
44            $option = (string) $option;
45            $match = $this->optionNames->matchOption($option, array_keys($parameters));
46
47            if ($match->isAmbiguous()) {
48                throw ContainerException::appOptionAmbiguous($app->id, $option, $app->class, $match->candidates);
49            }
50
51            $name = $match->parameter ?? throw ContainerException::appOptionUnknown($app->id, $option, $app->class, $match->suggestion);
52            $parameter = $parameters[$name];
53
54            if (isset($optionsByParameter[$name])) {
55                throw ContainerException::createForReason(
56                    ContainerError::AppOptionRepeated,
57                    appId: $app->id->value,
58                    parameter: $name,
59                    class: $app->class,
60                    firstOption: $optionsByParameter[$name],
61                    secondOption: $option,
62                );
63            }
64
65            $optionsByParameter[$name] = $option;
66            $arguments['$' . $name] = $this->escapeParameterPlaceholders($this->coerceToParameterType($app, $parameter, $value));
67        }
68
69        foreach ($parameters as $name => $parameter) {
70            if (!isset($optionsByParameter[$name]) && $this->needsExplicitValue($parameter)) {
71                throw ContainerException::createForReason(ContainerError::AppOptionMissing, appId: $app->id->value, option: $name, class: $app->class);
72            }
73        }
74
75        return $arguments;
76    }
77
78    /**
79     * @param class-string $class
80     * @return array<string, ReflectionParameter>
81     */
82    private function listConstructorParameters(string $class): array
83    {
84        $parameters = [];
85
86        foreach (new ReflectionClass($class)->getConstructor()?->getParameters() ?? [] as $parameter) {
87            $parameters[$parameter->getName()] = $parameter;
88        }
89
90        return $parameters;
91    }
92
93    // Mirrors Symfony's AutowirePass: a parameter with no service type and no default needs a configured value.
94    private function needsExplicitValue(ReflectionParameter $parameter): bool
95    {
96        return !$parameter->isVariadic()
97            && !$parameter->isDefaultValueAvailable()
98            && !$parameter->isOptional()
99            && !$this->hasAutowiringAttribute($parameter)
100            && !$this->namesAService($parameter->getType());
101    }
102
103    private function hasAutowiringAttribute(ReflectionParameter $parameter): bool
104    {
105        return $parameter->getAttributes(Autowire::class, ReflectionAttribute::IS_INSTANCEOF) !== []
106            || $parameter->getAttributes(Lazy::class, ReflectionAttribute::IS_INSTANCEOF) !== []
107            || $parameter->getAttributes(AutowireDecorated::class) !== [];
108    }
109
110    private function namesAService(?ReflectionType $type): bool
111    {
112        if ($type instanceof ReflectionNamedType) {
113            return !$type->isBuiltin();
114        }
115
116        if ($type instanceof ReflectionUnionType || $type instanceof ReflectionIntersectionType) {
117            return array_any($type->getTypes(), $this->namesAService(...));
118        }
119
120        return false;
121    }
122
123    /** @throws ContainerException */
124    private function coerceToParameterType(WorkerApp $app, ReflectionParameter $parameter, mixed $value): mixed
125    {
126        $type = $parameter->getType();
127
128        if (!\is_string($value) || !$type instanceof ReflectionNamedType || !\in_array($type->getName(), self::COERCIBLE_TYPES, true)) {
129            return $value;
130        }
131
132        $coerced = match ($type->getName()) {
133            'bool' => BooleanSpelling::tryParseBoolean($value),
134            'int' => filter_var(trim($value), \FILTER_VALIDATE_INT, \FILTER_NULL_ON_FAILURE),
135            default => is_numeric(trim($value)) ? (float) trim($value) : null,
136        };
137
138        return $coerced ?? throw ContainerException::createForReason(
139            ContainerError::AppOptionInvalid,
140            appId: $app->id->value,
141            option: $parameter->getName(),
142            value: $value,
143            expectedType: $type->getName(),
144        );
145    }
146
147    // Symfony resolves %name% in arguments; app options are literals.
148    private function escapeParameterPlaceholders(mixed $value): mixed
149    {
150        if (\is_string($value)) {
151            return str_replace('%', '%%', $value);
152        }
153
154        if (\is_array($value)) {
155            return array_map($this->escapeParameterPlaceholders(...), $value);
156        }
157
158        return $value;
159    }
160}