Lines 100.00% 84 / 84
Methods 100.00% 13 / 13
Classes 100.00% 1 / 1
Name Lines Methods CRAP
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 collectEnvironmentOverrides 100.00% 24 / 24 100.00% 1 / 1 7
 isReadElsewhere 100.00% 1 / 1 100.00% 1 / 1 2
 resolveOverrideTarget 100.00% 21 / 21 100.00% 1 / 1 9
 withValueAtPath 100.00% 7 / 7 100.00% 1 / 1 3
 resolveChildKey 100.00% 12 / 12 100.00% 1 / 1 5
 findSecretFileKey 100.00% 6 / 6 100.00% 1 / 1 5
 findPrototypedSecretFileKey 100.00% 5 / 5 100.00% 1 / 1 4
 findMatchingFileKey 100.00% 1 / 1 100.00% 1 / 1 1
 findExistingFileKey 100.00% 3 / 3 100.00% 1 / 1 1
 findFileKeyBy 100.00% 1 / 1 100.00% 1 / 1 1
 normalizeForKeyComparison 100.00% 1 / 1 100.00% 1 / 1 1
 foldForKeyComparison 100.00% 1 / 1 100.00% 1 / 1 1
16final readonly class EnvironmentOverlay
17{
18    public const string PREFIX = 'STEWART_';
19
20    public const string ENTRYPOINT_PREFIX = self::PREFIX . 'BOOT_';
21
22    private const string SEPARATOR = '__';
23
24    private const string SECRET_FILE_SUFFIX = '_file';
25
26    // Kubernetes names these after every Service in the namespace, ours and others like stewart-valkey alike.
27    private const string KUBERNETES_SERVICE_LINK = '/\A' . self::PREFIX . '(?:[A-Z0-9]+_)*(?:SERVICE_HOST|SERVICE_PORT(?:_[A-Z0-9_]+)?|PORT(?:_\d+_(?:TCP|UDP|SCTP)(?:_(?:PROTO|PORT|ADDR))?)?)\z/';
28
29    public function __construct(
30        private EnvironmentVariables $variables,
31        private EnvironmentValueParser $environmentValueParser,
32        private ClosestNameFinder $closestNameFinder,
33        private SecretFileReader $secretFiles,
34        private RenamedSettings $renamedSettings,
35    ) {}
36
37    /**
38     * @param array<array-key, mixed> $file
39     * @return array<array-key, mixed>
40     * @throws ConfigurationException
41     */
42    public function collectEnvironmentOverrides(NodeInterface $tree, array $file): array
43    {
44        $overrides = [];
45        $variableByPath = [];
46
47        foreach ($this->variables->filterByPrefix(self::PREFIX) as $name => $raw) {
48            if ($this->isReadElsewhere($name)) {
49                continue;
50            }
51
52            $segments = array_values(array_filter(
53                explode(self::SEPARATOR, substr($name, \strlen(self::PREFIX))),
54                static fn(string $segment): bool => $segment !== '',
55            ));
56
57            if ($segments === []) {
58                continue;
59            }
60
61            $target = $this->resolveOverrideTarget($tree, $file, $segments, $name);
62
63            if (!$this->environmentValueParser->supportsNode($target->node)) {
64                throw ConfigurationException::createForReason(ConfigurationError::EnvironmentVariableNamesSection, variable: $name, separator: self::SEPARATOR);
65            }
66
67            $valuePath = implode('.', $target->path);
68
69            if (isset($variableByPath[$valuePath])) {
70                throw ConfigurationException::createForReason(
71                    ConfigurationError::EnvironmentVariableConflict,
72                    variable: $variableByPath[$valuePath],
73                    otherVariable: $name,
74                    valuePath: $valuePath,
75                );
76            }
77
78            $variableByPath[$valuePath] = $name;
79            $value = $target->readsSecretFile ? $this->secretFiles->readSecretFile($name, $raw) : $raw;
80            $overrides = $this->withValueAtPath($overrides, $target->path, $this->environmentValueParser->parseForNode($target->node, $name, $value));
81        }
82
83        return $overrides;
84    }
85
86    private function isReadElsewhere(string $name): bool
87    {
88        return str_starts_with($name, self::ENTRYPOINT_PREFIX) || preg_match(self::KUBERNETES_SERVICE_LINK, $name) === 1;
89    }
90
91    /**
92     * @param array<array-key, mixed> $file
93     * @param non-empty-list<string> $segments
94     * @throws ConfigurationException
95     */
96    private function resolveOverrideTarget(NodeInterface $node, array $file, array $segments, string $name): EnvironmentOverrideTarget
97    {
98        $path = [];
99        $lastSegment = array_key_last($segments);
100
101        foreach ($segments as $index => $segment) {
102            if (!$node instanceof ArrayNode) {
103                throw ConfigurationException::createForReason(ConfigurationError::EnvironmentVariableTooDeep, variable: $name, valuePath: implode('.', $path));
104            }
105
106            if ($node instanceof PrototypedArrayNode) {
107                $prototype = $node->getPrototype();
108                $secretKey = $index === $lastSegment ? $this->findPrototypedSecretFileKey($prototype, $segment, $file) : null;
109
110                if ($secretKey !== null) {
111                    return new EnvironmentOverrideTarget([...$path, $secretKey], $prototype, readsSecretFile: true);
112                }
113
114                $key = $this->findMatchingFileKey($segment, $file);
115                $node = $prototype;
116            } else {
117                $secretKey = $index === $lastSegment ? $this->findSecretFileKey($node, $segment) : null;
118
119                if ($secretKey !== null) {
120                    return new EnvironmentOverrideTarget([...$path, $secretKey], $node->getChildren()[$secretKey], readsSecretFile: true);
121                }
122
123                $key = $this->resolveChildKey($node, $segment, $path, $name);
124                $node = $node->getChildren()[$key];
125            }
126
127            $nested = $file[$key] ?? [];
128            $file = \is_array($nested) ? $nested : [];
129            $path[] = $key;
130        }
131
132        return new EnvironmentOverrideTarget($path, $node);
133    }
134
135    /**
136     * @param array<array-key, mixed> $values
137     * @param non-empty-list<string> $path
138     * @return array<array-key, mixed>
139     */
140    private function withValueAtPath(array $values, array $path, mixed $value): array
141    {
142        $key = array_shift($path);
143
144        if ($path === []) {
145            $values[$key] = $value;
146
147            return $values;
148        }
149
150        $nested = $values[$key] ?? null;
151        $values[$key] = $this->withValueAtPath(\is_array($nested) ? $nested : [], $path, $value);
152
153        return $values;
154    }
155
156    /**
157     * @param list<string> $path
158     * @throws ConfigurationException
159     */
160    private function resolveChildKey(ArrayNode $node, string $segment, array $path, string $name): string
161    {
162        $key = strtolower($segment);
163        $children = array_keys($node->getChildren());
164
165        if (\in_array($key, $children, true)) {
166            return $key;
167        }
168
169        $newName = $path === [] ? $this->renamedSettings->findNewName($key) : null;
170
171        if ($newName !== null) {
172            throw ConfigurationException::createForReason(ConfigurationError::KeyRenamed, setting: $name, renamedTo: self::PREFIX . strtoupper($newName) . substr($name, \strlen(self::PREFIX . $segment)));
173        }
174
175        $closestChildKey = $this->closestNameFinder->findClosestName($key, $children);
176
177        throw ConfigurationException::environmentVariableUnknown(
178            $name,
179            $closestChildKey === null ? null : self::PREFIX . strtoupper(implode(self::SEPARATOR, [...$path, $closestChildKey])),
180        );
181    }
182
183    private function findSecretFileKey(ArrayNode $node, string $segment): ?string
184    {
185        $key = strtolower($segment);
186        $children = $node->getChildren();
187
188        if (isset($children[$key]) || !str_ends_with($key, self::SECRET_FILE_SUFFIX)) {
189            return null;
190        }
191
192        $secretKey = substr($key, 0, -\strlen(self::SECRET_FILE_SUFFIX));
193
194        return isset($children[$secretKey]) && $this->environmentValueParser->supportsNode($children[$secretKey]) ? $secretKey : null;
195    }
196
197    // A free-form key the file already names, like an option called cert_file, keeps its literal meaning.
198    /** @param array<array-key, mixed> $file */
199    private function findPrototypedSecretFileKey(NodeInterface $prototype, string $segment, array $file): ?string
200    {
201        if (!str_ends_with(strtolower($segment), self::SECRET_FILE_SUFFIX) || !$this->environmentValueParser->supportsNode($prototype)) {
202            return null;
203        }
204
205        return $this->findExistingFileKey($segment, $file) === null
206            ? $this->findMatchingFileKey(substr($segment, 0, -\strlen(self::SECRET_FILE_SUFFIX)), $file)
207            : null;
208    }
209
210    /** @param array<array-key, mixed> $file */
211    private function findMatchingFileKey(string $segment, array $file): string
212    {
213        return $this->findExistingFileKey($segment, $file) ?? strtolower($segment);
214    }
215
216    /** @param array<array-key, mixed> $file */
217    private function findExistingFileKey(string $segment, array $file): ?string
218    {
219        $fileKeys = array_map(strval(...), array_keys($file));
220
221        return $this->findFileKeyBy($fileKeys, $segment, $this->normalizeForKeyComparison(...))
222            ?? $this->findFileKeyBy($fileKeys, $segment, $this->foldForKeyComparison(...));
223    }
224
225    /**
226     * @param list<string> $fileKeys
227     * @param Closure(string): string $normalize
228     */
229    private function findFileKeyBy(array $fileKeys, string $segment, Closure $normalize): ?string
230    {
231        return array_find($fileKeys, static fn(string $existing): bool => $normalize($existing) === $normalize($segment));
232    }
233
234    private function normalizeForKeyComparison(string $key): string
235    {
236        // Env segments are upper case and cannot express "-", so both sides map it to "_".
237        return strtolower(strtr($key, '-', '_'));
238    }
239
240    // MOTION_SENSOR and MOTIONSENSOR both stand for a camelCase key such as motionSensor.
241    private function foldForKeyComparison(string $key): string
242    {
243        return strtolower(str_replace(['_', '-'], '', $key));
244    }
245}