1818use Config \Modules ;
1919use ReflectionClass ;
2020use ReflectionException ;
21+ use ReflectionMethod ;
2122
2223/**
2324 * Class BaseConfig
@@ -69,6 +70,36 @@ class BaseConfig
6970 */
7071 protected static $ moduleConfig ;
7172
73+ /**
74+ * Environment variables grouped by the text before their first "." or "_",
75+ * then by source ("env", "server", "getenv").
76+ *
77+ * @var array<string, array<string, array<array-key, mixed>>>|null
78+ */
79+ private static ?array $ envIndex = null ;
80+
81+ /**
82+ * The [$_ENV, $_SERVER] arrays the index was built from.
83+ *
84+ * @var array{array<array-key, mixed>, array<array-key, mixed>}|null
85+ */
86+ private static ?array $ envSnapshot = null ;
87+
88+ /**
89+ * Env vars found with live getenv() calls on each class's first build, keyed
90+ * by class name. The getenv() array omits names that contain ".", " " or "[".
91+ *
92+ * @var array<class-string, array<string, string>>
93+ */
94+ private static array $ unlistedEnvVars = [];
95+
96+ /**
97+ * Whether a class overrides getEnvValue() or initEnvValue(), keyed by class name.
98+ *
99+ * @var array<class-string, bool>
100+ */
101+ private static array $ overridesEnvHooks = [];
102+
72103 /**
73104 * @param array<string, mixed> $array
74105 */
@@ -106,6 +137,9 @@ public static function reset(): void
106137 static ::$ override = true ;
107138 static ::$ didDiscovery = false ;
108139 static ::$ moduleConfig = null ;
140+
141+ self ::$ envIndex = self ::$ envSnapshot = null ;
142+ self ::$ unlistedEnvVars = [];
109143 }
110144
111145 /**
@@ -124,13 +158,31 @@ public function __construct()
124158
125159 $ this ->registerProperties ();
126160
127- $ properties = array_keys (get_object_vars ($ this ));
161+ $ values = get_object_vars ($ this );
162+ $ properties = array_keys ($ values );
128163 $ prefix = static ::class;
129164 $ slashAt = strrpos ($ prefix , '\\' );
130165 $ shortPrefix = strtolower (substr ($ prefix , $ slashAt === false ? 0 : $ slashAt + 1 ));
131166
167+ // Classes with custom env hooks keep the full walk with live lookups.
168+ $ sources = (self ::$ overridesEnvHooks [static ::class] ??= self ::overridesEnvHooks (static ::class))
169+ ? null
170+ : self ::scopedEnvSources ($ prefix , $ shortPrefix );
171+
172+ if ($ sources !== null ) {
173+ $ sources ['getenv ' ] = (self ::$ unlistedEnvVars [static ::class] ??= self ::findUnlistedEnvVars ($ values , $ prefix , $ shortPrefix ))
174+ + $ sources ['getenv ' ];
175+
176+ // Every env var that can override this class, for a fast miss check per leaf.
177+ $ candidates = $ sources ['env ' ] + $ sources ['server ' ] + $ sources ['getenv ' ];
178+ }
179+
132180 foreach ($ properties as $ property ) {
133- $ this ->initEnvValue ($ this ->{$ property }, $ property , $ prefix , $ shortPrefix );
181+ if ($ sources === null ) {
182+ $ this ->initEnvValue ($ this ->{$ property }, $ property , $ prefix , $ shortPrefix );
183+ } elseif ($ candidates !== []) {
184+ $ this ->initScopedEnvValue ($ sources , $ candidates , $ this ->{$ property }, $ property , $ prefix , $ shortPrefix );
185+ }
134186
135187 if ($ this instanceof Encryption) {
136188 if ($ property === 'key ' ) {
@@ -179,75 +231,224 @@ protected function initEnvValue(&$property, string $name, string $prefix, string
179231 $ this ->initEnvValue ($ property [$ key ], "{$ name }. {$ key }" , $ prefix , $ shortPrefix );
180232 }
181233 } elseif (($ value = $ this ->getEnvValue ($ name , $ prefix , $ shortPrefix )) !== false && $ value !== null ) {
182- if ($ value === 'false ' ) {
183- $ value = false ;
184- } elseif ($ value === 'true ' ) {
185- $ value = true ;
186- }
187- if (is_bool ($ value )) {
188- $ property = $ value ;
234+ // If the default value of the property is `null` and the type is not
235+ // `string`, TypeError will happen.
236+ // So cannot set `declare(strict_types=1)` in this file.
237+ $ property = self ::castEnvValue ($ value , $ property );
238+ }
239+ }
189240
190- return ;
241+ /**
242+ * Same as initEnvValue(), but looks values up in the pre-filtered sources
243+ * from scopedEnvSources() instead of the live environment.
244+ *
245+ * @param array{env: array<array-key, mixed>, server: array<array-key, mixed>, getenv: array<array-key, mixed>} $sources
246+ * @param array<array-key, mixed> $candidates All keys of $sources
247+ * @param array<array-key, mixed>|bool|float|int|string|null $property
248+ */
249+ private function initScopedEnvValue (array $ sources , array $ candidates , &$ property , string $ name , string $ prefix , string $ shortPrefix ): void
250+ {
251+ if (is_array ($ property )) {
252+ foreach (array_keys ($ property ) as $ key ) {
253+ $ this ->initScopedEnvValue ($ sources , $ candidates , $ property [$ key ], "{$ name }. {$ key }" , $ prefix , $ shortPrefix );
191254 }
192255
193- $ value = trim ($ value , '\'" ' );
256+ return ;
257+ }
194258
195- if (is_int ($ property )) {
196- $ value = (int ) $ value ;
197- } elseif (is_float ($ property )) {
198- $ value = (float ) $ value ;
199- }
259+ $ keys = self ::envKeys ($ name , $ prefix , $ shortPrefix );
200260
201- // If the default value of the property is `null` and the type is not
202- // `string`, TypeError will happen.
203- // So cannot set `declare(strict_types=1)` in this file.
204- $ property = $ value ;
261+ if (! array_key_exists ($ keys [0 ], $ candidates ) && ! array_key_exists ($ keys [1 ], $ candidates )
262+ && ! array_key_exists ($ keys [2 ], $ candidates ) && ! array_key_exists ($ keys [3 ], $ candidates )) {
263+ return ;
264+ }
265+
266+ if (($ value = self ::lookupEnvValue ($ sources ['env ' ], $ sources ['server ' ], $ sources ['getenv ' ], $ keys )) !== false && $ value !== null ) {
267+ $ property = self ::castEnvValue ($ value , $ property );
205268 }
206269 }
207270
208271 /**
209- * Retrieve an environment-specific configuration setting
272+ * Converts a raw env value to the type of the property's default value.
210273 *
211- * @return string|null
274+ * @param bool|float|int|string|null $default
275+ *
276+ * @return bool|float|int|string
212277 */
213- protected function getEnvValue (string $ property , string $ prefix , string $ shortPrefix )
278+ private static function castEnvValue (mixed $ value , $ default )
279+ {
280+ if ($ value === 'false ' ) {
281+ return false ;
282+ }
283+
284+ if ($ value === 'true ' ) {
285+ return true ;
286+ }
287+
288+ if (is_bool ($ value )) {
289+ return $ value ;
290+ }
291+
292+ $ value = trim ($ value , '\'" ' );
293+
294+ if (is_int ($ default )) {
295+ return (int ) $ value ;
296+ }
297+
298+ if (is_float ($ default )) {
299+ return (float ) $ value ;
300+ }
301+
302+ return $ value ;
303+ }
304+
305+ /**
306+ * The env var names for a property, in lookup order: short prefix dot and
307+ * underscore forms, then full prefix dot and underscore forms.
308+ *
309+ * @return array{string, string, string, string}
310+ */
311+ private static function envKeys (string $ property , string $ prefix , string $ shortPrefix ): array
214312 {
215- $ shortPrefix = ltrim ($ shortPrefix , '\\' );
216313 $ underscoreProperty = str_replace ('. ' , '_ ' , $ property );
217314
218- switch (true ) {
219- case array_key_exists ("{$ shortPrefix }. {$ property }" , $ _ENV ):
220- return $ _ENV ["{$ shortPrefix }. {$ property }" ];
315+ return [
316+ "{$ shortPrefix }. {$ property }" ,
317+ "{$ shortPrefix }_ {$ underscoreProperty }" ,
318+ "{$ prefix }. {$ property }" ,
319+ "{$ prefix }_ {$ underscoreProperty }" ,
320+ ];
321+ }
322+
323+ /**
324+ * Finds the first of the env var names from envKeys(). For each prefix,
325+ * $_ENV wins over $_SERVER. getenv() is checked last, and is read live
326+ * when $getenv is null.
327+ *
328+ * @param array<array-key, mixed> $env
329+ * @param array<array-key, mixed> $server
330+ * @param array<array-key, mixed>|null $getenv
331+ * @param array{string, string, string, string} $keys
332+ */
333+ private static function lookupEnvValue (array $ env , array $ server , ?array $ getenv , array $ keys ): mixed
334+ {
335+ foreach ([[$ keys [0 ], $ keys [1 ]], [$ keys [2 ], $ keys [3 ]]] as $ prefixKeys ) {
336+ foreach ([$ env , $ server ] as $ source ) {
337+ foreach ($ prefixKeys as $ key ) {
338+ if (array_key_exists ($ key , $ source )) {
339+ return $ source [$ key ];
340+ }
341+ }
342+ }
343+ }
344+
345+ foreach ($ keys as $ key ) {
346+ if (($ value = $ getenv === null ? getenv ($ key ) : ($ getenv [$ key ] ?? false )) !== false ) {
347+ return $ value ;
348+ }
349+ }
350+
351+ return null ;
352+ }
221353
222- case array_key_exists ("{$ shortPrefix }_ {$ underscoreProperty }" , $ _ENV ):
223- return $ _ENV ["{$ shortPrefix }_ {$ underscoreProperty }" ];
354+ /**
355+ * Returns the env vars that can override a class with these prefixes, by source.
356+ *
357+ * @return array{env: array<array-key, mixed>, server: array<array-key, mixed>, getenv: array<array-key, mixed>}
358+ */
359+ private static function scopedEnvSources (string $ prefix , string $ shortPrefix ): array
360+ {
361+ // Unchanged superglobals share memory with the snapshot, so this check is cheap.
362+ if ([$ _ENV , $ _SERVER ] !== self ::$ envSnapshot ) {
363+ self ::$ envIndex = [];
224364
225- case array_key_exists ("{$ shortPrefix }. {$ property }" , $ _SERVER ):
226- return $ _SERVER ["{$ shortPrefix }. {$ property }" ]; // @phpstan-ignore codeigniter.superglobalsOffsetAccess (reads live $_SERVER, not the snapshot service)
365+ foreach (['env ' => $ _ENV , 'server ' => $ _SERVER , 'getenv ' => getenv ()] as $ source => $ vars ) {
366+ foreach ($ vars as $ key => $ value ) {
367+ self ::$ envIndex [self ::envGroup ((string ) $ key )][$ source ][$ key ] = $ value ;
368+ }
369+ }
370+ }
371+
372+ // Re-share memory even when only equal contents were written.
373+ self ::$ envSnapshot = [$ _ENV , $ _SERVER ];
374+
375+ $ sources = ['env ' => [], 'server ' => [], 'getenv ' => []];
376+
377+ foreach ([$ shortPrefix , $ prefix ] as $ p ) {
378+ // The prefix itself may contain "_", so match within its group.
379+ foreach (self ::$ envIndex [self ::envGroup ($ p )] ?? [] as $ source => $ vars ) {
380+ foreach ($ vars as $ key => $ value ) {
381+ if (str_starts_with ((string ) $ key , "{$ p }. " ) || str_starts_with ((string ) $ key , "{$ p }_ " )) {
382+ $ sources [$ source ][$ key ] = $ value ;
383+ }
384+ }
385+ }
386+ }
227387
228- case array_key_exists ( "{ $ shortPrefix } _ { $ underscoreProperty }" , $ _SERVER ):
229- return $ _SERVER [ "{ $ shortPrefix } _ { $ underscoreProperty }" ]; // @phpstan-ignore codeigniter.superglobalsOffsetAccess (reads live $_SERVER, not the snapshot service)
388+ return $ sources ;
389+ }
230390
231- case array_key_exists ("{$ prefix }. {$ property }" , $ _ENV ):
232- return $ _ENV ["{$ prefix }. {$ property }" ];
391+ /**
392+ * Looks up, with getenv(), every leaf's env var names that the getenv()
393+ * array omits.
394+ *
395+ * @param array<array-key, mixed> $values
396+ *
397+ * @return array<string, string>
398+ */
399+ private static function findUnlistedEnvVars (array $ values , string $ prefix , string $ shortPrefix , string $ parent = '' ): array
400+ {
401+ $ found = [];
233402
234- case array_key_exists ( "{ $ prefix } _ { $ underscoreProperty }" , $ _ENV ):
235- return $ _ENV [ "{$ prefix } _ { $ underscoreProperty }" ] ;
403+ foreach ( $ values as $ key => $ value ) {
404+ $ name = $ parent === '' ? ( string ) $ key : "{$ parent } . { $ key }" ;
236405
237- case array_key_exists ( "{ $ prefix } . { $ property }" , $ _SERVER ):
238- return $ _SERVER [ "{ $ prefix } . { $ property }" ]; // @phpstan-ignore codeigniter.superglobalsOffsetAccess (reads live $_SERVER, not the snapshot service)
406+ if ( is_array ( $ value )) {
407+ $ found += self :: findUnlistedEnvVars ( $ value , $ prefix , $ shortPrefix , $ name );
239408
240- case array_key_exists ( "{ $ prefix } _ { $ underscoreProperty }" , $ _SERVER ):
241- return $ _SERVER [ "{ $ prefix } _ { $ underscoreProperty }" ]; // @phpstan-ignore codeigniter.superglobalsOffsetAccess (reads live $_SERVER, not the snapshot service)
409+ continue ;
410+ }
242411
243- default :
244- $ value = getenv ( "{ $ shortPrefix } . { $ property }" );
245- $ value = $ value === false ? getenv ( "{ $ shortPrefix } _ { $ underscoreProperty }" ) : $ value ;
246- $ value = $ value === false ? getenv ( "{$ prefix }. {$ property }" ) : $ value ;
247- $ value = $ value === false ? getenv ( "{ $ prefix} _ { $ underscoreProperty }" ) : $ value ;
412+ // Dot forms always contain "."; underscore forms only need a live
413+ // lookup when the name itself contains " " or "[".
414+ $ envKeys = strpbrk ( $ name , ' [ ' ) === false
415+ ? [ "{$ shortPrefix }. {$ name }" , "{ $ prefix } . { $ name }" ]
416+ : self :: envKeys ( $ name , $ prefix, $ shortPrefix ) ;
248417
249- return $ value === false ? null : $ value ;
418+ foreach ($ envKeys as $ envKey ) {
419+ if (($ envValue = getenv ($ envKey )) !== false ) {
420+ $ found [$ envKey ] = $ envValue ;
421+ }
422+ }
250423 }
424+
425+ return $ found ;
426+ }
427+
428+ private static function envGroup (string $ key ): string
429+ {
430+ return substr ($ key , 0 , strcspn ($ key , '._ ' ));
431+ }
432+
433+ /**
434+ * @param class-string $class
435+ */
436+ private static function overridesEnvHooks (string $ class ): bool
437+ {
438+ return (new ReflectionMethod ($ class , 'getEnvValue ' ))->class !== self ::class
439+ || (new ReflectionMethod ($ class , 'initEnvValue ' ))->class !== self ::class;
440+ }
441+
442+ /**
443+ * Retrieve an environment-specific configuration setting
444+ *
445+ * @return string|null
446+ */
447+ protected function getEnvValue (string $ property , string $ prefix , string $ shortPrefix )
448+ {
449+ $ keys = self ::envKeys ($ property , $ prefix , ltrim ($ shortPrefix , '\\' ));
450+
451+ return self ::lookupEnvValue ($ _ENV , $ _SERVER , null , $ keys );
251452 }
252453
253454 /**
0 commit comments