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

nette / bootstrap / 4091871235

pending completion
4091871235

push

github

David Grudl
fixed test

120 of 133 relevant lines covered (90.23%)

0.9 hits per line

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

90.76
/src/Bootstrap/Configurator.php
1
<?php
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
declare(strict_types=1);
9

10
namespace Nette\Bootstrap;
11

12
use Composer\Autoload\ClassLoader;
13
use Latte;
14
use Nette;
15
use Nette\DI;
16
use Tracy;
17

18

19
/**
20
 * Initial system DI container generator.
21
 */
22
class Configurator
23
{
24
        use Nette\SmartObject;
25

26
        public const CookieSecret = 'nette-debug';
27

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

31

32
        /** @var callable[]  function (Configurator $sender, DI\Compiler $compiler); Occurs after the compiler is created */
33
        public array $onCompile = [];
34

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

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

65
        protected array $staticParameters;
66
        protected array $dynamicParameters = [];
67
        protected array $services = [];
68

69
        /** @var array<string|array> */
70
        protected array $configs = [];
71

72

73
        public function __construct()
74
        {
75
                $this->staticParameters = $this->getDefaultParameters();
1✔
76
        }
1✔
77

78

79
        /**
80
         * Set parameter %debugMode%.
81
         */
82
        public function setDebugMode(bool|string|array $value): static
1✔
83
        {
84
                if (is_string($value) || is_array($value)) {
1✔
85
                        $value = static::detectDebugMode($value);
1✔
86
                }
87

88
                $this->staticParameters['debugMode'] = $value;
1✔
89
                $this->staticParameters['productionMode'] = !$this->staticParameters['debugMode']; // compatibility
1✔
90
                return $this;
1✔
91
        }
92

93

94
        public function isDebugMode(): bool
95
        {
96
                return $this->staticParameters['debugMode'];
1✔
97
        }
98

99

100
        /**
101
         * Sets path to temporary directory.
102
         */
103
        public function setTempDirectory(string $path): static
1✔
104
        {
105
                $this->staticParameters['tempDir'] = $path;
1✔
106
                return $this;
1✔
107
        }
108

109

110
        /**
111
         * Sets the default timezone.
112
         */
113
        public function setTimeZone(string $timezone): static
1✔
114
        {
115
                date_default_timezone_set($timezone);
1✔
116
                @ini_set('date.timezone', $timezone); // @ - function may be disabled
1✔
117
                return $this;
1✔
118
        }
119

120

121
        /** @deprecated use addStaticParameters() */
122
        public function addParameters(array $params): static
1✔
123
        {
124
                return $this->addStaticParameters($params);
1✔
125
        }
126

127

128
        /**
129
         * Adds new static parameters.
130
         */
131
        public function addStaticParameters(array $params): static
1✔
132
        {
133
                $this->staticParameters = DI\Config\Helpers::merge($params, $this->staticParameters);
1✔
134
                return $this;
1✔
135
        }
136

137

138
        /**
139
         * Adds new dynamic parameters.
140
         */
141
        public function addDynamicParameters(array $params): static
1✔
142
        {
143
                $this->dynamicParameters = $params + $this->dynamicParameters;
1✔
144
                return $this;
1✔
145
        }
146

147

148
        /**
149
         * Add instances of services.
150
         */
151
        public function addServices(array $services): static
1✔
152
        {
153
                $this->services = $services + $this->services;
1✔
154
                return $this;
1✔
155
        }
156

157

158
        protected function getDefaultParameters(): array
159
        {
160
                $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
1✔
161
                $last = end($trace);
1✔
162
                $debugMode = static::detectDebugMode();
1✔
163
                $loaderRc = class_exists(ClassLoader::class)
1✔
164
                        ? new \ReflectionClass(ClassLoader::class)
1✔
165
                        : null;
×
166
                return [
167
                        'appDir' => isset($trace[1]['file']) ? dirname($trace[1]['file']) : null,
1✔
168
                        'wwwDir' => isset($last['file']) ? dirname($last['file']) : null,
1✔
169
                        'vendorDir' => $loaderRc ? dirname($loaderRc->getFileName(), 2) : null,
1✔
170
                        'debugMode' => $debugMode,
1✔
171
                        'productionMode' => !$debugMode,
1✔
172
                        'consoleMode' => PHP_SAPI === 'cli',
1✔
173
                ];
174
        }
175

176

177
        public function enableTracy(?string $logDirectory = null, ?string $email = null): void
178
        {
179
                if (!class_exists(Tracy\Debugger::class)) {
×
180
                        throw new Nette\NotSupportedException('Tracy not found, do you have `tracy/tracy` package installed?');
×
181
                }
182

183
                Tracy\Debugger::$strictMode = true;
×
184
                Tracy\Debugger::enable(!$this->staticParameters['debugMode'], $logDirectory, $email);
×
185
                Tracy\Bridges\Nette\Bridge::initialize();
×
186
                if (class_exists(Latte\Bridges\Tracy\BlueScreenPanel::class)) {
×
187
                        Latte\Bridges\Tracy\BlueScreenPanel::initialize();
×
188
                }
189
        }
190

191

192
        /** @deprecated use enableTracy() */
193
        public function enableDebugger(?string $logDirectory = null, ?string $email = null): void
194
        {
195
                $this->enableTracy($logDirectory, $email);
×
196
        }
197

198

199
        /**
200
         * @throws Nette\NotSupportedException if RobotLoader is not available
201
         */
202
        public function createRobotLoader(): Nette\Loaders\RobotLoader
203
        {
204
                if (!class_exists(Nette\Loaders\RobotLoader::class)) {
1✔
205
                        throw new Nette\NotSupportedException('RobotLoader not found, do you have `nette/robot-loader` package installed?');
×
206
                }
207

208
                $loader = new Nette\Loaders\RobotLoader;
1✔
209
                $loader->setTempDirectory($this->getCacheDirectory() . '/nette.robotLoader');
1✔
210
                $loader->setAutoRefresh($this->staticParameters['debugMode']);
1✔
211

212
                if (isset($this->defaultExtensions['application'])) {
1✔
213
                        $this->defaultExtensions['application'][1][1] = null;
1✔
214
                        $this->defaultExtensions['application'][1][3] = $loader;
1✔
215
                }
216

217
                return $loader;
1✔
218
        }
219

220

221
        /**
222
         * Adds configuration file.
223
         */
224
        public function addConfig(string|array $config): static
1✔
225
        {
226
                $this->configs[] = $config;
1✔
227
                return $this;
1✔
228
        }
229

230

231
        /**
232
         * Returns system DI container.
233
         */
234
        public function createContainer(bool $initialize = true): DI\Container
1✔
235
        {
236
                $class = $this->loadContainer();
1✔
237
                $container = new $class($this->dynamicParameters);
1✔
238
                foreach ($this->services as $name => $service) {
1✔
239
                        $container->addService($name, $service);
1✔
240
                }
241

242
                if ($initialize) {
1✔
243
                        $container->initialize();
1✔
244
                }
245

246
                return $container;
1✔
247
        }
248

249

250
        /**
251
         * Loads system DI container class and returns its name.
252
         */
253
        public function loadContainer(): string
254
        {
255
                $loader = new DI\ContainerLoader(
1✔
256
                        $this->getCacheDirectory() . '/nette.configurator',
1✔
257
                        $this->staticParameters['debugMode'],
1✔
258
                );
259
                return $loader->load(
1✔
260
                        [$this, 'generateContainer'],
1✔
261
                        $this->generateContainerKey(),
1✔
262
                );
263
        }
264

265

266
        /**
267
         * @internal
268
         */
269
        public function generateContainer(DI\Compiler $compiler): void
1✔
270
        {
271
                $loader = $this->createLoader();
1✔
272
                $loader->setParameters($this->staticParameters);
1✔
273

274
                foreach ($this->configs as $config) {
1✔
275
                        if (is_string($config)) {
1✔
276
                                $compiler->loadConfig($config, $loader);
1✔
277
                        } else {
278
                                $compiler->addConfig($config);
×
279
                        }
280
                }
281

282
                $compiler->addConfig(['parameters' => DI\Helpers::escape($this->staticParameters)]);
1✔
283
                $compiler->setDynamicParameterNames(array_keys($this->dynamicParameters));
1✔
284

285
                $builder = $compiler->getContainerBuilder();
1✔
286
                $builder->addExcludedClasses($this->autowireExcludedClasses);
1✔
287

288
                foreach ($this->defaultExtensions as $name => $extension) {
1✔
289
                        [$class, $args] = is_string($extension)
1✔
290
                                ? [$extension, []]
1✔
291
                                : $extension;
1✔
292
                        if (class_exists($class)) {
1✔
293
                                $args = DI\Helpers::expand($args, $this->staticParameters);
1✔
294
                                $compiler->addExtension($name, (new \ReflectionClass($class))->newInstanceArgs($args));
1✔
295
                        }
296
                }
297

298
                Nette\Utils\Arrays::invoke($this->onCompile, $this, $compiler);
1✔
299
        }
1✔
300

301

302
        protected function createLoader(): DI\Config\Loader
303
        {
304
                return new DI\Config\Loader;
1✔
305
        }
306

307

308
        protected function generateContainerKey(): array
309
        {
310
                return [
311
                        $this->staticParameters,
1✔
312
                        array_keys($this->dynamicParameters),
1✔
313
                        $this->configs,
1✔
314
                        PHP_VERSION_ID - PHP_RELEASE_VERSION, // minor PHP version
1✔
315
                        class_exists(ClassLoader::class) // composer update
1✔
316
                                ? filemtime((new \ReflectionClass(ClassLoader::class))->getFilename())
1✔
317
                                : null,
318
                ];
319
        }
320

321

322
        protected function getCacheDirectory(): string
323
        {
324
                if (empty($this->staticParameters['tempDir'])) {
1✔
325
                        throw new Nette\InvalidStateException('Set path to temporary directory using setTempDirectory().');
1✔
326
                }
327

328
                $dir = $this->staticParameters['tempDir'] . '/cache';
1✔
329
                Nette\Utils\FileSystem::createDir($dir);
1✔
330
                return $dir;
1✔
331
        }
332

333

334
        /********************* tools ****************d*g**/
335

336

337
        /**
338
         * Detects debug mode by IP addresses or computer names whitelist detection.
339
         */
340
        public static function detectDebugMode(string|array $list = null): bool
1✔
341
        {
342
                $addr = $_SERVER['REMOTE_ADDR'] ?? php_uname('n');
1✔
343
                $secret = is_string($_COOKIE[self::CookieSecret] ?? null)
1✔
344
                        ? $_COOKIE[self::CookieSecret]
1✔
345
                        : null;
1✔
346
                $list = is_string($list)
1✔
347
                        ? preg_split('#[,\s]+#', $list)
1✔
348
                        : (array) $list;
1✔
349
                if (!isset($_SERVER['HTTP_X_FORWARDED_FOR']) && !isset($_SERVER['HTTP_FORWARDED'])) {
1✔
350
                        $list[] = '127.0.0.1';
1✔
351
                        $list[] = '::1';
1✔
352
                        $list[] = '[::1]'; // workaround for PHP < 7.3.4
1✔
353
                }
354

355
                return in_array($addr, $list, true) || in_array("$secret@$addr", $list, true);
1✔
356
        }
357
}
358

359

360
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