Packages

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

Classes

  • NArrayTools
  • NCallback
  • NComponent
  • NComponentContainer
  • NConfigurator
  • NDateTime53
  • NDebug
  • NEnvironment
  • NFramework
  • NFreezableObject
  • NGenericRecursiveIterator
  • NImage
  • NImageMagick
  • NInstanceFilterIterator
  • NObject
  • NObjectMixin
  • NPaginator
  • NRecursiveComponentIterator
  • NServiceLocator
  • NSmartCachingIterator
  • NString
  • NTools

Interfaces

  • IComponent
  • IComponentContainer
  • IDebuggable
  • IServiceLocator
  • ITranslator

Exceptions

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