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

nette / bootstrap / 26544958339

27 May 2026 11:31PM UTC coverage: 91.608% (+0.5%) from 91.156%
26544958339

push

github

dg
made static analysis mandatory

131 of 143 relevant lines covered (91.61%)

0.92 hits per line

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

91.2
/src/Bootstrap/Configurator.php
1
<?php declare(strict_types=1);
2

3
/**
4
 * This file is part of the Nette Framework (https://nette.org)
5
 * Copyright (c) 2004 David Grudl (https://davidgrudl.com)
6
 */
7

8
namespace Nette\Bootstrap;
9

10
use Composer\Autoload\ClassLoader;
11
use Composer\InstalledVersions;
12
use Latte;
13
use Nette;
14
use Nette\DI;
15
use Nette\DI\Definitions\Statement;
16
use Tracy;
17
use function in_array, is_array, is_string;
18
use const PHP_RELEASE_VERSION, PHP_SAPI, PHP_VERSION_ID;
19

20

21
/**
22
 * Initial system DI container generator.
23
 */
24
class Configurator
25
{
26
        public const CookieSecret = 'nette-debug';
27

28
        /** @deprecated  use Configurator::CookieSecret */
29
        public const COOKIE_SECRET = self::CookieSecret;
30

31

32
        /** @var array<callable(static, DI\Compiler): void>  Occurs after the compiler is created */
33
        public array $onCompile = [];
34

35
        /** @var array<string, class-string<DI\CompilerExtension>|array{class-string<DI\CompilerExtension>, list<mixed>}> */
36
        public array $defaultExtensions = [
37
                'application' => [Nette\Bridges\ApplicationDI\ApplicationExtension::class, ['%debugMode%', ['%appDir%'], '%tempDir%/cache/nette.application']],
38
                'assets' => [Nette\Bridges\AssetsDI\DIExtension::class, ['%baseUrl%', '%wwwDir%', '%debugMode%']],
39
                'cache' => [Nette\Bridges\CacheDI\CacheExtension::class, ['%tempDir%/cache']],
40
                'constants' => Extensions\ConstantsExtension::class,
41
                'database' => [Nette\Bridges\DatabaseDI\DatabaseExtension::class, ['%debugMode%']],
42
                'decorator' => Nette\DI\Extensions\DecoratorExtension::class,
43
                'di' => [Nette\DI\Extensions\DIExtension::class, ['%debugMode%']],
44
                'extensions' => Nette\DI\Extensions\ExtensionsExtension::class,
45
                'forms' => Nette\Bridges\FormsDI\FormsExtension::class,
46
                'http' => [Nette\Bridges\HttpDI\HttpExtension::class, ['%consoleMode%']],
47
                'inject' => Nette\DI\Extensions\InjectExtension::class,
48
                'latte' => [Nette\Bridges\ApplicationDI\LatteExtension::class, ['%tempDir%/cache/latte', '%debugMode%']],
49
                'mail' => [Nette\Bridges\MailDI\MailExtension::class, ['%debugMode%']],
50
                'php' => Extensions\PhpExtension::class,
51
                'routing' => [Nette\Bridges\ApplicationDI\RoutingExtension::class, ['%debugMode%']],
52
                'search' => [Nette\DI\Extensions\SearchExtension::class, ['%tempDir%/cache/nette.search']],
53
                'security' => [Nette\Bridges\SecurityDI\SecurityExtension::class, ['%debugMode%']],
54
                'session' => [Nette\Bridges\HttpDI\SessionExtension::class, ['%debugMode%', '%consoleMode%']],
55
                'tracy' => [Tracy\Bridges\Nette\TracyExtension::class, ['%debugMode%', '%consoleMode%']],
56
        ];
57

58
        /** @var list<class-string>  classes which shouldn't be autowired */
59
        public array $autowireExcludedClasses = [
60
                \ArrayAccess::class,
61
                \Countable::class,
62
                \IteratorAggregate::class,
63
                \stdClass::class,
64
                \Traversable::class,
65
        ];
66

67
        /** @var array<string, mixed> */
68
        protected array $staticParameters;
69

70
        /** @var array<string, mixed> */
71
        protected array $dynamicParameters = [];
72

73
        /** @var array<string, object> */
74
        protected array $services = [];
75

76
        /** @var list<string|array<string, mixed>> */
77
        protected array $configs = [];
78

79
        /** @var array<string, mixed> */
80
        private array $defaultParameters;
81

82

83
        public function __construct()
84
        {
85
                $this->defaultParameters = $this->staticParameters = $this->getDefaultParameters();
1✔
86
        }
1✔
87

88

89
        /**
90
         * Sets the %debugMode% parameter.
91
         * @param  bool|string|list<string>  $value  IP addresses or computer names whitelist, or true/false
92
         */
93
        public function setDebugMode(bool|string|array $value): static
1✔
94
        {
95
                if (is_string($value) || is_array($value)) {
1✔
96
                        $value = static::detectDebugMode($value);
1✔
97
                }
98

99
                return $this->addStaticParameters([
1✔
100
                        'debugMode' => $value,
1✔
101
                        'productionMode' => !$value, // compatibility
1✔
102
                ]);
103
        }
104

105

106
        public function isDebugMode(): bool
107
        {
108
                return $this->staticParameters['debugMode'];
1✔
109
        }
110

111

112
        /**
113
         * Sets path to temporary directory.
114
         */
115
        public function setTempDirectory(string $path): static
1✔
116
        {
117
                return $this->addStaticParameters(['tempDir' => $path]);
1✔
118
        }
119

120

121
        /**
122
         * Sets the default timezone.
123
         */
124
        public function setTimeZone(string $timezone): static
1✔
125
        {
126
                date_default_timezone_set($timezone);
1✔
127
                @ini_set('date.timezone', $timezone); // @ - function may be disabled
1✔
128
                return $this;
1✔
129
        }
130

131

132
        /**
133
         * @deprecated use addStaticParameters()
134
         * @param  array<string, mixed>  $params
135
         */
136
        public function addParameters(array $params): static
1✔
137
        {
138
                return $this->addStaticParameters($params);
1✔
139
        }
140

141

142
        /**
143
         * Adds static parameters.
144
         * @param  array<string, mixed>  $params
145
         */
146
        public function addStaticParameters(array $params): static
1✔
147
        {
148
                $this->staticParameters = DI\Config\Helpers::merge($params, $this->staticParameters);
1✔
149
                $this->defaultParameters = array_diff_key($this->defaultParameters, $params);
1✔
150
                return $this;
1✔
151
        }
152

153

154
        /**
155
         * Adds dynamic parameters.
156
         * @param  array<string, mixed>  $params
157
         */
158
        public function addDynamicParameters(array $params): static
1✔
159
        {
160
                $this->dynamicParameters = $params + $this->dynamicParameters;
1✔
161
                return $this;
1✔
162
        }
163

164

165
        /**
166
         * Adds service instances.
167
         * @param  array<string, object>  $services
168
         */
169
        public function addServices(array $services): static
1✔
170
        {
171
                $this->services = $services + $this->services;
1✔
172
                return $this;
1✔
173
        }
174

175

176
        /** @return array<string, mixed> */
177
        protected function getDefaultParameters(): array
178
        {
179
                $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
1✔
180
                $last = end($trace);
1✔
181
                $debugMode = static::detectDebugMode();
1✔
182
                $loaderRc = class_exists(ClassLoader::class)
1✔
183
                        ? new \ReflectionClass(ClassLoader::class)
1✔
184
                        : null;
×
185
                $rootDir = class_exists(InstalledVersions::class)
1✔
186
                        ? rtrim(Nette\Utils\FileSystem::normalizePath(InstalledVersions::getRootPackage()['install_path']), '\/')
1✔
187
                        : null;
×
188
                $baseUrl = new Statement('trim($this->getByType(?)->getUrl()->getBaseUrl(), "/")', [Nette\Http\IRequest::class]);
1✔
189
                return [
190
                        'appDir' => isset($trace[1]['file']) ? dirname($trace[1]['file']) : null,
1✔
191
                        'wwwDir' => isset($last['file']) ? dirname($last['file']) : null,
1✔
192
                        'vendorDir' => $loaderRc ? dirname($loaderRc->getFileName(), 2) : null,
1✔
193
                        'rootDir' => $rootDir,
1✔
194
                        'debugMode' => $debugMode,
1✔
195
                        'productionMode' => !$debugMode,
1✔
196
                        'consoleMode' => PHP_SAPI === 'cli',
197
                        'baseUrl' => $baseUrl,
1✔
198
                ];
199
        }
200

201

202
        /**
203
         * Enables Tracy debugger and configures it for the current mode.
204
         */
205
        public function enableTracy(?string $logDirectory = null, ?string $email = null): void
206
        {
207
                if (!class_exists(Tracy\Debugger::class)) {
×
208
                        throw new Nette\NotSupportedException('Tracy not found, do you have `tracy/tracy` package installed?');
×
209
                }
210

211
                Tracy\Debugger::$strictMode = true;
×
212
                Tracy\Debugger::enable(!$this->staticParameters['debugMode'], $logDirectory, $email);
×
213
                Tracy\Bridges\Nette\Bridge::initialize();
×
214
                if (class_exists(Latte\Bridges\Tracy\BlueScreenPanel::class)) {
×
215
                        Latte\Bridges\Tracy\BlueScreenPanel::initialize();
×
216
                }
217
        }
218

219

220
        /** @deprecated use enableTracy() */
221
        public function enableDebugger(?string $logDirectory = null, ?string $email = null): void
222
        {
223
                $this->enableTracy($logDirectory, $email);
×
224
        }
225

226

227
        /**
228
         * Creates RobotLoader for automatic class discovery and caching.
229
         * @throws Nette\NotSupportedException if RobotLoader is not available
230
         */
231
        public function createRobotLoader(): Nette\Loaders\RobotLoader
232
        {
233
                if (!class_exists(Nette\Loaders\RobotLoader::class)) {
1✔
234
                        throw new Nette\NotSupportedException('RobotLoader not found, do you have `nette/robot-loader` package installed?');
×
235
                }
236

237
                $loader = new Nette\Loaders\RobotLoader;
1✔
238
                $loader->setTempDirectory($this->getCacheDirectory() . '/nette.robotLoader');
1✔
239
                $loader->setAutoRefresh($this->staticParameters['debugMode']);
1✔
240

241
                if (isset($this->defaultExtensions['application'])) {
1✔
242
                        $this->defaultExtensions['application'][1][1] = null;
1✔
243
                        $this->defaultExtensions['application'][1][3] = $loader;
1✔
244
                }
245

246
                return $loader;
1✔
247
        }
248

249

250
        /**
251
         * Adds a configuration file path or configuration array.
252
         * @param  string|array<string, mixed>  $config
253
         */
254
        public function addConfig(string|array $config): static
1✔
255
        {
256
                $this->configs[] = $config;
1✔
257
                return $this;
1✔
258
        }
259

260

261
        /**
262
         * Returns system DI container.
263
         */
264
        public function createContainer(bool $initialize = true): DI\Container
1✔
265
        {
266
                $class = $this->loadContainer();
1✔
267
                $container = new $class($this->dynamicParameters);
1✔
268
                foreach ($this->services as $name => $service) {
1✔
269
                        $container->addService($name, $service);
1✔
270
                }
271

272
                if ($initialize) {
1✔
273
                        $container->initialize();
1✔
274
                }
275

276
                return $container;
1✔
277
        }
278

279

280
        /**
281
         * Loads system DI container class and returns its name.
282
         * @return class-string<DI\Container>
283
         */
284
        public function loadContainer(): string
285
        {
286
                $loader = new DI\ContainerLoader(
1✔
287
                        $this->getCacheDirectory() . '/nette.configurator',
1✔
288
                        $this->staticParameters['debugMode'],
1✔
289
                );
290
                return $loader->load(
1✔
291
                        $this->generateContainer(...),
1✔
292
                        $this->generateContainerKey(),
1✔
293
                );
294
        }
295

296

297
        /**
298
         * @internal
299
         */
300
        public function generateContainer(DI\Compiler $compiler): void
1✔
301
        {
302
                $loader = $this->createLoader();
1✔
303
                $loader->setParameters($this->staticParameters);
1✔
304

305
                $compiler->addConfig(['parameters' => DI\Helpers::escape($this->defaultParameters)]);
1✔
306

307
                foreach ($this->configs as $config) {
1✔
308
                        if (is_string($config)) {
1✔
309
                                $compiler->loadConfig($config, $loader);
1✔
310
                        } else {
311
                                $compiler->addConfig($config);
1✔
312
                        }
313
                }
314

315
                $explicit = array_diff_key($this->staticParameters, $this->defaultParameters);
1✔
316
                $compiler->addConfig(['parameters' => DI\Helpers::escape($explicit)]);
1✔
317
                $compiler->setDynamicParameterNames(array_merge(array_keys($this->dynamicParameters), ['baseUrl']));
1✔
318

319
                $builder = $compiler->getContainerBuilder();
1✔
320
                $builder->addExcludedClasses($this->autowireExcludedClasses);
1✔
321

322
                foreach ($this->defaultExtensions as $name => $extension) {
1✔
323
                        [$class, $args] = is_string($extension)
1✔
324
                                ? [$extension, []]
1✔
325
                                : $extension;
1✔
326
                        if (class_exists($class)) {
1✔
327
                                $args = DI\Helpers::expand($args, $this->staticParameters);
1✔
328
                                $compiler->addExtension($name, (new \ReflectionClass($class))->newInstanceArgs($args));
1✔
329
                        }
330
                }
331

332
                Nette\Utils\Arrays::invoke($this->onCompile, $this, $compiler);
1✔
333
        }
1✔
334

335

336
        protected function createLoader(): DI\Config\Loader
337
        {
338
                return new DI\Config\Loader;
1✔
339
        }
340

341

342
        /** @return list<mixed> */
343
        protected function generateContainerKey(): array
344
        {
345
                return [
346
                        $this->staticParameters,
1✔
347
                        array_diff_key($this->staticParameters, $this->defaultParameters),
1✔
348
                        array_keys($this->dynamicParameters),
1✔
349
                        $this->configs,
1✔
350
                        PHP_VERSION_ID - PHP_RELEASE_VERSION, // minor PHP version
351
                        class_exists(ClassLoader::class) // composer update
1✔
352
                                ? filemtime((new \ReflectionClass(ClassLoader::class))->getFilename())
1✔
353
                                : null,
354
                ];
355
        }
356

357

358
        protected function getCacheDirectory(): string
359
        {
360
                if (empty($this->staticParameters['tempDir'])) {
1✔
361
                        throw new Nette\InvalidStateException('Set path to temporary directory using setTempDirectory().');
1✔
362
                }
363

364
                $dir = $this->staticParameters['tempDir'] . '/cache';
1✔
365
                Nette\Utils\FileSystem::createDir($dir);
1✔
366
                return $dir;
1✔
367
        }
368

369

370
        /**
371
         * Detects debug mode based on IP address or computer name matching.
372
         * @param  string|list<string>|null  $list  IP addresses or computer names whitelist
373
         */
374
        public static function detectDebugMode(string|array|null $list = null): bool
1✔
375
        {
376
                $addr = $_SERVER['REMOTE_ADDR'] ?? php_uname('n');
1✔
377
                $secret = is_string($_COOKIE[self::CookieSecret] ?? null)
1✔
378
                        ? $_COOKIE[self::CookieSecret]
1✔
379
                        : null;
1✔
380
                $list = is_string($list)
1✔
381
                        ? preg_split('#[,\s]+#', $list)
1✔
382
                        : (array) $list;
1✔
383
                if (!isset($_SERVER['HTTP_X_FORWARDED_FOR']) && !isset($_SERVER['HTTP_FORWARDED'])) {
1✔
384
                        $list[] = '127.0.0.1';
1✔
385
                        $list[] = '::1';
1✔
386
                }
387

388
                return in_array($addr, $list, strict: true) || in_array("$secret@$addr", $list, strict: true);
1✔
389
        }
390
}
391

392

393
class_exists(Nette\Configurator::class);
1✔
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