Lines 88.13% 52 / 59
Functions and Methods 66.66% 4 / 6
Classes and Traits 0.00% 0 / 1
Name Lines Functions and Methods CRAP Classes and Traits
AppArgumentResolver 88.13% 52 / 59 66.66% 4 / 6 28.22 0.00% 0 / 1
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 resolveArguments 100.00% 8 / 8 100.00% 1 / 1 3
 matchOptionsToParameters 71.42% 15 / 21 0.00% 0 / 1 4.37
 resolveParameter 93.75% 15 / 16 0.00% 0 / 1 11.03
 findStoreFor 100.00% 5 / 5 100.00% 1 / 1 4
 isBuiltOnHaContext 100.00% 8 / 8 100.00% 1 / 1 4
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\Testing\App;
6
7use ReflectionClass;
8use ReflectionNamedType;
9use ReflectionParameter;
10use Stewart\Contracts\App;
11use Stewart\Contracts\App\AppId;
12use Stewart\Contracts\HaContext;
13use Stewart\Contracts\Store\GlobalStore;
14use Stewart\Contracts\Store\PeerStore;
15use Stewart\Contracts\Store\Store;
16use Stewart\Store\ReadOnlyStore;
17use Stewart\Store\Stores;
18use Stewart\Support\Text\OptionNameMatcher;
19use Stewart\Testing\Exception\HarnessError;
20use Stewart\Testing\Exception\HarnessException;
21
22/** @internal */
23final readonly class AppArgumentResolver
24{
25    /** @param array<string, object> $servicesByType */
26    public function __construct(
27        private array $servicesByType,
28        private Stores $stores,
29        private HaContext $ha,
30        private OptionNameMatcher $optionNames,
31    ) {}
32
33    /**
34     * @template T of App
35     * @param ReflectionClass<T> $app
36     * @param array<string, mixed> $options
37     * @return array<string, mixed>
38     * @throws HarnessException
39     */
40    public function resolveArguments(ReflectionClass $app, array $options): array
41    {
42        $parameters = $app->getConstructor()?->getParameters() ?? [];
43        $optionsByParameter = $this->matchOptionsToParameters($app, $options, array_map(static fn(ReflectionParameter $parameter): string => $parameter->getName(), $parameters));
44        $arguments = [];
45
46        foreach ($parameters as $parameter) {
47            $arguments[$parameter->getName()] = \array_key_exists($parameter->getName(), $optionsByParameter)
48                ? $options[$optionsByParameter[$parameter->getName()]]
49                : $this->resolveParameter($app, $parameter);
50        }
51
52        return $arguments;
53    }
54
55    /**
56     * @template T of App
57     * @param ReflectionClass<T> $app
58     * @param array<string, mixed> $options
59     * @param list<string> $parameters
60     * @return array<string, string>
61     * @throws HarnessException
62     */
63    private function matchOptionsToParameters(ReflectionClass $app, array $options, array $parameters): array
64    {
65        $optionsByParameter = [];
66
67        foreach (array_keys($options) as $option) {
68            $match = $this->optionNames->matchOption($option, $parameters);
69
70            if ($match->isAmbiguous()) {
71                throw HarnessException::createForReason(
72                    HarnessError::OptionAmbiguous,
73                    option: $option,
74                    class: $app->getName(),
75                    parameters: implode(', ', array_map(static fn(string $name): string => '$' . $name, $match->candidates)),
76                );
77            }
78
79            $parameter = $match->parameter ?? throw HarnessException::optionUnknown($option, $app->getName(), $match->suggestion);
80
81            if (isset($optionsByParameter[$parameter])) {
82                throw HarnessException::createForReason(
83                    HarnessError::OptionRepeated,
84                    class: $app->getName(),
85                    parameter: $parameter,
86                    firstOption: $optionsByParameter[$parameter],
87                    secondOption: $option,
88                );
89            }
90
91            $optionsByParameter[$parameter] = $option;
92        }
93
94        return $optionsByParameter;
95    }
96
97    /**
98     * @template T of App
99     * @param ReflectionClass<T> $app
100     * @throws HarnessException
101     */
102    private function resolveParameter(ReflectionClass $app, ReflectionParameter $parameter): mixed
103    {
104        $type = $parameter->getType();
105        $typeName = $type instanceof ReflectionNamedType ? $type->getName() : null;
106        $store = $this->findStoreFor($parameter, $typeName);
107
108        if ($store !== null) {
109            return $store;
110        }
111
112        if ($typeName !== null && isset($this->servicesByType[$typeName])) {
113            return $this->servicesByType[$typeName];
114        }
115
116        if ($typeName !== null && self::isBuiltOnHaContext($typeName)) {
117            return new $typeName($this->ha);
118        }
119
120        if ($parameter->isDefaultValueAvailable()) {
121            return $parameter->getDefaultValue();
122        }
123
124        if ($type?->allowsNull() === true) {
125            return null;
126        }
127
128        if ($type instanceof ReflectionNamedType && $type->isBuiltin()) {
129            throw HarnessException::createForReason(HarnessError::OptionMissing, class: $app->getName(), option: $parameter->getName());
130        }
131
132        throw HarnessException::createForReason(HarnessError::ParameterUnresolvable, class: $app->getName(), parameter: $parameter->getName(), type: (string) $type);
133    }
134
135    private function findStoreFor(ReflectionParameter $parameter, ?string $typeName): ?object
136    {
137        if ($parameter->getAttributes(GlobalStore::class) !== []) {
138            $global = $this->stores->openGlobalStore();
139
140            return $typeName === Store::class ? $global : new ReadOnlyStore($global);
141        }
142
143        $peer = ($parameter->getAttributes(PeerStore::class)[0] ?? null)?->newInstance();
144
145        return $peer === null ? null : new ReadOnlyStore($this->stores->openAppStore(new AppId($peer->appId)));
146    }
147
148    // The generated Entities and Actions roots take the app's HaContext and nothing else.
149    private static function isBuiltOnHaContext(string $typeName): bool
150    {
151        if (!class_exists($typeName)) {
152            return false;
153        }
154
155        $required = array_values(array_filter(
156            new ReflectionClass($typeName)->getConstructor()?->getParameters() ?? [],
157            static fn(ReflectionParameter $parameter): bool => !$parameter->isOptional(),
158        ));
159        $type = ($required[0] ?? null)?->getType();
160
161        return \count($required) === 1 && $type instanceof ReflectionNamedType && $type->getName() === HaContext::class;
162    }
163}