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
      • Reflection
      • Table
    • DI
      • Config
        • Adapters
      • Extensions
    • Diagnostics
    • Forms
      • Controls
      • Rendering
    • Http
    • Iterators
    • Latte
    • Loaders
    • Localization
    • Mail
    • Neon
    • PhpGenerator
    • Reflection
    • Security
    • Templating
    • Utils
  • NetteModule
  • none
  • Tracy
    • Bridges
      • Nette

Classes

  • Compiler
  • CompilerExtension
  • Container
  • ContainerBuilder
  • ContainerFactory
  • ContainerLoader
  • ServiceDefinition
  • Statement

Exceptions

  • MissingServiceException
  • ServiceCreationException
  • 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\DI;
  9: 
 10: use Nette;
 11: use Nette\Utils\Validators;
 12: use Nette\Utils\Strings;
 13: use Nette\PhpGenerator\Helpers as PhpHelpers;
 14: use ReflectionClass;
 15: 
 16: 
 17: /**
 18:  * Basic container builder.
 19:  */
 20: class ContainerBuilder extends Nette\Object
 21: {
 22:     const THIS_SERVICE = 'self',
 23:         THIS_CONTAINER = 'container';
 24: 
 25:     /** @var array */
 26:     public $parameters = array();
 27: 
 28:     /** @var string */
 29:     private $className = 'Container';
 30: 
 31:     /** @var ServiceDefinition[] */
 32:     private $definitions = array();
 33: 
 34:     /** @var array of alias => service */
 35:     private $aliases = array();
 36: 
 37:     /** @var array for auto-wiring */
 38:     private $classes;
 39: 
 40:     /** @var string[] of classes excluded from auto-wiring */
 41:     private $excludedClasses = array();
 42: 
 43:     /** @var array of file names */
 44:     private $dependencies = array();
 45: 
 46:     /** @var Nette\PhpGenerator\ClassType[] */
 47:     private $generatedClasses = array();
 48: 
 49:     /** @var string */
 50:     /*private in 5.4*/public $currentService;
 51: 
 52: 
 53:     /**
 54:      * Adds new service definition.
 55:      * @param  string
 56:      * @return ServiceDefinition
 57:      */
 58:     public function addDefinition($name, ServiceDefinition $definition = NULL)
 59:     {
 60:         if (!is_string($name) || !$name) { // builder is not ready for falsy names such as '0'
 61:             throw new Nette\InvalidArgumentException(sprintf('Service name must be a non-empty string, %s given.', gettype($name)));
 62:         }
 63:         $name = isset($this->aliases[$name]) ? $this->aliases[$name] : $name;
 64:         if (isset($this->definitions[$name])) {
 65:             throw new Nette\InvalidStateException("Service '$name' has already been added.");
 66:         }
 67:         return $this->definitions[$name] = $definition ?: new ServiceDefinition;
 68:     }
 69: 
 70: 
 71:     /**
 72:      * Removes the specified service definition.
 73:      * @param  string
 74:      * @return void
 75:      */
 76:     public function removeDefinition($name)
 77:     {
 78:         $name = isset($this->aliases[$name]) ? $this->aliases[$name] : $name;
 79:         unset($this->definitions[$name]);
 80: 
 81:         if ($this->classes) {
 82:             foreach ($this->classes as & $tmp) {
 83:                 foreach ($tmp as & $names) {
 84:                     $names = array_values(array_diff($names, array($name)));
 85:                 }
 86:             }
 87:         }
 88:     }
 89: 
 90: 
 91:     /**
 92:      * Gets the service definition.
 93:      * @param  string
 94:      * @return ServiceDefinition
 95:      */
 96:     public function getDefinition($name)
 97:     {
 98:         $service = isset($this->aliases[$name]) ? $this->aliases[$name] : $name;
 99:         if (!isset($this->definitions[$service])) {
100:             throw new MissingServiceException("Service '$name' not found.");
101:         }
102:         return $this->definitions[$service];
103:     }
104: 
105: 
106:     /**
107:      * Gets all service definitions.
108:      * @return ServiceDefinition[]
109:      */
110:     public function getDefinitions()
111:     {
112:         return $this->definitions;
113:     }
114: 
115: 
116:     /**
117:      * Does the service definition or alias exist?
118:      * @param  string
119:      * @return bool
120:      */
121:     public function hasDefinition($name)
122:     {
123:         $name = isset($this->aliases[$name]) ? $this->aliases[$name] : $name;
124:         return isset($this->definitions[$name]);
125:     }
126: 
127: 
128:     /**
129:      * @param  string
130:      * @param  string
131:      */
132:     public function addAlias($alias, $service)
133:     {
134:         if (!is_string($alias) || !$alias) { // builder is not ready for falsy names such as '0'
135:             throw new Nette\InvalidArgumentException(sprintf('Alias name must be a non-empty string, %s given.', gettype($alias)));
136: 
137:         } elseif (!is_string($service) || !$service) { // builder is not ready for falsy names such as '0'
138:             throw new Nette\InvalidArgumentException(sprintf('Service name must be a non-empty string, %s given.', gettype($service)));
139: 
140:         } elseif (isset($this->aliases[$alias])) {
141:             throw new Nette\InvalidStateException("Alias '$alias' has already been added.");
142: 
143:         } elseif (isset($this->definitions[$alias])) {
144:             throw new Nette\InvalidStateException("Service '$alias' has already been added.");
145: 
146:         }
147:         $this->aliases[$alias] = $service;
148:     }
149: 
150: 
151:     /**
152:      * Gets all service aliases.
153:      * @return array
154:      */
155:     public function getAliases()
156:     {
157:         return $this->aliases;
158:     }
159: 
160: 
161:     /**
162:      * @return self
163:      */
164:     public function setClassName($name)
165:     {
166:         $this->className = (string) $name;
167:         return $this;
168:     }
169: 
170: 
171:     /**
172:      * @return string
173:      */
174:     public function getClassName()
175:     {
176:         return $this->className;
177:     }
178: 
179: 
180:     /********************* class resolving ****************d*g**/
181: 
182: 
183:     /**
184:      * Resolves service name by type.
185:      * @param  string  class or interface
186:      * @return string|NULL  service name or NULL
187:      * @throws ServiceCreationException
188:      */
189:     public function getByType($class)
190:     {
191:         $class = ltrim($class, '\\');
192: 
193:         if ($this->currentService !== NULL) {
194:             $curClass = $this->definitions[$this->currentService]->getClass();
195:             if ($curClass === $class || is_subclass_of($curClass, $class)) {
196:                 return $this->currentService;
197:             }
198:         }
199: 
200:         if (empty($this->classes[$class][TRUE])) {
201:             self::checkCase($class);
202:             return;
203: 
204:         } elseif (count($this->classes[$class][TRUE]) === 1) {
205:             return $this->classes[$class][TRUE][0];
206: 
207:         } else {
208:             throw new ServiceCreationException("Multiple services of type $class found: " . implode(', ', $this->classes[$class][TRUE]));
209:         }
210:     }
211: 
212: 
213:     /**
214:      * Gets the service names and definitions of the specified type.
215:      * @param  string
216:      * @return ServiceDefinition[]
217:      */
218:     public function findByType($class)
219:     {
220:         $class = ltrim($class, '\\');
221:         self::checkCase($class);
222:         $found = array();
223:         if (!empty($this->classes[$class])) {
224:             foreach (call_user_func_array('array_merge', $this->classes[$class]) as $name) {
225:                 $found[$name] = $this->definitions[$name];
226:             }
227:         }
228:         return $found;
229:     }
230: 
231: 
232:     /**
233:      * Gets the service objects of the specified tag.
234:      * @param  string
235:      * @return array of [service name => tag attributes]
236:      */
237:     public function findByTag($tag)
238:     {
239:         $found = array();
240:         foreach ($this->definitions as $name => $def) {
241:             if (($tmp = $def->getTag($tag)) !== NULL) {
242:                 $found[$name] = $tmp;
243:             }
244:         }
245:         return $found;
246:     }
247: 
248: 
249:     /**
250:      * Creates a list of arguments using autowiring.
251:      * @return array
252:      */
253:     public function autowireArguments($class, $method, array $arguments)
254:     {
255:         $rc = new ReflectionClass($class);
256:         if (!$rc->hasMethod($method)) {
257:             if (!Nette\Utils\Arrays::isList($arguments)) {
258:                 throw new ServiceCreationException("Unable to pass specified arguments to $class::$method().");
259:             }
260:             return $arguments;
261:         }
262: 
263:         $rm = $rc->getMethod($method);
264:         if (!$rm->isPublic()) {
265:             throw new ServiceCreationException("$class::$method() is not callable.");
266:         }
267:         $this->addDependency($rm->getFileName());
268:         return Helpers::autowireArguments($rm, $arguments, $this);
269:     }
270: 
271: 
272:     /**
273:      * Generates $dependencies, $classes and normalizes class names.
274:      * @return array
275:      * @internal
276:      */
277:     public function prepareClassList()
278:     {
279:         unset($this->definitions[self::THIS_CONTAINER]);
280:         $this->addDefinition(self::THIS_CONTAINER)->setClass('Nette\DI\Container');
281: 
282:         $this->classes = FALSE;
283: 
284:         foreach ($this->definitions as $name => $def) {
285:             // prepare generated factories
286:             if ($def->getImplement()) {
287:                 $this->resolveImplement($def, $name);
288:             }
289: 
290:             if ($def->isDynamic()) {
291:                 if (!$def->getClass()) {
292:                     throw new ServiceCreationException("Class is missing in definition of service '$name'.");
293:                 }
294:                 $def->setFactory(NULL);
295:                 continue;
296:             }
297: 
298:             // complete class-factory pairs
299:             if (!$def->getEntity()) {
300:                 if (!$def->getClass()) {
301:                     throw new ServiceCreationException("Class and factory are missing in definition of service '$name'.");
302:                 }
303:                 $def->setFactory($def->getClass(), ($factory = $def->getFactory()) ? $factory->arguments : array());
304:             }
305: 
306:             // auto-disable autowiring for aliases
307:             if (($alias = $this->getServiceName($def->getFactory()->getEntity())) &&
308:                 (!$def->getImplement() || (!Strings::contains($alias, '\\') && $this->definitions[$alias]->getImplement()))
309:             ) {
310:                 $def->setAutowired(FALSE);
311:             }
312:         }
313: 
314:         // resolve and check classes
315:         foreach ($this->definitions as $name => $def) {
316:             $this->resolveServiceClass($name);
317:         }
318: 
319:         //  build auto-wiring list
320:         $excludedClasses = array();
321:         foreach ($this->excludedClasses as $class) {
322:             self::checkCase($class);
323:             $excludedClasses += class_parents($class) + class_implements($class) + array($class => $class);
324:         }
325: 
326:         $this->classes = array();
327:         foreach ($this->definitions as $name => $def) {
328:             if ($class = $def->getImplement() ?: $def->getClass()) {
329:                 foreach (class_parents($class) + class_implements($class) + array($class) as $parent) {
330:                     $this->classes[$parent][$def->isAutowired() && empty($excludedClasses[$parent])][] = (string) $name;
331:                 }
332:             }
333:         }
334: 
335:         foreach ($this->classes as $class => $foo) {
336:             $rc = new ReflectionClass($class);
337:             $this->addDependency($rc->getFileName());
338:         }
339:     }
340: 
341: 
342:     private function resolveImplement(ServiceDefinition $def, $name)
343:     {
344:         $interface = $def->getImplement();
345:         if (!interface_exists($interface)) {
346:             throw new ServiceCreationException("Interface $interface used in service '$name' not found.");
347:         }
348:         self::checkCase($interface);
349:         $rc = new ReflectionClass($interface);
350:         $method = $rc->hasMethod('create')
351:             ? $rc->getMethod('create')
352:             : ($rc->hasMethod('get') ? $rc->getMethod('get') : NULL);
353: 
354:         if (count($rc->getMethods()) !== 1 || !$method || $method->isStatic()) {
355:             throw new ServiceCreationException("Interface $interface used in service '$name' must have just one non-static method create() or get().");
356:         }
357:         $def->setImplementType($methodName = $rc->hasMethod('create') ? 'create' : 'get');
358: 
359:         if (!$def->getClass() && !$def->getEntity()) {
360:             $returnType = PhpReflection::getReturnType($method);
361:             if (!$returnType) {
362:                 throw new ServiceCreationException("Method $interface::$methodName() used in service '$name' has no @return annotation.");
363:             } elseif (!class_exists($returnType)) {
364:                 throw new ServiceCreationException("Check a @return annotation of the $interface::$methodName() method used in service '$name', class '$returnType' cannot be found.");
365:             }
366:             $def->setClass($returnType);
367:         }
368: 
369:         if ($methodName === 'get') {
370:             if ($method->getParameters()) {
371:                 throw new ServiceCreationException("Method $interface::get() used in service '$name' must have no arguments.");
372:             }
373:             if (!$def->getEntity()) {
374:                 $def->setFactory('@\\' . ltrim($def->getClass(), '\\'));
375:             } elseif (!$this->getServiceName($def->getFactory()->getEntity())) {
376:                 throw new ServiceCreationException("Invalid factory in service '$name' definition.");
377:             }
378:         }
379: 
380:         if (!$def->parameters) {
381:             $ctorParams = array();
382:             if (!$def->getEntity()) {
383:                 $def->setFactory($def->getClass(), $def->getFactory() ? $def->getFactory()->arguments : array());
384:             }
385:             if (($class = $this->resolveEntityClass($def->getFactory(), array($name => 1)))
386:                 && ($rc = new ReflectionClass($class)) && ($ctor = $rc->getConstructor())
387:             ) {
388:                 foreach ($ctor->getParameters() as $param) {
389:                     $ctorParams[$param->getName()] = $param;
390:                 }
391:             }
392: 
393:             foreach ($method->getParameters() as $param) {
394:                 $hint = PhpReflection::getParameterType($param);
395:                 if (isset($ctorParams[$param->getName()])) {
396:                     $arg = $ctorParams[$param->getName()];
397:                     if ($hint !== PhpReflection::getParameterType($arg)) {
398:                         throw new ServiceCreationException("Type hint for \${$param->getName()} in $interface::$methodName() doesn't match type hint in $class constructor.");
399:                     }
400:                     $def->getFactory()->arguments[$arg->getPosition()] = self::literal('$' . $arg->getName());
401:                 }
402:                 $paramDef = $hint . ' ' . $param->getName();
403:                 if ($param->isOptional()) {
404:                     $def->parameters[$paramDef] = $param->getDefaultValue();
405:                 } else {
406:                     $def->parameters[] = $paramDef;
407:                 }
408:             }
409:         }
410:     }
411: 
412: 
413:     /** @return string|NULL */
414:     private function resolveServiceClass($name, $recursive = array())
415:     {
416:         if (isset($recursive[$name])) {
417:             throw new ServiceCreationException(sprintf('Circular reference detected for services: %s.', implode(', ', array_keys($recursive))));
418:         }
419:         $recursive[$name] = TRUE;
420: 
421:         $def = $this->definitions[$name];
422:         $class = $def->getFactory() ? $this->resolveEntityClass($def->getFactory()->getEntity(), $recursive) : NULL; // call always to check entities
423:         if ($class = $def->getClass() ?: $class) {
424:             $def->setClass($class);
425:             if (!class_exists($class) && !interface_exists($class)) {
426:                 throw new ServiceCreationException("Type $class used in service '$name' not found or is not class or interface.");
427:             }
428:             self::checkCase($class);
429: 
430:         } elseif ($def->isAutowired()) {
431:             trigger_error("Type of service '$name' is unknown.", E_USER_NOTICE);
432:         }
433:         return $class;
434:     }
435: 
436: 
437:     /** @return string|NULL */
438:     private function resolveEntityClass($entity, $recursive = array())
439:     {
440:         $entity = $this->normalizeEntity($entity instanceof Statement ? $entity->getEntity() : $entity);
441: 
442:         if (is_array($entity)) {
443:             if (($service = $this->getServiceName($entity[0])) || $entity[0] instanceof Statement) {
444:                 $entity[0] = $this->resolveEntityClass($entity[0], $recursive);
445:                 if (!$entity[0]) {
446:                     return;
447:                 } elseif (isset($this->definitions[$service]) && $this->definitions[$service]->getImplement()) { // @Implement::create
448:                     return $entity[1] === 'create' ? $this->resolveServiceClass($service, $recursive) : NULL;
449:                 }
450:             }
451: 
452:             try {
453:                 $reflection = Nette\Utils\Callback::toReflection($entity[0] === '' ? $entity[1] : $entity);
454:                 $refClass = $reflection instanceof \ReflectionMethod ? $reflection->getDeclaringClass() : NULL;
455:             } catch (\ReflectionException $e) {
456:             }
457: 
458:             if (isset($e) || ($refClass && (!$reflection->isPublic()
459:                 || (PHP_VERSION_ID >= 50400 && $refClass->isTrait() && !$reflection->isStatic())
460:             ))) {
461:                 $name = array_slice(array_keys($recursive), -1);
462:                 throw new ServiceCreationException(sprintf("Factory '%s' used in service '%s' is not callable.", Nette\Utils\Callback::toString($entity), $name[0]));
463:             }
464: 
465:             return PhpReflection::getReturnType($reflection);
466: 
467:         } elseif ($service = $this->getServiceName($entity)) { // alias or factory
468:             if (Strings::contains($service, '\\')) { // @\Class
469:                 return ltrim($service, '\\');
470:             }
471:             return $this->definitions[$service]->getImplement() ?: $this->resolveServiceClass($service, $recursive);
472: 
473:         } elseif (is_string($entity)) {
474:             if (!class_exists($entity) || !($rc = new ReflectionClass($entity)) || !$rc->isInstantiable()) {
475:                 $name = array_slice(array_keys($recursive), -1);
476:                 throw new ServiceCreationException("Class $entity used in service '$name[0]' not found or is not instantiable.");
477:             }
478:             return ltrim($entity, '\\');
479:         }
480:     }
481: 
482: 
483:     private function checkCase($class)
484:     {
485:         if (class_exists($class) && ($rc = new ReflectionClass($class)) && $class !== $rc->getName()) {
486:             throw new ServiceCreationException("Case mismatch on class name '$class', correct name is '{$rc->getName()}'.");
487:         }
488:     }
489: 
490: 
491:     /**
492:      * @param  string[]
493:      * @return self
494:      */
495:     public function addExcludedClasses(array $classes)
496:     {
497:         $this->excludedClasses = array_merge($this->excludedClasses, $classes);
498:         return $this;
499:     }
500: 
501: 
502:     /**
503:      * Adds a file to the list of dependencies.
504:      * @return self
505:      * @internal
506:      */
507:     public function addDependency($file)
508:     {
509:         $this->dependencies[$file] = TRUE;
510:         return $this;
511:     }
512: 
513: 
514:     /**
515:      * Returns the list of dependent files.
516:      * @return array
517:      */
518:     public function getDependencies()
519:     {
520:         unset($this->dependencies[FALSE]);
521:         return array_keys($this->dependencies);
522:     }
523: 
524: 
525:     /********************* code generator ****************d*g**/
526: 
527: 
528:     /**
529:      * Generates PHP classes. First class is the container.
530:      * @return Nette\PhpGenerator\ClassType[]
531:      */
532:     public function generateClasses($className = NULL, $parentName = NULL)
533:     {
534:         $this->prepareClassList();
535: 
536:         $this->generatedClasses = array();
537:         $this->className = $className ?: $this->className;
538:         $containerClass = $this->generatedClasses[] = new Nette\PhpGenerator\ClassType($this->className);
539:         $containerClass->setExtends($parentName ?: 'Nette\DI\Container');
540:         $containerClass->addMethod('__construct')
541:             ->addBody('parent::__construct(?);', array($this->parameters));
542: 
543:         $definitions = $this->definitions;
544:         ksort($definitions);
545: 
546:         $meta = $containerClass->addProperty('meta')
547:             ->setVisibility('protected')
548:             ->setValue(array(Container::TYPES => $this->classes));
549: 
550:         foreach ($definitions as $name => $def) {
551:             $meta->value[Container::SERVICES][$name] = $def->getClass() ?: NULL;
552:             foreach ($def->getTags() as $tag => $value) {
553:                 $meta->value[Container::TAGS][$tag][$name] = $value;
554:             }
555:         }
556: 
557:         foreach ($definitions as $name => $def) {
558:             try {
559:                 $name = (string) $name;
560:                 $methodName = Container::getMethodName($name);
561:                 if (!PhpHelpers::isIdentifier($methodName)) {
562:                     throw new ServiceCreationException('Name contains invalid characters.');
563:                 }
564:                 $containerClass->addMethod($methodName)
565:                     ->addDocument('@return ' . ($def->getImplement() ?: $def->getClass()))
566:                     ->setBody($name === self::THIS_CONTAINER ? 'return $this;' : $this->generateService($name))
567:                     ->setParameters($def->getImplement() ? array() : $this->convertParameters($def->parameters));
568:             } catch (\Exception $e) {
569:                 throw new ServiceCreationException("Service '$name': " . $e->getMessage(), NULL, $e);
570:             }
571:         }
572: 
573:         $aliases = $this->aliases;
574:         ksort($aliases);
575:         $meta->value[Container::ALIASES] = $aliases;
576: 
577:         return $this->generatedClasses;
578:     }
579: 
580: 
581:     /**
582:      * Generates body of service method.
583:      * @return string
584:      */
585:     private function generateService($name)
586:     {
587:         $this->currentService = NULL;
588:         $def = $this->definitions[$name];
589: 
590:         if ($def->isDynamic()) {
591:             return PhpHelpers::formatArgs('throw new Nette\\DI\\ServiceCreationException(?);',
592:                 array("Unable to create dynamic service '$name', it must be added using addService()")
593:             );
594:         }
595: 
596:         $entity = $def->getFactory()->getEntity();
597:         $serviceRef = $this->getServiceName($entity);
598:         $factory = $serviceRef && !$def->getFactory()->arguments && !$def->getSetup() && $def->getImplementType() !== 'create'
599:             ? new Statement(array('@' . self::THIS_CONTAINER, 'getService'), array($serviceRef))
600:             : $def->getFactory();
601: 
602:         $code = '$service = ' . $this->formatStatement($factory) . ";\n";
603:         $this->currentService = $name;
604: 
605:         if (($class = $def->getClass()) && !$serviceRef && $class !== $entity
606:             && !(is_string($entity) && preg_match('#^[\w\\\\]+\z#', $entity) && is_subclass_of($entity, $class))
607:         ) {
608:             $code .= PhpHelpers::formatArgs("if (!\$service instanceof $class) {\n"
609:                 . "\tthrow new Nette\\UnexpectedValueException(?);\n}\n",
610:                 array("Unable to create service '$name', value returned by factory is not $class type.")
611:             );
612:         }
613: 
614:         foreach ($def->getSetup() as $setup) {
615:             if (is_string($setup->getEntity()) && strpbrk($setup->getEntity(), ':@?\\') === FALSE) { // auto-prepend @self
616:                 $setup->setEntity(array('@self', $setup->getEntity()));
617:             }
618:             $code .= $this->formatStatement($setup) . ";\n";
619:         }
620:         $this->currentService = NULL;
621: 
622:         $code .= 'return $service;';
623: 
624:         if (!$def->getImplement()) {
625:             return $code;
626:         }
627: 
628:         $factoryClass = $this->generatedClasses[] = new Nette\PhpGenerator\ClassType;
629:         $factoryClass->setName(str_replace(array('\\', '.'), '_', "{$this->className}_{$def->getImplement()}Impl_{$name}"))
630:             ->addImplement($def->getImplement())
631:             ->setFinal(TRUE);
632: 
633:         $factoryClass->addProperty('container')
634:             ->setVisibility('private');
635: 
636:         $factoryClass->addMethod('__construct')
637:             ->addBody('$this->container = $container;')
638:             ->addParameter('container')
639:                 ->setTypeHint($this->className);
640: 
641:         $factoryClass->addMethod($def->getImplementType())
642:             ->setParameters($this->convertParameters($def->parameters))
643:             ->setBody(str_replace('$this', '$this->container', $code))
644:             ->setReturnType(PHP_VERSION_ID >= 70000 ? $def->getClass() : NULL);
645: 
646:         return "return new {$factoryClass->getName()}(\$this);";
647:     }
648: 
649: 
650:     /**
651:      * Converts parameters from ServiceDefinition to PhpGenerator.
652:      * @return Nette\PhpGenerator\Parameter[]
653:      */
654:     private function convertParameters(array $parameters)
655:     {
656:         $res = array();
657:         foreach ($parameters as $k => $v) {
658:             $tmp = explode(' ', is_int($k) ? $v : $k);
659:             $param = $res[] = new Nette\PhpGenerator\Parameter;
660:             $param->setName(end($tmp));
661:             if (!is_int($k)) {
662:                 $param = $param->setOptional(TRUE)->setDefaultValue($v);
663:             }
664:             if (isset($tmp[1])) {
665:                 $param->setTypeHint($tmp[0]);
666:             }
667:         }
668:         return $res;
669:     }
670: 
671: 
672:     /**
673:      * Formats PHP code for class instantiating, function calling or property setting in PHP.
674:      * @return string
675:      * @internal
676:      */
677:     public function formatStatement(Statement $statement)
678:     {
679:         $entity = $this->normalizeEntity($statement->getEntity());
680:         $arguments = $statement->arguments;
681: 
682:         if (is_string($entity) && Strings::contains($entity, '?')) { // PHP literal
683:             return $this->formatPhp($entity, $arguments);
684: 
685:         } elseif ($service = $this->getServiceName($entity)) { // factory calling
686:             $params = array();
687:             foreach ($this->definitions[$service]->parameters as $k => $v) {
688:                 $params[] = preg_replace('#\w+\z#', '\$$0', (is_int($k) ? $v : $k)) . (is_int($k) ? '' : ' = ' . PhpHelpers::dump($v));
689:             }
690:             $rm = new \ReflectionFunction(create_function(implode(', ', $params), ''));
691:             $arguments = Helpers::autowireArguments($rm, $arguments, $this);
692:             return $this->formatPhp('$this->?(?*)', array(Container::getMethodName($service), $arguments));
693: 
694:         } elseif ($entity === 'not') { // operator
695:             return $this->formatPhp('!?', array($arguments[0]));
696: 
697:         } elseif (is_string($entity)) { // class name
698:             $rc = new ReflectionClass($entity);
699:             if ($constructor = $rc->getConstructor()) {
700:                 $this->addDependency($constructor->getFileName());
701:                 $arguments = Helpers::autowireArguments($constructor, $arguments, $this);
702:             } elseif ($arguments) {
703:                 throw new ServiceCreationException("Unable to pass arguments, class $entity has no constructor.");
704:             }
705:             return $this->formatPhp("new $entity" . ($arguments ? '(?*)' : ''), array($arguments));
706: 
707:         } elseif (!Nette\Utils\Arrays::isList($entity) || count($entity) !== 2) {
708:             throw new ServiceCreationException(sprintf('Expected class, method or property, %s given.', PhpHelpers::dump($entity)));
709: 
710:         } elseif (!preg_match('#^\$?' . PhpHelpers::PHP_IDENT . '\z#', $entity[1])) {
711:             throw new ServiceCreationException("Expected function, method or property name, '$entity[1]' given.");
712: 
713:         } elseif ($entity[0] === '') { // globalFunc
714:             return $this->formatPhp("$entity[1](?*)", array($arguments));
715: 
716:         } elseif ($entity[0] instanceof Statement) {
717:             $inner = $this->formatPhp('?', array($entity[0]));
718:             if (substr($inner, 0, 4) === 'new ') {
719:                 $inner = PHP_VERSION_ID < 50400 ? "current(array($inner))" : "($inner)";
720:             }
721:             return $this->formatPhp("$inner->?(?*)", array($entity[1], $arguments));
722: 
723:         } elseif (Strings::contains($entity[1], '$')) { // property setter
724:             Validators::assert($arguments, 'list:1', "setup arguments for '" . Nette\Utils\Callback::toString($entity) . "'");
725:             if ($this->getServiceName($entity[0])) {
726:                 return $this->formatPhp('?->? = ?', array($entity[0], substr($entity[1], 1), $arguments[0]));
727:             } else {
728:                 return $this->formatPhp($entity[0] . '::$? = ?', array(substr($entity[1], 1), $arguments[0]));
729:             }
730: 
731:         } elseif ($service = $this->getServiceName($entity[0])) { // service method
732:             $class = $this->definitions[$service]->getImplement();
733:             if (!$class || !method_exists($class, $entity[1])) {
734:                 $class = $this->definitions[$service]->getClass();
735:             }
736:             if ($class) {
737:                 $arguments = $this->autowireArguments($class, $entity[1], $arguments);
738:             }
739:             return $this->formatPhp('?->?(?*)', array($entity[0], $entity[1], $arguments));
740: 
741:         } else { // static method
742:             $arguments = $this->autowireArguments($entity[0], $entity[1], $arguments);
743:             return $this->formatPhp("$entity[0]::$entity[1](?*)", array($arguments));
744:         }
745:     }
746: 
747: 
748:     /**
749:      * Formats PHP statement.
750:      * @return string
751:      * @internal
752:      */
753:     public function formatPhp($statement, $args)
754:     {
755:         $that = $this;
756:         array_walk_recursive($args, function (& $val) use ($that) {
757:             if ($val instanceof Statement) {
758:                 $val = ContainerBuilder::literal($that->formatStatement($val));
759: 
760:             } elseif ($val === $that) {
761:                 $val = ContainerBuilder::literal('$this');
762: 
763:             } elseif ($val instanceof ServiceDefinition) {
764:                 $val = '@' . current(array_keys($that->getDefinitions(), $val, TRUE));
765:             }
766: 
767:             if (!is_string($val)) {
768:                 return;
769: 
770:             } elseif (substr($val, 0, 2) === '@@') {
771:                 $val = substr($val, 1);
772: 
773:             } elseif (substr($val, 0, 1) === '@') {
774:                 $pair = explode('::', $val, 2);
775:                 $name = $that->getServiceName($pair[0]);
776:                 if (isset($pair[1]) && preg_match('#^[A-Z][A-Z0-9_]*\z#', $pair[1], $m)) {
777:                     $val = $that->getDefinition($name)->getClass() . '::' . $pair[1];
778:                 } else {
779:                     if ($name === ContainerBuilder::THIS_CONTAINER) {
780:                         $val = '$this';
781:                     } elseif ($name === $that->currentService) {
782:                         $val = '$service';
783:                     } else {
784:                         $val = $that->formatStatement(new Statement(array('@' . ContainerBuilder::THIS_CONTAINER, 'getService'), array($name)));
785:                     }
786:                     $val .= (isset($pair[1]) ? PhpHelpers::formatArgs('->?', array($pair[1])) : '');
787:                 }
788:                 $val = ContainerBuilder::literal($val);
789:             }
790:         });
791:         return PhpHelpers::formatArgs($statement, $args);
792:     }
793: 
794: 
795:     /**
796:      * Expands %placeholders% in strings.
797:      * @return mixed
798:      * @deprecated
799:      */
800:     public function expand($value)
801:     {
802:         return Helpers::expand($value, $this->parameters);
803:     }
804: 
805: 
806:     /**
807:      * @return Nette\PhpGenerator\PhpLiteral
808:      */
809:     public static function literal($phpCode)
810:     {
811:         return new Nette\PhpGenerator\PhpLiteral($phpCode);
812:     }
813: 
814: 
815:     /** @internal */
816:     public function normalizeEntity($entity)
817:     {
818:         if (is_string($entity) && Strings::contains($entity, '::') && !Strings::contains($entity, '?')) { // Class::method -> [Class, method]
819:             $entity = explode('::', $entity);
820:         }
821: 
822:         if (is_array($entity) && $entity[0] instanceof ServiceDefinition) { // [ServiceDefinition, ...] -> [@serviceName, ...]
823:             $entity[0] = '@' . current(array_keys($this->definitions, $entity[0], TRUE));
824: 
825:         } elseif ($entity instanceof ServiceDefinition) { // ServiceDefinition -> @serviceName
826:             $entity = '@' . current(array_keys($this->definitions, $entity, TRUE));
827: 
828:         } elseif (is_array($entity) && $entity[0] === $this) { // [$this, ...] -> [@container, ...]
829:             $entity[0] = '@' . self::THIS_CONTAINER;
830:         }
831:         return $entity; // Class, @service, [Class, member], [@service, member], [, globalFunc], Statement
832:     }
833: 
834: 
835:     /**
836:      * Converts @service or @\Class -> service name and checks its existence.
837:      * @return string  of FALSE, if argument is not service name
838:      * @internal
839:      */
840:     public function getServiceName($arg)
841:     {
842:         $arg = $this->normalizeEntity($arg);
843:         if (!is_string($arg) || !preg_match('#^@[\w\\\\.].*\z#', $arg)) {
844:             return FALSE;
845:         }
846:         $service = substr($arg, 1);
847:         if ($service === self::THIS_SERVICE) {
848:             $service = $this->currentService;
849:         }
850:         if (Strings::contains($service, '\\')) {
851:             if ($this->classes === FALSE) { // may be disabled by prepareClassList
852:                 return $service;
853:             }
854:             $res = $this->getByType($service);
855:             if (!$res) {
856:                 throw new ServiceCreationException("Reference to missing service of type $service.");
857:             }
858:             return $res;
859:         }
860:         $service = isset($this->aliases[$service]) ? $this->aliases[$service] : $service;
861:         if (!isset($this->definitions[$service])) {
862:             throw new ServiceCreationException("Reference to missing service '$service'.");
863:         }
864:         return $service;
865:     }
866: 
867: }
868: 
Nette 2.3.8 API API documentation generated by ApiGen 2.8.0