Namespaces

  • Latte
    • Loaders
    • Macros
    • Runtime
  • Nette
    • Application
      • Responses
      • Routers
      • UI
    • Bridges
      • ApplicationDI
      • ApplicationLatte
      • ApplicationTracy
      • CacheDI
      • CacheLatte
      • DatabaseDI
      • DatabaseTracy
      • DITracy
      • FormsDI
      • FormsLatte
      • Framework
      • HttpDI
      • HttpTracy
      • MailDI
      • ReflectionDI
      • SecurityDI
      • SecurityTracy
    • Caching
      • Storages
    • ComponentModel
    • Database
      • Conventions
      • Drivers
      • Table
    • DI
      • Config
        • Adapters
      • Extensions
    • Forms
      • Controls
      • Rendering
    • Http
    • Iterators
    • Loaders
    • Localization
    • Mail
    • Neon
    • PhpGenerator
    • Reflection
    • Security
    • Utils
  • none
  • Tracy
    • Bridges
      • Nette

Classes

  • Callback
  • Configurator
  • Environment
  • Framework
  • FreezableObject
  • Object

Interfaces

  • IFreezable

Traits

  • SmartObject
  • StaticClass

Exceptions

  • ArgumentOutOfRangeException
  • DeprecatedException
  • DirectoryNotFoundException
  • FileNotFoundException
  • InvalidArgumentException
  • InvalidStateException
  • IOException
  • MemberAccessException
  • NotImplementedException
  • NotSupportedException
  • OutOfRangeException
  • StaticClassException
  • UnexpectedValueException
  • Overview
  • Namespace
  • Class
  • Tree
  • Deprecated
  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: namespace Nette;
  9: 
 10: use Nette;
 11: use Nette\DI;
 12: use Tracy;
 13: 
 14: 
 15: /**
 16:  * Initial system DI container generator.
 17:  */
 18: class Configurator
 19: {
 20:     use SmartObject;
 21: 
 22:     const AUTO = TRUE,
 23:         NONE = FALSE;
 24: 
 25:     const COOKIE_SECRET = 'nette-debug';
 26: 
 27:     /** @var callable[]  function (Configurator $sender, DI\Compiler $compiler); Occurs after the compiler is created */
 28:     public $onCompile;
 29: 
 30:     /** @var array */
 31:     public $defaultExtensions = [
 32:         'php' => Nette\DI\Extensions\PhpExtension::class,
 33:         'constants' => Nette\DI\Extensions\ConstantsExtension::class,
 34:         'extensions' => Nette\DI\Extensions\ExtensionsExtension::class,
 35:         'application' => [Nette\Bridges\ApplicationDI\ApplicationExtension::class, ['%debugMode%', ['%appDir%'], '%tempDir%/cache']],
 36:         'decorator' => Nette\DI\Extensions\DecoratorExtension::class,
 37:         'cache' => [Nette\Bridges\CacheDI\CacheExtension::class, ['%tempDir%']],
 38:         'database' => [Nette\Bridges\DatabaseDI\DatabaseExtension::class, ['%debugMode%']],
 39:         'di' => [Nette\DI\Extensions\DIExtension::class, ['%debugMode%']],
 40:         'forms' => Nette\Bridges\FormsDI\FormsExtension::class,
 41:         'http' => [Nette\Bridges\HttpDI\HttpExtension::class, ['%consoleMode%']],
 42:         'latte' => [Nette\Bridges\ApplicationDI\LatteExtension::class, ['%tempDir%/cache/latte', '%debugMode%']],
 43:         'mail' => Nette\Bridges\MailDI\MailExtension::class,
 44:         'routing' => [Nette\Bridges\ApplicationDI\RoutingExtension::class, ['%debugMode%']],
 45:         'security' => [Nette\Bridges\SecurityDI\SecurityExtension::class, ['%debugMode%']],
 46:         'session' => [Nette\Bridges\HttpDI\SessionExtension::class, ['%debugMode%', '%consoleMode%']],
 47:         'tracy' => [Tracy\Bridges\Nette\TracyExtension::class, ['%debugMode%', '%consoleMode%']],
 48:         'inject' => Nette\DI\Extensions\InjectExtension::class,
 49:     ];
 50: 
 51:     /** @var string[] of classes which shouldn't be autowired */
 52:     public $autowireExcludedClasses = [
 53:         'stdClass',
 54:     ];
 55: 
 56:     /** @var array */
 57:     protected $parameters;
 58: 
 59:     /** @var array */
 60:     protected $services = [];
 61: 
 62:     /** @var array [file|array, section] */
 63:     protected $files = [];
 64: 
 65: 
 66:     public function __construct()
 67:     {
 68:         $this->parameters = $this->getDefaultParameters();
 69:     }
 70: 
 71: 
 72:     /**
 73:      * Set parameter %debugMode%.
 74:      * @param  bool|string|array
 75:      * @return self
 76:      */
 77:     public function setDebugMode($value)
 78:     {
 79:         if (is_string($value) || is_array($value)) {
 80:             $value = static::detectDebugMode($value);
 81:         } elseif (!is_bool($value)) {
 82:             throw new Nette\InvalidArgumentException(sprintf('Value must be either a string, array, or boolean, %s given.', gettype($value)));
 83:         }
 84:         $this->parameters['debugMode'] = $value;
 85:         $this->parameters['productionMode'] = !$this->parameters['debugMode']; // compatibility
 86:         return $this;
 87:     }
 88: 
 89: 
 90:     /**
 91:      * @return bool
 92:      */
 93:     public function isDebugMode()
 94:     {
 95:         return $this->parameters['debugMode'];
 96:     }
 97: 
 98: 
 99:     /**
100:      * Sets path to temporary directory.
101:      * @return self
102:      */
103:     public function setTempDirectory($path)
104:     {
105:         $this->parameters['tempDir'] = $path;
106:         return $this;
107:     }
108: 
109: 
110:     /**
111:      * Sets the default timezone.
112:      * @return self
113:      */
114:     public function setTimeZone($timezone)
115:     {
116:         date_default_timezone_set($timezone);
117:         @ini_set('date.timezone', $timezone); // @ - function may be disabled
118:         return $this;
119:     }
120: 
121: 
122:     /**
123:      * Adds new parameters. The %params% will be expanded.
124:      * @return self
125:      */
126:     public function addParameters(array $params)
127:     {
128:         $this->parameters = DI\Config\Helpers::merge($params, $this->parameters);
129:         return $this;
130:     }
131: 
132: 
133:     /**
134:      * Add instances of services.
135:      * @return self
136:      */
137:     public function addServices(array $services)
138:     {
139:         $this->services = $services + $this->services;
140:         return $this;
141:     }
142: 
143: 
144:     /**
145:      * @return array
146:      */
147:     protected function getDefaultParameters()
148:     {
149:         $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
150:         $last = end($trace);
151:         $debugMode = static::detectDebugMode();
152:         return [
153:             'appDir' => isset($trace[1]['file']) ? dirname($trace[1]['file']) : NULL,
154:             'wwwDir' => isset($last['file']) ? dirname($last['file']) : NULL,
155:             'debugMode' => $debugMode,
156:             'productionMode' => !$debugMode,
157:             'consoleMode' => PHP_SAPI === 'cli',
158:         ];
159:     }
160: 
161: 
162:     /**
163:      * @param  string        error log directory
164:      * @param  string        administrator email
165:      * @return void
166:      */
167:     public function enableDebugger($logDirectory = NULL, $email = NULL)
168:     {
169:         Tracy\Debugger::$strictMode = TRUE;
170:         Tracy\Debugger::enable(!$this->parameters['debugMode'], $logDirectory, $email);
171:         Nette\Bridges\Framework\TracyBridge::initialize();
172:     }
173: 
174: 
175:     /**
176:      * @return Nette\Loaders\RobotLoader
177:      * @throws Nette\NotSupportedException if RobotLoader is not available
178:      */
179:     public function createRobotLoader()
180:     {
181:         if (!class_exists(Nette\Loaders\RobotLoader::class)) {
182:             throw new Nette\NotSupportedException('RobotLoader not found, do you have `nette/robot-loader` package installed?');
183:         }
184: 
185:         $loader = new Nette\Loaders\RobotLoader;
186:         $loader->setCacheStorage(new Nette\Caching\Storages\FileStorage($this->getCacheDirectory()));
187:         $loader->autoRebuild = $this->parameters['debugMode'];
188:         return $loader;
189:     }
190: 
191: 
192:     /**
193:      * Adds configuration file.
194:      * @return self
195:      */
196:     public function addConfig($file)
197:     {
198:         $section = func_num_args() > 1 ? func_get_arg(1) : NULL;
199:         if ($section !== NULL) {
200:             trigger_error('Sections in config file are deprecated.', E_USER_DEPRECATED);
201:         }
202:         $this->files[] = [$file, $section === self::AUTO ? ($this->parameters['debugMode'] ? 'development' : 'production') : $section];
203:         return $this;
204:     }
205: 
206: 
207:     /**
208:      * Returns system DI container.
209:      * @return DI\Container
210:      */
211:     public function createContainer()
212:     {
213:         $class = $this->loadContainer();
214:         $container = new $class();
215:         foreach ($this->services as $name => $service) {
216:             $container->addService($name, $service);
217:         }
218:         $container->initialize();
219:         if (class_exists(Nette\Environment::class)) {
220:             Nette\Environment::setContext($container); // back compatibility
221:         }
222:         return $container;
223:     }
224: 
225: 
226:     /**
227:      * Loads system DI container class and returns its name.
228:      * @return string
229:      */
230:     public function loadContainer()
231:     {
232:         $loader = new DI\ContainerLoader(
233:             $this->getCacheDirectory() . '/Nette.Configurator',
234:             $this->parameters['debugMode']
235:         );
236:         $class = $loader->load(
237:             [$this, 'generateContainer'],
238:             [$this->parameters, $this->files, PHP_VERSION_ID - PHP_RELEASE_VERSION]
239:         );
240:         return $class;
241:     }
242: 
243: 
244:     /**
245:      * @return string
246:      * @internal
247:      */
248:     public function generateContainer(DI\Compiler $compiler)
249:     {
250:         $loader = $this->createLoader();
251:         $compiler->addConfig(['parameters' => $this->parameters]);
252:         $fileInfo = [];
253:         foreach ($this->files as $info) {
254:             if (is_scalar($info[0])) {
255:                 $fileInfo[] = "// source: $info[0] $info[1]";
256:                 $info[0] = $loader->load($info[0], $info[1]);
257:             }
258:             $compiler->addConfig($this->fixCompatibility($info[0]));
259:         }
260:         $compiler->addDependencies($loader->getDependencies());
261: 
262:         $builder = $compiler->getContainerBuilder();
263:         $builder->addExcludedClasses($this->autowireExcludedClasses);
264: 
265:         foreach ($this->defaultExtensions as $name => $extension) {
266:             list($class, $args) = is_string($extension) ? [$extension, []] : $extension;
267:             if (class_exists($class)) {
268:                 $args = DI\Helpers::expand($args, $this->parameters, TRUE);
269:                 $compiler->addExtension($name, (new \ReflectionClass($class))->newInstanceArgs($args));
270:             }
271:         }
272: 
273:         $this->onCompile($this, $compiler);
274: 
275:         $classes = $compiler->compile();
276:         return implode("\n", $fileInfo) . "\n\n" . $classes;
277:     }
278: 
279: 
280:     /**
281:      * @return DI\Config\Loader
282:      */
283:     protected function createLoader()
284:     {
285:         return new DI\Config\Loader;
286:     }
287: 
288: 
289:     protected function getCacheDirectory()
290:     {
291:         if (empty($this->parameters['tempDir'])) {
292:             throw new Nette\InvalidStateException('Set path to temporary directory using setTempDirectory().');
293:         }
294:         $dir = $this->parameters['tempDir'] . '/cache';
295:         if (!is_dir($dir)) {
296:             @mkdir($dir); // @ - directory may already exist
297:         }
298:         return $dir;
299:     }
300: 
301: 
302:     /**
303:      * Back compatibility with < v2.3
304:      * @return array
305:      */
306:     protected function fixCompatibility($config)
307:     {
308:         if (isset($config['nette']['security']['frames'])) {
309:             $config['nette']['http']['frames'] = $config['nette']['security']['frames'];
310:             unset($config['nette']['security']['frames']);
311:         }
312:         foreach (['application', 'cache', 'database', 'di' => 'container', 'forms', 'http',
313:             'latte', 'mail' => 'mailer', 'routing', 'security', 'session', 'tracy' => 'debugger'] as $new => $old) {
314:             if (isset($config['nette'][$old])) {
315:                 $new = is_int($new) ? $old : $new;
316:                 if (isset($config[$new])) {
317:                     throw new Nette\DeprecatedException("You can use (deprecated) section 'nette.$old' or new section '$new', but not both of them.");
318:                 } else {
319:                     trigger_error("Configuration section 'nette.$old' is deprecated, use section '$new' (without 'nette')", E_USER_DEPRECATED);
320:                 }
321:                 $config[$new] = $config['nette'][$old];
322:                 unset($config['nette'][$old]);
323:             }
324:         }
325:         if (isset($config['nette']['xhtml'])) {
326:             trigger_error("Configuration option 'nette.xhtml' is deprecated, use section 'latte.xhtml' instead.", E_USER_DEPRECATED);
327:             $config['latte']['xhtml'] = $config['nette']['xhtml'];
328:             unset($config['nette']['xhtml']);
329:         }
330: 
331:         if (empty($config['nette'])) {
332:             unset($config['nette']);
333:         }
334:         return $config;
335:     }
336: 
337: 
338:     /********************* tools ****************d*g**/
339: 
340: 
341:     /**
342:      * Detects debug mode by IP address.
343:      * @param  string|array  IP addresses or computer names whitelist detection
344:      * @return bool
345:      */
346:     public static function detectDebugMode($list = NULL)
347:     {
348:         $addr = isset($_SERVER['REMOTE_ADDR'])
349:             ? $_SERVER['REMOTE_ADDR']
350:             : php_uname('n');
351:         $secret = isset($_COOKIE[self::COOKIE_SECRET]) && is_string($_COOKIE[self::COOKIE_SECRET])
352:             ? $_COOKIE[self::COOKIE_SECRET]
353:             : NULL;
354:         $list = is_string($list)
355:             ? preg_split('#[,\s]+#', $list)
356:             : (array) $list;
357:         if (!isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
358:             $list[] = '127.0.0.1';
359:             $list[] = '::1';
360:         }
361:         return in_array($addr, $list, TRUE) || in_array("$secret@$addr", $list, TRUE);
362:     }
363: 
364: }
365: 
Nette 2.4-20160930 API API documentation generated by ApiGen 2.8.0