Namespaces

  • Nette
    • Application
    • Caching
    • Collections
    • Config
    • Forms
    • IO
    • Loaders
    • Mail
    • Reflection
    • Security
    • Templates
    • Web
  • None
  • PHP

Classes

  • ArrayTools
  • Callback
  • Component
  • ComponentContainer
  • Configurator
  • DateTime
  • Debug
  • Environment
  • Framework
  • FreezableObject
  • GenericRecursiveIterator
  • Image
  • ImageMagick
  • InstanceFilterIterator
  • Object
  • ObjectMixin
  • Paginator
  • RecursiveComponentIterator
  • ServiceLocator
  • SmartCachingIterator
  • String
  • Tools

Interfaces

  • IComponent
  • IComponentContainer
  • IDebuggable
  • IServiceLocator
  • ITranslator

Exceptions

  • AmbiguousServiceException
  • Overview
  • Namespace
  • Class
  • Tree
  • Other releases
  1: <?php
  2: 
  3: /**
  4:  * This file is part of the Nette Framework (https://nette.org)
  5:  *
  6:  * Copyright (c) 2004 David Grudl (http://davidgrudl.com)
  7:  *
  8:  * For the full copyright and license information, please view
  9:  * the file license.txt that was distributed with this source code.
 10:  */
 11: 
 12: namespace Nette;
 13: 
 14: use Nette;
 15: 
 16: 
 17: 
 18: /**
 19:  * Nette environment and configuration.
 20:  *
 21:  * @author     David Grudl
 22:  */
 23: final class Environment
 24: {
 25:     /**#@+ environment name */
 26:     const DEVELOPMENT = 'development';
 27:     const PRODUCTION = 'production';
 28:     const CONSOLE = 'console';
 29:     const LAB = 'lab';
 30:     /**#@-*/
 31: 
 32:     /**#@+ mode name */
 33:     const DEBUG = 'debug';
 34:     const PERFORMANCE = 'performance';
 35:     /**#@-*/
 36: 
 37:     /** @var Configurator */
 38:     private static $configurator;
 39: 
 40:     /** @var string  the mode of current application */
 41:     private static $modes = array();
 42: 
 43:     /** @var \ArrayObject */
 44:     private static $config;
 45: 
 46:     /** @var IServiceLocator */
 47:     private static $serviceLocator;
 48: 
 49:     /** @var array */
 50:     private static $vars = array( // all deprecated
 51:         'encoding' => array('UTF-8', FALSE),
 52:         'lang' => array('en', FALSE),
 53:         'cacheBase' => array('%tempDir%', TRUE),
 54:         'tempDir' => array('%appDir%/temp', TRUE),
 55:         'logDir' => array('%appDir%/log', TRUE),
 56:     );
 57: 
 58:     /** @var array */
 59:     private static $aliases = array(
 60:         'getHttpContext' => 'Nette\\Web\\HttpContext',
 61:         'getHttpRequest' => 'Nette\\Web\\IHttpRequest',
 62:         'getHttpResponse' => 'Nette\\Web\\IHttpResponse',
 63:         'getApplication' => 'Nette\\Application\\Application',
 64:         'getUser' => 'Nette\\Web\\IUser',
 65:     );
 66: 
 67:     /** @var array */
 68:     private static $criticalSections;
 69: 
 70: 
 71:     /**
 72:      * Static class - cannot be instantiated.
 73:      */
 74:     final public function __construct()
 75:     {
 76:         throw new \LogicException("Cannot instantiate static class " . get_class($this));
 77:     }
 78: 
 79: 
 80: 
 81:     /**
 82:      * Sets "class behind Environment" configurator.
 83:      * @param  Configurator
 84:      * @return void
 85:      */
 86:     public static function setConfigurator(Configurator $configurator)
 87:     {
 88:         self::$configurator = $configurator;
 89:     }
 90: 
 91: 
 92: 
 93:     /**
 94:      * Gets "class behind Environment" configurator.
 95:      * @return Configurator
 96:      */
 97:     public static function getConfigurator()
 98:     {
 99:         if (self::$configurator === NULL) {
100:             self::$configurator = new Configurator;
101:         }
102:         return self::$configurator;
103:     }
104: 
105: 
106: 
107:     /********************* environment name and modes ****************d*g**/
108: 
109: 
110: 
111:     /**
112:      * Sets the current environment name.
113:      * @param  string
114:      * @return void
115:      * @throws \InvalidStateException
116:      */
117:     public static function setName($name)
118:     {
119:         if (!isset(self::$vars['environment'])) {
120:             self::setVariable('environment', $name, FALSE);
121: 
122:         } else {
123:             throw new \InvalidStateException('Environment name has been already set.');
124:         }
125:     }
126: 
127: 
128: 
129:     /**
130:      * Returns the current environment name.
131:      * @return string
132:      */
133:     public static function getName()
134:     {
135:         $name = self::getVariable('environment');
136:         if ($name === NULL) {
137:             $name = self::getConfigurator()->detect('environment');
138:             self::setVariable('environment', $name, FALSE);
139:         }
140:         return $name;
141:     }
142: 
143: 
144: 
145:     /**
146:      * Sets the mode.
147:      * @param  string mode identifier
148:      * @param  bool   set or unset
149:      * @return void
150:      */
151:     public static function setMode($mode, $value = TRUE)
152:     {
153:         self::$modes[$mode] = (bool) $value;
154:     }
155: 
156: 
157: 
158:     /**
159:      * Returns the mode.
160:      * @param  string mode identifier
161:      * @return bool
162:      */
163:     public static function getMode($mode)
164:     {
165:         if (isset(self::$modes[$mode])) {
166:             return self::$modes[$mode];
167: 
168:         } else {
169:             return self::$modes[$mode] = self::getConfigurator()->detect($mode);
170:         }
171:     }
172: 
173: 
174: 
175:     /**
176:      * Detects console (non-HTTP) mode.
177:      * @return bool
178:      */
179:     public static function isConsole()
180:     {
181:         return self::getMode('console');
182:     }
183: 
184: 
185: 
186:     /**
187:      * Determines whether a server is running in production mode.
188:      * @return bool
189:      */
190:     public static function isProduction()
191:     {
192:         return self::getMode('production');
193:     }
194: 
195: 
196: 
197:     /**
198:      * @deprecated
199:      */
200:     public static function isDebugging()
201:     {
202:         throw new \DeprecatedException;
203:     }
204: 
205: 
206: 
207:     /********************* environment variables ****************d*g**/
208: 
209: 
210: 
211:     /**
212:      * Sets the environment variable.
213:      * @param  string
214:      * @param  mixed
215:      * @param  bool
216:      * @return void
217:      */
218:     public static function setVariable($name, $value, $expand = TRUE)
219:     {
220:         if (!is_string($value)) {
221:             $expand = FALSE;
222:         }
223:         self::$vars[$name] = array($value, (bool) $expand);
224:     }
225: 
226: 
227: 
228:     /**
229:      * Returns the value of an environment variable or $default if there is no element set.
230:      * @param  string
231:      * @param  mixed  default value to use if key not found
232:      * @return mixed
233:      * @throws \InvalidStateException
234:      */
235:     public static function getVariable($name, $default = NULL)
236:     {
237:         if (isset(self::$vars[$name])) {
238:             list($var, $exp) = self::$vars[$name];
239:             if ($exp) {
240:                 $var = self::expand($var);
241:                 self::$vars[$name] = array($var, FALSE);
242:             }
243:             return $var;
244: 
245:         } else {
246:             // convert from camelCaps (or PascalCaps) to ALL_CAPS
247:             $const = strtoupper(preg_replace('#(.)([A-Z]+)#', '$1_$2', $name));
248:             $list = get_defined_constants(TRUE);
249:             if (isset($list['user'][$const])) {
250:                 self::$vars[$name] = array($list['user'][$const], FALSE);
251:                 return $list['user'][$const];
252: 
253:             } else {
254:                 return $default;
255:             }
256:         }
257:     }
258: 
259: 
260: 
261:     /**
262:      * Returns the all environment variables.
263:      * @return array
264:      */
265:     public static function getVariables()
266:     {
267:         $res = array();
268:         foreach (self::$vars as $name => $foo) {
269:             $res[$name] = self::getVariable($name);
270:         }
271:         return $res;
272:     }
273: 
274: 
275: 
276:     /**
277:      * Returns expanded variable.
278:      * @param  string
279:      * @return string
280:      * @throws \InvalidStateException
281:      */
282:     public static function expand($var)
283:     {
284:         if (is_string($var) && strpos($var, '%') !== FALSE) {
285:             return @preg_replace_callback('#%([a-z0-9_-]*)%#i', array(__CLASS__, 'expandCb'), $var); // intentionally @ due PHP bug #39257
286:         }
287:         return $var;
288:     }
289: 
290: 
291: 
292:     /**
293:      * @see Environment::expand()
294:      * @param  array
295:      * @return string
296:      */
297:     private static function expandCb($m)
298:     {
299:         list(, $var) = $m;
300:         if ($var === '') return '%';
301: 
302:         static $livelock;
303:         if (isset($livelock[$var])) {
304:             throw new \InvalidStateException("Circular reference detected for variables: "
305:                 . implode(', ', array_keys($livelock)) . ".");
306:         }
307: 
308:         try {
309:             $livelock[$var] = TRUE;
310:             $val = self::getVariable($var);
311:             unset($livelock[$var]);
312:         } catch (\Exception $e) {
313:             $livelock = array();
314:             throw $e;
315:         }
316: 
317:         if ($val === NULL) {
318:             throw new \InvalidStateException("Unknown environment variable '$var'.");
319: 
320:         } elseif (!is_scalar($val)) {
321:             throw new \InvalidStateException("Environment variable '$var' is not scalar.");
322:         }
323: 
324:         return $val;
325:     }
326: 
327: 
328: 
329:     /********************* service locator ****************d*g**/
330: 
331: 
332: 
333:     /**
334:      * Get initial instance of service locator.
335:      * @return IServiceLocator
336:      */
337:     public static function getServiceLocator()
338:     {
339:         if (self::$serviceLocator === NULL) {
340:             self::$serviceLocator = self::getConfigurator()->createServiceLocator();
341:         }
342:         return self::$serviceLocator;
343:     }
344: 
345: 
346: 
347:     /**
348:      * Gets the service object of the specified type.
349:      * @param  string service name
350:      * @param  array  options in case service is not singleton
351:      * @return object
352:      */
353:     public static function getService($name, array $options = NULL)
354:     {
355:         return self::getServiceLocator()->getService($name, $options);
356:     }
357: 
358: 
359: 
360:     /**
361:      * Adds new Environment::get<Service>() method.
362:      * @param  string  service name
363:      * @param  string  alias name
364:      * @return void
365:      */
366:     public static function setServiceAlias($service, $alias)
367:     {
368:         self::$aliases['get' . ucfirst($alias)] = $service;
369:     }
370: 
371: 
372: 
373:     /**
374:      * Calling to undefined static method.
375:      * @param  string  method name
376:      * @param  array   arguments
377:      * @return object  service
378:      */
379:     public static function __callStatic($name, $args)
380:     {
381:         if (isset(self::$aliases[$name])) {
382:             return self::getServiceLocator()->getService(self::$aliases[$name], $args);
383:         } else {
384:             throw new \MemberAccessException("Call to undefined static method Nette\\Environment::$name().");
385:         }
386:     }
387: 
388: 
389: 
390:     /**
391:      * @return Nette\Web\HttpRequest
392:      */
393:     public static function getHttpRequest()
394:     {
395:         return self::getServiceLocator()->getService(self::$aliases[__FUNCTION__]);
396:     }
397: 
398: 
399: 
400:     /**
401:      * @return Nette\Web\HttpContext
402:      */
403:     public static function getHttpContext()
404:     {
405:         return self::getServiceLocator()->getService(self::$aliases[__FUNCTION__]);
406:     }
407: 
408: 
409: 
410:     /**
411:      * @return Nette\Web\HttpResponse
412:      */
413:     public static function getHttpResponse()
414:     {
415:         return self::getServiceLocator()->getService(self::$aliases[__FUNCTION__]);
416:     }
417: 
418: 
419: 
420:     /**
421:      * @return Nette\Application\Application
422:      */
423:     public static function getApplication()
424:     {
425:         return self::getServiceLocator()->getService(self::$aliases[__FUNCTION__]);
426:     }
427: 
428: 
429: 
430:     /**
431:      * @return Nette\Web\User
432:      */
433:     public static function getUser()
434:     {
435:         return self::getServiceLocator()->getService(self::$aliases[__FUNCTION__]);
436:     }
437: 
438: 
439: 
440:     /********************* service factories ****************d*g**/
441: 
442: 
443: 
444:     /**
445:      * @param  string
446:      * @return Nette\Caching\Cache
447:      */
448:     public static function getCache($namespace = '')
449:     {
450:         return new Nette\Caching\Cache(
451:             self::getService('Nette\\Caching\\ICacheStorage'),
452:             $namespace
453:         );
454:     }
455: 
456: 
457: 
458:     /**
459:      * Returns instance of session or session namespace.
460:      * @param  string
461:      * @return Nette\Web\Session
462:      */
463:     public static function getSession($namespace = NULL)
464:     {
465:         $handler = self::getService('Nette\\Web\\Session');
466:         return $namespace === NULL ? $handler : $handler->getNamespace($namespace);
467:     }
468: 
469: 
470: 
471:     /********************* global configuration ****************d*g**/
472: 
473: 
474: 
475:     /**
476:      * Loads global configuration from file and process it.
477:      * @param  string|Nette\Config\Config  file name or Config object
478:      * @return \ArrayObject
479:      */
480:     public static function loadConfig($file = NULL)
481:     {
482:         return self::$config = self::getConfigurator()->loadConfig($file);
483:     }
484: 
485: 
486: 
487:     /**
488:      * Returns the global configuration.
489:      * @param  string key
490:      * @param  mixed  default value
491:      * @return mixed
492:      */
493:     public static function getConfig($key = NULL, $default = NULL)
494:     {
495:         if (func_num_args()) {
496:             return isset(self::$config[$key]) ? self::$config[$key] : $default;
497: 
498:         } else {
499:             return self::$config;
500:         }
501:     }
502: 
503: 
504: 
505:     /********************* critical section ****************d*g**/
506: 
507: 
508: 
509:     /**
510:      * Enters the critical section, other threads are locked out.
511:      * @param  string
512:      * @return void
513:      */
514:     public static function enterCriticalSection($key)
515:     {
516:         $file = self::getVariable('tempDir') . "/criticalSection-" . md5($key);
517:         $handle = fopen($file, 'w');
518:         flock($handle, LOCK_EX);
519:         self::$criticalSections[$key] = array($file, $handle);
520:     }
521: 
522: 
523: 
524:     /**
525:      * Leaves the critical section, other threads can now enter it.
526:      * @param  string
527:      * @return void
528:      */
529:     public static function leaveCriticalSection($key)
530:     {
531:         if (!isset(self::$criticalSections[$key])) {
532:             throw new \InvalidStateException('Critical section has not been initialized.');
533:         }
534:         list($file, $handle) = self::$criticalSections[$key];
535:         @unlink($file);
536:         fclose($handle);
537:         unset(self::$criticalSections[$key]);
538:     }
539: 
540: }
541: 
Nette Framework 0.9.7 API documentation generated by ApiGen 2.3.0