• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

codeigniter4 / CodeIgniter4 / 28378730935

29 Jun 2026 02:17PM UTC coverage: 88.309%. Remained the same
28378730935

push

github

web-flow
refactor: bump to phpstan-codeigniter v2.1 (#10312)

14 of 21 new or added lines in 9 files covered. (66.67%)

22200 of 25139 relevant lines covered (88.31%)

211.9 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

91.51
/system/Config/BaseConfig.php
1
<?php
2

3
/**
4
 * This file is part of CodeIgniter 4 framework.
5
 *
6
 * (c) CodeIgniter Foundation <admin@codeigniter.com>
7
 *
8
 * For the full copyright and license information, please view
9
 * the LICENSE file that was distributed with this source code.
10
 */
11

12
namespace CodeIgniter\Config;
13

14
use CodeIgniter\Autoloader\FileLocatorInterface;
15
use CodeIgniter\Exceptions\ConfigException;
16
use CodeIgniter\Exceptions\RuntimeException;
17
use Config\Encryption;
18
use Config\Modules;
19
use ReflectionClass;
20
use ReflectionException;
21

22
/**
23
 * Class BaseConfig
24
 *
25
 * Not intended to be used on its own, this class will attempt to
26
 * automatically populate the child class' properties with values
27
 * from the environment.
28
 *
29
 * These can be set within the .env file.
30
 *
31
 * @phpstan-consistent-constructor
32
 * @see \CodeIgniter\Config\BaseConfigTest
33
 */
34
class BaseConfig
35
{
36
    /**
37
     * An optional array of classes that will act as Registrars
38
     * for rapidly setting config class properties.
39
     *
40
     * @var array
41
     */
42
    public static $registrars = [];
43

44
    /**
45
     * Whether to override properties by Env vars and Registrars.
46
     */
47
    public static bool $override = true;
48

49
    /**
50
     * Has module discovery completed?
51
     *
52
     * @var bool
53
     */
54
    protected static $didDiscovery = false;
55

56
    /**
57
     * Is module discovery running or not?
58
     */
59
    protected static bool $discovering = false;
60

61
    /**
62
     * The processing Registrar file for error message.
63
     */
64
    protected static string $registrarFile = '';
65

66
    /**
67
     * The modules configuration.
68
     *
69
     * @var Modules|null
70
     */
71
    protected static $moduleConfig;
72

73
    public static function __set_state(array $array)
74
    {
75
        static::$override = false;
2✔
76
        $obj              = new static();
2✔
77
        static::$override = true;
2✔
78

79
        $properties = array_keys(get_object_vars($obj));
2✔
80

81
        foreach ($properties as $property) {
2✔
82
            $obj->{$property} = $array[$property];
2✔
83
        }
84

85
        return $obj;
2✔
86
    }
87

88
    /**
89
     * @internal For testing purposes only.
90
     * @testTag
91
     */
92
    public static function setModules(Modules $modules): void
93
    {
94
        static::$moduleConfig = $modules;
1✔
95
    }
96

97
    /**
98
     * @internal For testing purposes only.
99
     * @testTag
100
     */
101
    public static function reset(): void
102
    {
103
        static::$registrars   = [];
18✔
104
        static::$override     = true;
18✔
105
        static::$didDiscovery = false;
18✔
106
        static::$moduleConfig = null;
18✔
107
    }
108

109
    /**
110
     * Will attempt to get environment variables with names
111
     * that match the properties of the child class.
112
     *
113
     * The "shortPrefix" is the lowercase-only config class name.
114
     */
115
    public function __construct()
116
    {
117
        static::$moduleConfig ??= new Modules();
7,424✔
118

119
        if (! static::$override) {
7,424✔
120
            return;
6✔
121
        }
122

123
        $this->registerProperties();
7,420✔
124

125
        $properties  = array_keys(get_object_vars($this));
7,420✔
126
        $prefix      = static::class;
7,420✔
127
        $slashAt     = strrpos($prefix, '\\');
7,420✔
128
        $shortPrefix = strtolower(substr($prefix, $slashAt === false ? 0 : $slashAt + 1));
7,420✔
129

130
        foreach ($properties as $property) {
7,420✔
131
            $this->initEnvValue($this->{$property}, $property, $prefix, $shortPrefix);
7,420✔
132

133
            if ($this instanceof Encryption) {
7,420✔
134
                if ($property === 'key') {
50✔
135
                    $this->{$property} = $this->parseEncryptionKey($this->{$property});
50✔
136
                } elseif ($property === 'previousKeys') {
50✔
137
                    $keysArray  = is_string($this->{$property}) ? array_map(trim(...), explode(',', $this->{$property})) : $this->{$property};
50✔
138
                    $parsedKeys = [];
50✔
139

140
                    foreach ($keysArray as $key) {
50✔
141
                        $parsedKeys[] = $this->parseEncryptionKey($key);
50✔
142
                    }
143

144
                    $this->{$property} = $parsedKeys;
50✔
145
                }
146
            }
147
        }
148
    }
149

150
    /**
151
     * Parse encryption key with hex2bin: or base64: prefix
152
     */
153
    protected function parseEncryptionKey(string $key): string
154
    {
155
        if (str_starts_with($key, 'hex2bin:')) {
50✔
156
            return hex2bin(substr($key, 8));
2✔
157
        }
158

159
        if (str_starts_with($key, 'base64:')) {
50✔
160
            return base64_decode(substr($key, 7), true);
2✔
161
        }
162

163
        return $key;
50✔
164
    }
165

166
    /**
167
     * Initialization an environment-specific configuration setting
168
     *
169
     * @param array|bool|float|int|string|null $property
170
     *
171
     * @return void
172
     */
173
    protected function initEnvValue(&$property, string $name, string $prefix, string $shortPrefix)
174
    {
175
        if (is_array($property)) {
7,420✔
176
            foreach (array_keys($property) as $key) {
7,403✔
177
                $this->initEnvValue($property[$key], "{$name}.{$key}", $prefix, $shortPrefix);
7,403✔
178
            }
179
        } elseif (($value = $this->getEnvValue($name, $prefix, $shortPrefix)) !== false && $value !== null) {
7,420✔
180
            if ($value === 'false') {
7,341✔
181
                $value = false;
10✔
182
            } elseif ($value === 'true') {
7,341✔
183
                $value = true;
10✔
184
            }
185
            if (is_bool($value)) {
7,341✔
186
                $property = $value;
10✔
187

188
                return;
10✔
189
            }
190

191
            $value = trim($value, '\'"');
7,341✔
192

193
            if (is_int($property)) {
7,341✔
194
                $value = (int) $value;
10✔
195
            } elseif (is_float($property)) {
7,341✔
196
                $value = (float) $value;
10✔
197
            }
198

199
            // If the default value of the property is `null` and the type is not
200
            // `string`, TypeError will happen.
201
            // So cannot set `declare(strict_types=1)` in this file.
202
            $property = $value;
7,341✔
203
        }
204
    }
205

206
    /**
207
     * Retrieve an environment-specific configuration setting
208
     *
209
     * @return string|null
210
     */
211
    protected function getEnvValue(string $property, string $prefix, string $shortPrefix)
212
    {
213
        $shortPrefix        = ltrim($shortPrefix, '\\');
7,420✔
214
        $underscoreProperty = str_replace('.', '_', $property);
7,420✔
215

216
        switch (true) {
217
            case array_key_exists("{$shortPrefix}.{$property}", $_ENV):
7,420✔
218
                return $_ENV["{$shortPrefix}.{$property}"];
12✔
219

220
            case array_key_exists("{$shortPrefix}_{$underscoreProperty}", $_ENV):
7,420✔
221
                return $_ENV["{$shortPrefix}_{$underscoreProperty}"];
10✔
222

223
            case array_key_exists("{$shortPrefix}.{$property}", $_SERVER):
7,420✔
224
                return $_SERVER["{$shortPrefix}.{$property}"]; // @phpstan-ignore codeigniter.superglobalsOffsetAccess (reads live $_SERVER, not the snapshot service)
7,341✔
225

226
            case array_key_exists("{$shortPrefix}_{$underscoreProperty}", $_SERVER):
7,420✔
NEW
227
                return $_SERVER["{$shortPrefix}_{$underscoreProperty}"]; // @phpstan-ignore codeigniter.superglobalsOffsetAccess (reads live $_SERVER, not the snapshot service)
×
228

229
            case array_key_exists("{$prefix}.{$property}", $_ENV):
7,420✔
230
                return $_ENV["{$prefix}.{$property}"];
10✔
231

232
            case array_key_exists("{$prefix}_{$underscoreProperty}", $_ENV):
7,420✔
233
                return $_ENV["{$prefix}_{$underscoreProperty}"];
10✔
234

235
            case array_key_exists("{$prefix}.{$property}", $_SERVER):
7,420✔
236
                return $_SERVER["{$prefix}.{$property}"]; // @phpstan-ignore codeigniter.superglobalsOffsetAccess (reads live $_SERVER, not the snapshot service)
1✔
237

238
            case array_key_exists("{$prefix}_{$underscoreProperty}", $_SERVER):
7,420✔
NEW
239
                return $_SERVER["{$prefix}_{$underscoreProperty}"]; // @phpstan-ignore codeigniter.superglobalsOffsetAccess (reads live $_SERVER, not the snapshot service)
×
240

241
            default:
242
                $value = getenv("{$shortPrefix}.{$property}");
7,420✔
243
                $value = $value === false ? getenv("{$shortPrefix}_{$underscoreProperty}") : $value;
7,420✔
244
                $value = $value === false ? getenv("{$prefix}.{$property}") : $value;
7,420✔
245
                $value = $value === false ? getenv("{$prefix}_{$underscoreProperty}") : $value;
7,420✔
246

247
                return $value === false ? null : $value;
7,420✔
248
        }
249
    }
250

251
    /**
252
     * Provides external libraries a simple way to register one or more
253
     * options into a config file.
254
     *
255
     * @return void
256
     *
257
     * @throws ReflectionException
258
     */
259
    protected function registerProperties()
260
    {
261
        if (! static::$moduleConfig->shouldDiscover('registrars')) {
7,420✔
262
            return;
1✔
263
        }
264

265
        if (! static::$didDiscovery) {
7,420✔
266
            // Discovery must be completed before the first instantiation of any Config class.
267
            if (static::$discovering) {
19✔
268
                throw new ConfigException(
×
269
                    'During Auto-Discovery of Registrars,'
×
270
                    . ' "' . static::class . '" executes Auto-Discovery again.'
×
271
                    . ' "' . clean_path(static::$registrarFile) . '" seems to have bad code.',
×
272
                );
×
273
            }
274

275
            static::$discovering = true;
19✔
276

277
            /** @var FileLocatorInterface */
278
            $locator         = service('locator');
19✔
279
            $registrarsFiles = $locator->search('Config/Registrar.php');
19✔
280

281
            foreach ($registrarsFiles as $file) {
19✔
282
                // Saves the file for error message.
283
                static::$registrarFile = $file;
19✔
284

285
                $className = $locator->findQualifiedNameFromPath($file);
19✔
286

287
                if ($className === false) {
19✔
288
                    continue;
×
289
                }
290

291
                static::$registrars[] = new $className();
19✔
292
            }
293

294
            static::$didDiscovery = true;
19✔
295
            static::$discovering  = false;
19✔
296
        }
297

298
        $shortName = (new ReflectionClass($this))->getShortName();
7,420✔
299

300
        // Check the registrar class for a method named after this class' shortName
301
        foreach (static::$registrars as $callable) {
7,420✔
302
            // ignore non-applicable registrars
303
            if (! method_exists($callable, $shortName)) {
7,420✔
304
                continue; // @codeCoverageIgnore
305
            }
306

307
            $properties = $callable::$shortName();
922✔
308

309
            if (! is_array($properties)) {
922✔
310
                throw new RuntimeException('Registrars must return an array of properties and their values.');
1✔
311
            }
312

313
            foreach ($properties as $property => $value) {
921✔
314
                if (isset($this->{$property}) && is_array($this->{$property}) && is_array($value)) {
921✔
315
                    $this->{$property} = array_merge($this->{$property}, $value);
921✔
316
                } else {
317
                    $this->{$property} = $value;
×
318
                }
319
            }
320
        }
321
    }
322
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc