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

  • Container
  • ContainerBuilder
  • Helpers
  • ServiceDefinition
  • Statement

Exceptions

  • MissingServiceException
  • ServiceCreationException
  • 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\DI;
 13: 
 14: use Nette,
 15:     Nette\Utils\Validators,
 16:     Nette\Utils\Strings,
 17:     Nette\Utils\PhpGenerator\Helpers as PhpHelpers,
 18:     Nette\Utils\PhpGenerator\PhpLiteral;
 19: 
 20: 
 21: 
 22: /**
 23:  * Basic container builder.
 24:  *
 25:  * @author     David Grudl
 26:  * @property-read ServiceDefinition[] $definitions
 27:  * @property-read array $dependencies
 28:  */
 29: class ContainerBuilder extends Nette\Object
 30: {
 31:     const CREATED_SERVICE = 'self',
 32:         THIS_CONTAINER = 'container';
 33: 
 34:     /** @var array  %param% will be expanded */
 35:     public $parameters = array();
 36: 
 37:     /** @var ServiceDefinition[] */
 38:     private $definitions = array();
 39: 
 40:     /** @var array for auto-wiring */
 41:     private $classes;
 42: 
 43:     /** @var array of file names */
 44:     private $dependencies = array();
 45: 
 46: 
 47: 
 48:     /**
 49:      * Adds new service definition. The expressions %param% and @service will be expanded.
 50:      * @param  string
 51:      * @return ServiceDefinition
 52:      */
 53:     public function addDefinition($name)
 54:     {
 55:         if (isset($this->definitions[$name])) {
 56:             throw new Nette\InvalidStateException("Service '$name' has already been added.");
 57:         }
 58:         return $this->definitions[$name] = new ServiceDefinition;
 59:     }
 60: 
 61: 
 62: 
 63:     /**
 64:      * Removes the specified service definition.
 65:      * @param  string
 66:      * @return void
 67:      */
 68:     public function removeDefinition($name)
 69:     {
 70:         unset($this->definitions[$name]);
 71:     }
 72: 
 73: 
 74: 
 75:     /**
 76:      * Gets the service definition.
 77:      * @param  string
 78:      * @return ServiceDefinition
 79:      */
 80:     public function getDefinition($name)
 81:     {
 82:         if (!isset($this->definitions[$name])) {
 83:             throw new MissingServiceException("Service '$name' not found.");
 84:         }
 85:         return $this->definitions[$name];
 86:     }
 87: 
 88: 
 89: 
 90:     /**
 91:      * Gets all service definitions.
 92:      * @return array
 93:      */
 94:     public function getDefinitions()
 95:     {
 96:         return $this->definitions;
 97:     }
 98: 
 99: 
100: 
101:     /**
102:      * Does the service definition exist?
103:      * @param  string
104:      * @return bool
105:      */
106:     public function hasDefinition($name)
107:     {
108:         return isset($this->definitions[$name]);
109:     }
110: 
111: 
112: 
113:     /********************* class resolving ****************d*g**/
114: 
115: 
116: 
117:     /**
118:      * Resolves service name by type.
119:      * @param  string  class or interface
120:      * @return string  service name or NULL
121:      * @throws ServiceCreationException
122:      */
123:     public function getByType($class)
124:     {
125:         $lower = ltrim(strtolower($class), '\\');
126:         if (!isset($this->classes[$lower])) {
127:             return;
128: 
129:         } elseif (count($this->classes[$lower]) === 1) {
130:             return $this->classes[$lower][0];
131: 
132:         } else {
133:             throw new ServiceCreationException("Multiple services of type $class found: " . implode(', ', $this->classes[$lower]));
134:         }
135:     }
136: 
137: 
138: 
139:     /**
140:      * Gets the service objects of the specified tag.
141:      * @param  string
142:      * @return array of [service name => tag attributes]
143:      */
144:     public function findByTag($tag)
145:     {
146:         $found = array();
147:         foreach ($this->definitions as $name => $def) {
148:             if (isset($def->tags[$tag]) && $def->shared) {
149:                 $found[$name] = $def->tags[$tag];
150:             }
151:         }
152:         return $found;
153:     }
154: 
155: 
156: 
157:     /**
158:      * Creates a list of arguments using autowiring.
159:      * @return array
160:      */
161:     public function autowireArguments($class, $method, array $arguments)
162:     {
163:         $rc = Nette\Reflection\ClassType::from($class);
164:         if (!$rc->hasMethod($method)) {
165:             if (!Nette\Utils\Validators::isList($arguments)) {
166:                 throw new ServiceCreationException("Unable to pass specified arguments to $class::$method().");
167:             }
168:             return $arguments;
169:         }
170: 
171:         $rm = $rc->getMethod($method);
172:         if ($rm->isAbstract() || !$rm->isPublic()) {
173:             throw new ServiceCreationException("$rm is not callable.");
174:         }
175:         $this->addDependency($rm->getFileName());
176:         return Helpers::autowireArguments($rm, $arguments, $this);
177:     }
178: 
179: 
180: 
181:     /**
182:      * Generates $dependencies, $classes and expands and normalize class names.
183:      * @return array
184:      */
185:     public function prepareClassList()
186:     {
187:         // complete class-factory pairs; expand classes
188:         foreach ($this->definitions as $name => $def) {
189:             if ($def->class === self::CREATED_SERVICE || ($def->factory && $def->factory->entity === self::CREATED_SERVICE)) {
190:                 $def->class = $name;
191:                 $def->internal = TRUE;
192:                 if ($def->factory && $def->factory->entity === self::CREATED_SERVICE) {
193:                     $def->factory->entity = $def->class;
194:                 }
195:                 unset($this->definitions[$name]);
196:                 $this->definitions['_anonymous_' . str_replace('\\', '_', strtolower(trim($name, '\\')))] = $def;
197:             }
198: 
199:             if ($def->class) {
200:                 $def->class = $this->expand($def->class);
201:                 if (!$def->factory) {
202:                     $def->factory = new Statement($def->class);
203:                 }
204:             } elseif (!$def->factory) {
205:                 throw new ServiceCreationException("Class and factory are missing in service '$name' definition.");
206:             }
207:         }
208: 
209:         // complete classes
210:         $this->classes = FALSE;
211:         foreach ($this->definitions as $name => $def) {
212:             $this->resolveClass($name);
213:         }
214: 
215:         //  build auto-wiring list
216:         $this->classes = array();
217:         foreach ($this->definitions as $name => $def) {
218:             if (!$def->class) {
219:                 continue;
220:             }
221:             if (!class_exists($def->class) && !interface_exists($def->class)) {
222:                 throw new Nette\InvalidStateException("Class $def->class has not been found.");
223:             }
224:             $def->class = Nette\Reflection\ClassType::from($def->class)->getName();
225:             if ($def->autowired) {
226:                 foreach (class_parents($def->class) + class_implements($def->class) + array($def->class) as $parent) {
227:                     $this->classes[strtolower($parent)][] = $name;
228:                 }
229:             }
230:         }
231: 
232:         foreach ($this->classes as $class => $foo) {
233:             $this->addDependency(Nette\Reflection\ClassType::from($class)->getFileName());
234:         }
235:     }
236: 
237: 
238: 
239:     private function resolveClass($name, $recursive = array())
240:     {
241:         if (isset($recursive[$name])) {
242:             throw new Nette\InvalidArgumentException('Circular reference detected for services: ' . implode(', ', array_keys($recursive)) . '.');
243:         }
244:         $recursive[$name] = TRUE;
245: 
246:         $def = $this->definitions[$name];
247:         $factory = $this->normalizeEntity($this->expand($def->factory->entity));
248: 
249:         if ($def->class) {
250:             return $def->class;
251: 
252:         } elseif (is_array($factory)) { // method calling
253:             if ($service = $this->getServiceName($factory[0])) {
254:                 if (Strings::contains($service, '\\')) { // @\Class
255:                     throw new ServiceCreationException("Unable resolve class name for service '$name'.");
256:                 }
257:                 $factory[0] = $this->resolveClass($service, $recursive);
258:                 if (!$factory[0]) {
259:                     return;
260:                 }
261:             }
262:             $factory = new Nette\Callback($factory);
263:             if (!$factory->isCallable()) {
264:                 throw new Nette\InvalidStateException("Factory '$factory' is not callable.");
265:             }
266:             try {
267:                 $reflection = $factory->toReflection();
268:                 $def->class = preg_replace('#[|\s].*#', '', $reflection->getAnnotation('return'));
269:                 if ($def->class && !class_exists($def->class) && $def->class[0] !== '\\' && $reflection instanceof \ReflectionMethod) {
270:                     $def->class = $reflection->getDeclaringClass()->getNamespaceName() . '\\' . $def->class;
271:                 }
272:             } catch (\ReflectionException $e) {
273:             }
274: 
275:         } elseif ($service = $this->getServiceName($factory)) { // alias or factory
276:             if (Strings::contains($service, '\\')) { // @\Class
277:                 $def->autowired = FALSE;
278:                 return $def->class = $service;
279:             }
280:             if ($this->definitions[$service]->shared) {
281:                 $def->autowired = FALSE;
282:             }
283:             return $def->class = $this->resolveClass($service, $recursive);
284: 
285:         } else {
286:             return $def->class = $factory; // class name
287:         }
288:     }
289: 
290: 
291: 
292:     /**
293:      * Adds a file to the list of dependencies.
294:      * @return ContainerBuilder  provides a fluent interface
295:      */
296:     public function addDependency($file)
297:     {
298:         $this->dependencies[$file] = TRUE;
299:         return $this;
300:     }
301: 
302: 
303: 
304:     /**
305:      * Returns the list of dependent files.
306:      * @return array
307:      */
308:     public function getDependencies()
309:     {
310:         unset($this->dependencies[FALSE]);
311:         return array_keys($this->dependencies);
312:     }
313: 
314: 
315: 
316:     /********************* code generator ****************d*g**/
317: 
318: 
319: 
320:     /**
321:      * Generates PHP class.
322:      * @return Nette\Utils\PhpGenerator\ClassType
323:      */
324:     public function generateClass($parentClass = 'Nette\DI\Container')
325:     {
326:         unset($this->definitions[self::THIS_CONTAINER]);
327:         $this->addDefinition(self::THIS_CONTAINER)->setClass($parentClass);
328: 
329:         $this->prepareClassList();
330: 
331:         $class = new Nette\Utils\PhpGenerator\ClassType('Container');
332:         $class->addExtend($parentClass);
333:         $class->addMethod('__construct')
334:             ->addBody('parent::__construct(?);', array($this->expand($this->parameters)));
335: 
336:         $classes = $class->addProperty('classes', array());
337:         foreach ($this->classes as $name => $foo) {
338:             try {
339:                 $classes->value[$name] = $this->getByType($name);
340:             } catch (ServiceCreationException $e) {
341:                 $classes->value[$name] = new PhpLiteral('FALSE, //' . strstr($e->getMessage(), ':'));
342:             }
343:         }
344: 
345:         $definitions = $this->definitions;
346:         ksort($definitions);
347: 
348:         $meta = $class->addProperty('meta', array());
349:         foreach ($definitions as $name => $def) {
350:             if ($def->shared) {
351:                 foreach ($this->expand($def->tags) as $tag => $value) {
352:                     $meta->value[$name][Container::TAGS][$tag] = $value;
353:                 }
354:             }
355:         }
356: 
357:         foreach ($definitions as $name => $def) {
358:             try {
359:                 $type = $def->class ?: 'object';
360:                 $methodName = Container::getMethodName($name, $def->shared);
361:                 if (!PhpHelpers::isIdentifier($methodName)) {
362:                     throw new ServiceCreationException('Name contains invalid characters.');
363:                 }
364:                 if ($def->shared && !$def->internal && PhpHelpers::isIdentifier($name)) {
365:                     $class->addDocument("@property $type \$$name");
366:                 }
367:                 $method = $class->addMethod($methodName)
368:                     ->addDocument("@return $type")
369:                     ->setVisibility($def->shared || $def->internal ? 'protected' : 'public')
370:                     ->setBody($name === self::THIS_CONTAINER ? 'return $this;' : $this->generateService($name));
371: 
372:                 foreach ($this->expand($def->parameters) as $k => $v) {
373:                     $tmp = explode(' ', is_int($k) ? $v : $k);
374:                     $param = is_int($k) ? $method->addParameter(end($tmp)) : $method->addParameter(end($tmp), $v);
375:                     if (isset($tmp[1])) {
376:                         $param->setTypeHint($tmp[0]);
377:                     }
378:                 }
379:             } catch (\Exception $e) {
380:                 throw new ServiceCreationException("Service '$name': " . $e->getMessage(), NULL, $e);
381:             }
382:         }
383: 
384:         return $class;
385:     }
386: 
387: 
388: 
389:     /**
390:      * Generates body of service method.
391:      * @return string
392:      */
393:     private function generateService($name)
394:     {
395:         $def = $this->definitions[$name];
396:         $parameters = $this->parameters;
397:         foreach ($this->expand($def->parameters) as $k => $v) {
398:             $v = explode(' ', is_int($k) ? $v : $k);
399:             $parameters[end($v)] = new PhpLiteral('$' . end($v));
400:         }
401: 
402:         $code = '$service = ' . $this->formatStatement(Helpers::expand($def->factory, $parameters, TRUE)) . ";\n";
403: 
404:         $entity = $this->normalizeEntity($def->factory->entity);
405:         if ($def->class && $def->class !== $entity && !$this->getServiceName($entity)) {
406:             $code .= PhpHelpers::formatArgs("if (!\$service instanceof $def->class) {\n"
407:                 . "\tthrow new Nette\\UnexpectedValueException(?);\n}\n",
408:                 array("Unable to create service '$name', value returned by factory is not $def->class type.")
409:             );
410:         }
411: 
412:         foreach ((array) $def->setup as $setup) {
413:             $setup = Helpers::expand($setup, $parameters, TRUE);
414:             if (is_string($setup->entity) && strpbrk($setup->entity, ':@?') === FALSE) { // auto-prepend @self
415:                 $setup->entity = array("@$name", $setup->entity);
416:             }
417:             $code .= $this->formatStatement($setup, $name) . ";\n";
418:         }
419: 
420:         return $code .= 'return $service;';
421:     }
422: 
423: 
424: 
425:     /**
426:      * Formats PHP code for class instantiating, function calling or property setting in PHP.
427:      * @return string
428:      * @internal
429:      */
430:     public function formatStatement(Statement $statement, $self = NULL)
431:     {
432:         $entity = $this->normalizeEntity($statement->entity);
433:         $arguments = $statement->arguments;
434: 
435:         if (is_string($entity) && Strings::contains($entity, '?')) { // PHP literal
436:             return $this->formatPhp($entity, $arguments, $self);
437: 
438:         } elseif ($service = $this->getServiceName($entity)) { // factory calling or service retrieving
439:             if ($this->definitions[$service]->shared) {
440:                 if ($arguments) {
441:                     throw new ServiceCreationException("Unable to call service '$entity'.");
442:                 }
443:                 return $this->formatPhp('$this->getService(?)', array($service));
444:             }
445:             $params = array();
446:             foreach ($this->definitions[$service]->parameters as $k => $v) {
447:                 $params[] = preg_replace('#\w+$#', '\$$0', (is_int($k) ? $v : $k)) . (is_int($k) ? '' : ' = ' . PhpHelpers::dump($v));
448:             }
449:             $rm = new Nette\Reflection\GlobalFunction(create_function(implode(', ', $params), ''));
450:             $arguments = Helpers::autowireArguments($rm, $arguments, $this);
451:             return $this->formatPhp('$this->?(?*)', array(Container::getMethodName($service, FALSE), $arguments), $self);
452: 
453:         } elseif ($entity === 'not') { // operator
454:             return $this->formatPhp('!?', array($arguments[0]));
455: 
456:         } elseif (is_string($entity)) { // class name
457:             if ($constructor = Nette\Reflection\ClassType::from($entity)->getConstructor()) {
458:                 $this->addDependency($constructor->getFileName());
459:                 $arguments = Helpers::autowireArguments($constructor, $arguments, $this);
460:             } elseif ($arguments) {
461:                 throw new ServiceCreationException("Unable to pass arguments, class $entity has no constructor.");
462:             }
463:             return $this->formatPhp("new $entity" . ($arguments ? '(?*)' : ''), array($arguments), $self);
464: 
465:         } elseif (!Validators::isList($entity) || count($entity) !== 2) {
466:             throw new Nette\InvalidStateException("Expected class, method or property, " . PhpHelpers::dump($entity) . " given.");
467: 
468:         } elseif ($entity[0] === '') { // globalFunc
469:             return $this->formatPhp("$entity[1](?*)", array($arguments), $self);
470: 
471:         } elseif (Strings::contains($entity[1], '$')) { // property setter
472:             Validators::assert($arguments, 'list:1', "setup arguments for '" . Nette\Callback::create($entity) . "'");
473:             if ($this->getServiceName($entity[0], $self)) {
474:                 return $this->formatPhp('?->? = ?', array($entity[0], substr($entity[1], 1), $arguments[0]), $self);
475:             } else {
476:                 return $this->formatPhp($entity[0] . '::$? = ?', array(substr($entity[1], 1), $arguments[0]), $self);
477:             }
478: 
479:         } elseif ($service = $this->getServiceName($entity[0], $self)) { // service method
480:             if ($this->definitions[$service]->class) {
481:                 $arguments = $this->autowireArguments($this->definitions[$service]->class, $entity[1], $arguments);
482:             }
483:             return $this->formatPhp('?->?(?*)', array($entity[0], $entity[1], $arguments), $self);
484: 
485:         } else { // static method
486:             $arguments = $this->autowireArguments($entity[0], $entity[1], $arguments);
487:             return $this->formatPhp("$entity[0]::$entity[1](?*)", array($arguments), $self);
488:         }
489:     }
490: 
491: 
492: 
493:     /**
494:      * Formats PHP statement.
495:      * @return string
496:      */
497:     public function formatPhp($statement, $args, $self = NULL)
498:     {
499:         $that = $this;
500:         array_walk_recursive($args, function(&$val) use ($self, $that) {
501:             list($val) = $that->normalizeEntity(array($val));
502: 
503:             if ($val instanceof Statement) {
504:                 $val = new PhpLiteral($that->formatStatement($val, $self));
505: 
506:             } elseif ($val === '@' . ContainerBuilder::THIS_CONTAINER) {
507:                 $val = new PhpLiteral('$this');
508: 
509:             } elseif ($service = $that->getServiceName($val, $self)) {
510:                 $val = $service === $self ? '$service' : $that->formatStatement(new Statement($val));
511:                 $val = new PhpLiteral($val);
512:             }
513:         });
514:         return PhpHelpers::formatArgs($statement, $args);
515:     }
516: 
517: 
518: 
519:     /**
520:      * Expands %placeholders% in strings (recursive).
521:      * @param  mixed
522:      * @return mixed
523:      */
524:     public function expand($value)
525:     {
526:         return Helpers::expand($value, $this->parameters, TRUE);
527:     }
528: 
529: 
530: 
531:     /** @internal */
532:     public function normalizeEntity($entity)
533:     {
534:         if (is_string($entity) && Strings::contains($entity, '::') && !Strings::contains($entity, '?')) { // Class::method -> [Class, method]
535:             $entity = explode('::', $entity);
536:         }
537: 
538:         if (is_array($entity) && $entity[0] instanceof ServiceDefinition) { // [ServiceDefinition, ...] -> [@serviceName, ...]
539:             $tmp = array_keys($this->definitions, $entity[0], TRUE);
540:             $entity[0] = "@$tmp[0]";
541: 
542:         } elseif ($entity instanceof ServiceDefinition) { // ServiceDefinition -> @serviceName
543:             $tmp = array_keys($this->definitions, $entity, TRUE);
544:             $entity = "@$tmp[0]";
545: 
546:         } elseif (is_array($entity) && $entity[0] === $this) { // [$this, ...] -> [@container, ...]
547:             $entity[0] = '@' . ContainerBuilder::THIS_CONTAINER;
548:         }
549:         return $entity; // Class, @service, [Class, member], [@service, member], [, globalFunc]
550:     }
551: 
552: 
553: 
554:     /**
555:      * Converts @service or @\Class -> service name and checks its existence.
556:      * @param  mixed
557:      * @return string  of FALSE, if argument is not service name
558:      */
559:     public function getServiceName($arg, $self = NULL)
560:     {
561:         if (!is_string($arg) || !preg_match('#^@[\w\\\\.].+$#', $arg)) {
562:             return FALSE;
563:         }
564:         $service = substr($arg, 1);
565:         if ($service === self::CREATED_SERVICE) {
566:             $service = $self;
567:         }
568:         if (Strings::contains($service, '\\')) {
569:             if ($this->classes === FALSE) { // may be disabled by prepareClassList
570:                 return $service;
571:             }
572:             $res = $this->getByType($service);
573:             if (!$res) {
574:                 throw new ServiceCreationException("Reference to missing service of type $service.");
575:             }
576:             return $res;
577:         }
578:         if (!isset($this->definitions[$service])) {
579:             throw new ServiceCreationException("Reference to missing service '$service'.");
580:         }
581:         return $service;
582:     }
583: 
584: }
585: 
Nette Framework 2.0.6 API API documentation generated by ApiGen 2.7.0