Namespaces

  • Nette
    • Application
      • Diagnostics
      • Responses
      • Routers
      • UI
    • Caching
      • Storages
    • ComponentModel
    • Config
      • Adapters
      • Extensions
    • Database
      • Diagnostics
      • Drivers
      • Reflection
      • Table
    • DI
      • Diagnostics
    • Diagnostics
    • Forms
      • Controls
      • Rendering
    • Http
    • Iterators
    • Latte
      • Macros
    • Loaders
    • Localization
    • Mail
    • Reflection
    • Security
      • Diagnostics
    • Templating
    • Utils
      • PhpGenerator
  • NetteModule
  • None
  • PHP

Classes

  • Compiler
  • CompilerExtension
  • Configurator
  • Helpers
  • Loader

Interfaces

  • IAdapter
  • Overview
  • Namespace
  • Class
  • Tree
  1: <?php
  2: 
  3: /**
  4:  * This file is part of the Nette Framework (http://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\Config;
 13: 
 14: use Nette,
 15:     Nette\Utils\Validators;
 16: 
 17: 
 18: 
 19: /**
 20:  * DI container compiler.
 21:  *
 22:  * @author     David Grudl
 23:  *
 24:  * @property-read CompilerExtension[] $extensions
 25:  * @property-read Nette\DI\ContainerBuilder $containerBuilder
 26:  * @property-read array $config
 27:  */
 28: class Compiler extends Nette\Object
 29: {
 30:     /** @var CompilerExtension[] */
 31:     private $extensions = array();
 32: 
 33:     /** @var Nette\DI\ContainerBuilder */
 34:     private $container;
 35: 
 36:     /** @var array */
 37:     private $config;
 38: 
 39:     /** @var array reserved section names */
 40:     private static $reserved = array('services' => 1, 'factories' => 1, 'parameters' => 1);
 41: 
 42: 
 43: 
 44:     /**
 45:      * Add custom configurator extension.
 46:      * @return Compiler  provides a fluent interface
 47:      */
 48:     public function addExtension($name, CompilerExtension $extension)
 49:     {
 50:         if (isset(self::$reserved[$name])) {
 51:             throw new Nette\InvalidArgumentException("Name '$name' is reserved.");
 52:         }
 53:         $this->extensions[$name] = $extension->setCompiler($this, $name);
 54:         return $this;
 55:     }
 56: 
 57: 
 58: 
 59:     /**
 60:      * @return array
 61:      */
 62:     public function getExtensions()
 63:     {
 64:         return $this->extensions;
 65:     }
 66: 
 67: 
 68: 
 69:     /**
 70:      * @return Nette\DI\ContainerBuilder
 71:      */
 72:     public function getContainerBuilder()
 73:     {
 74:         return $this->container;
 75:     }
 76: 
 77: 
 78: 
 79:     /**
 80:      * Returns configuration without expanded parameters.
 81:      * @return array
 82:      */
 83:     public function getConfig()
 84:     {
 85:         return $this->config;
 86:     }
 87: 
 88: 
 89: 
 90:     /**
 91:      * @return string
 92:      */
 93:     public function compile(array $config, $className, $parentName)
 94:     {
 95:         $this->config = $config;
 96:         $this->container = new Nette\DI\ContainerBuilder;
 97:         $this->processParameters();
 98:         $this->processExtensions();
 99:         $this->processServices();
100:         return $this->generateCode($className, $parentName);
101:     }
102: 
103: 
104: 
105:     public function processParameters()
106:     {
107:         if (isset($this->config['parameters'])) {
108:             $this->container->parameters = $this->config['parameters'];
109:         }
110:     }
111: 
112: 
113: 
114:     public function processExtensions()
115:     {
116:         foreach ($this->extensions as $name => $extension) {
117:             $extension->loadConfiguration();
118:         }
119: 
120:         if ($extra = array_diff_key($this->config, self::$reserved, $this->extensions)) {
121:             $extra = implode("', '", array_keys($extra));
122:             throw new Nette\InvalidStateException("Found sections '$extra' in configuration, but corresponding extensions are missing.");
123:         }
124:     }
125: 
126: 
127: 
128:     public function processServices()
129:     {
130:         $this->parseServices($this->container, $this->config);
131: 
132:         foreach ($this->extensions as $name => $extension) {
133:             $this->container->addDefinition($name)
134:                 ->setClass('Nette\DI\NestedAccessor', array('@container', $name))
135:                 ->setAutowired(FALSE);
136: 
137:             if (isset($this->config[$name])) {
138:                 $this->parseServices($this->container, $this->config[$name], $name);
139:             }
140:         }
141: 
142:         foreach ($this->container->getDefinitions() as $name => $def) {
143:             $factory = $name . 'Factory';
144:             if (!$def->shared && !$def->internal && !$this->container->hasDefinition($factory)) {
145:                 $this->container->addDefinition($factory)
146:                     ->setClass('Nette\Callback', array('@container', Nette\DI\Container::getMethodName($name, FALSE)))
147:                     ->setAutowired(FALSE)
148:                     ->tags = $def->tags;
149:             }
150:         }
151:     }
152: 
153: 
154: 
155:     public function generateCode($className, $parentName)
156:     {
157:         foreach ($this->extensions as $extension) {
158:             $extension->beforeCompile();
159:             $this->container->addDependency(Nette\Reflection\ClassType::from($extension)->getFileName());
160:         }
161: 
162:         $classes[] = $class = $this->container->generateClass($parentName);
163:         $class->setName($className)
164:             ->addMethod('initialize');
165: 
166:         foreach ($this->extensions as $extension) {
167:             $extension->afterCompile($class);
168:         }
169: 
170:         $defs = $this->container->getDefinitions();
171:         ksort($defs);
172:         $list = array_keys($defs);
173:         foreach (array_reverse($defs, TRUE) as $name => $def) {
174:             if ($def->class === 'Nette\DI\NestedAccessor' && ($found = preg_grep('#^'.$name.'\.#i', $list))) {
175:                 $list = array_diff($list, $found);
176:                 $def->class = $className . '_' . preg_replace('#\W+#', '_', $name);
177:                 $class->documents = preg_replace("#\S+(?= \\$$name$)#", $def->class, $class->documents);
178:                 $classes[] = $accessor = new Nette\Utils\PhpGenerator\ClassType($def->class);
179:                 foreach ($found as $item) {
180:                     $short = substr($item, strlen($name)  + 1);
181:                     $accessor->addDocument($defs[$item]->shared
182:                         ? "@property {$defs[$item]->class} \$$short"
183:                         : "@method {$defs[$item]->class} create" . ucfirst("$short()"));
184:                 }
185:             }
186:         }
187: 
188:         return implode("\n\n\n", $classes);
189:     }
190: 
191: 
192: 
193:     /********************* tools ****************d*g**/
194: 
195: 
196: 
197:     /**
198:      * Parses section 'services' from configuration file.
199:      * @return void
200:      */
201:     public static function parseServices(Nette\DI\ContainerBuilder $container, array $config, $namespace = NULL)
202:     {
203:         $services = isset($config['services']) ? $config['services'] : array();
204:         $factories = isset($config['factories']) ? $config['factories'] : array();
205:         if ($tmp = array_intersect_key($services, $factories)) {
206:             $tmp = implode("', '", array_keys($tmp));
207:             throw new Nette\DI\ServiceCreationException("It is not allowed to use services and factories with the same names: '$tmp'.");
208:         }
209: 
210:         $all = $services + $factories;
211:         uasort($all, function($a, $b) {
212:             return strcmp(Helpers::isInheriting($a), Helpers::isInheriting($b));
213:         });
214: 
215:         foreach ($all as $name => $def) {
216:             $shared = array_key_exists($name, $services);
217:             $name = ($namespace ? $namespace . '.' : '') . $name;
218: 
219:             if (($parent = Helpers::takeParent($def)) && $parent !== $name) {
220:                 $container->removeDefinition($name);
221:                 $definition = $container->addDefinition($name);
222:                 if ($parent !== Helpers::OVERWRITE) {
223:                     foreach ($container->getDefinition($parent) as $k => $v) {
224:                         $definition->$k = unserialize(serialize($v)); // deep clone
225:                     }
226:                 }
227:             } elseif ($container->hasDefinition($name)) {
228:                 $definition = $container->getDefinition($name);
229:                 if ($definition->shared !== $shared) {
230:                     throw new Nette\DI\ServiceCreationException("It is not allowed to use service and factory with the same name '$name'.");
231:                 }
232:             } else {
233:                 $definition = $container->addDefinition($name);
234:             }
235:             try {
236:                 static::parseService($definition, $def, $shared);
237:             } catch (\Exception $e) {
238:                 throw new Nette\DI\ServiceCreationException("Service '$name': " . $e->getMessage(), NULL, $e);
239:             }
240:         }
241:     }
242: 
243: 
244: 
245:     /**
246:      * Parses single service from configuration file.
247:      * @return void
248:      */
249:     public static function parseService(Nette\DI\ServiceDefinition $definition, $config, $shared = TRUE)
250:     {
251:         if ($config === NULL) {
252:             return;
253:         } elseif (!is_array($config)) {
254:             $config = array('class' => NULL, 'factory' => $config);
255:         }
256: 
257:         $known = $shared
258:             ? array('class', 'factory', 'arguments', 'setup', 'autowired', 'run', 'tags')
259:             : array('class', 'factory', 'arguments', 'setup', 'autowired', 'tags', 'internal', 'parameters');
260: 
261:         if ($error = array_diff(array_keys($config), $known)) {
262:             throw new Nette\InvalidStateException("Unknown key '" . implode("', '", $error) . "' in definition of service.");
263:         }
264: 
265:         $arguments = array();
266:         if (array_key_exists('arguments', $config)) {
267:             Validators::assertField($config, 'arguments', 'array');
268:             $arguments = self::filterArguments($config['arguments']);
269:             $definition->setArguments($arguments);
270:         }
271: 
272:         if (array_key_exists('class', $config) || array_key_exists('factory', $config)) {
273:             $definition->class = NULL;
274:             $definition->factory = NULL;
275:         }
276: 
277:         if (array_key_exists('class', $config)) {
278:             Validators::assertField($config, 'class', 'string|stdClass|null');
279:             if ($config['class'] instanceof \stdClass) {
280:                 $definition->setClass($config['class']->value, self::filterArguments($config['class']->attributes));
281:             } else {
282:                 $definition->setClass($config['class'], $arguments);
283:             }
284:         }
285: 
286:         if (array_key_exists('factory', $config)) {
287:             Validators::assertField($config, 'factory', 'callable|stdClass|null');
288:             if ($config['factory'] instanceof \stdClass) {
289:                 $definition->setFactory($config['factory']->value, self::filterArguments($config['factory']->attributes));
290:             } else {
291:                 $definition->setFactory($config['factory'], $arguments);
292:             }
293:         }
294: 
295:         if (isset($config['setup'])) {
296:             if (Helpers::takeParent($config['setup'])) {
297:                 $definition->setup = array();
298:             }
299:             Validators::assertField($config, 'setup', 'list');
300:             foreach ($config['setup'] as $id => $setup) {
301:                 Validators::assert($setup, 'callable|stdClass', "setup item #$id");
302:                 if ($setup instanceof \stdClass) {
303:                     Validators::assert($setup->value, 'callable', "setup item #$id");
304:                     $definition->addSetup($setup->value, self::filterArguments($setup->attributes));
305:                 } else {
306:                     $definition->addSetup($setup);
307:                 }
308:             }
309:         }
310: 
311:         $definition->setShared($shared);
312:         if (isset($config['parameters'])) {
313:             Validators::assertField($config, 'parameters', 'array');
314:             $definition->setParameters($config['parameters']);
315:         }
316: 
317:         if (isset($config['autowired'])) {
318:             Validators::assertField($config, 'autowired', 'bool');
319:             $definition->setAutowired($config['autowired']);
320:         }
321: 
322:         if (isset($config['internal'])) {
323:             Validators::assertField($config, 'internal', 'bool');
324:             $definition->setInternal($config['internal']);
325:         }
326: 
327:         if (isset($config['run'])) {
328:             $config['tags']['run'] = (bool) $config['run'];
329:         }
330: 
331:         if (isset($config['tags'])) {
332:             Validators::assertField($config, 'tags', 'array');
333:             if (Helpers::takeParent($config['tags'])) {
334:                 $definition->tags = array();
335:             }
336:             foreach ($config['tags'] as $tag => $attrs) {
337:                 if (is_int($tag) && is_string($attrs)) {
338:                     $definition->addTag($attrs);
339:                 } else {
340:                     $definition->addTag($tag, $attrs);
341:                 }
342:             }
343:         }
344:     }
345: 
346: 
347: 
348:     /**
349:      * Removes ... and replaces entities with Nette\DI\Statement.
350:      * @return array
351:      */
352:     public static function filterArguments(array $args)
353:     {
354:         foreach ($args as $k => $v) {
355:             if ($v === '...') {
356:                 unset($args[$k]);
357:             } elseif ($v instanceof \stdClass && isset($v->value, $v->attributes)) {
358:                 $args[$k] = new Nette\DI\Statement($v->value, self::filterArguments($v->attributes));
359:             }
360:         }
361:         return $args;
362:     }
363: 
364: }
365: 
Nette Framework 2.0.4 API API documentation generated by ApiGen 2.7.0