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

Classes

  • Compiler
  • CompilerExtension
  • Container
  • ContainerBuilder
  • ContainerLoader
  • DependencyChecker
  • PhpGenerator
  • 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\PhpGenerator\Helpers as PhpHelpers;
 12: use Nette\PhpGenerator\PhpLiteral;
 13: use Nette\Utils\Reflection;
 14: use Nette\Utils\Strings;
 15: 
 16: 
 17: /**
 18:  * Container PHP code generator.
 19:  */
 20: class PhpGenerator
 21: {
 22:     /** @var ContainerBuilder */
 23:     private $builder;
 24: 
 25:     /** @var string */
 26:     private $className;
 27: 
 28:     /** @var Nette\PhpGenerator\ClassType[] */
 29:     private $generatedClasses = [];
 30: 
 31:     /** @var string */
 32:     private $currentService;
 33: 
 34: 
 35:     public function __construct(ContainerBuilder $builder)
 36:     {
 37:         $this->builder = $builder;
 38:     }
 39: 
 40: 
 41:     /**
 42:      * Generates PHP classes. First class is the container.
 43:      * @return Nette\PhpGenerator\ClassType[]
 44:      */
 45:     public function generate($className)
 46:     {
 47:         $this->builder->complete();
 48: 
 49:         $this->generatedClasses = [];
 50:         $this->className = $className;
 51:         $containerClass = $this->generatedClasses[] = new Nette\PhpGenerator\ClassType($this->className);
 52:         $containerClass->setExtends(Container::class);
 53:         $containerClass->addMethod('__construct')
 54:             ->addBody('$this->parameters = $params;')
 55:             ->addBody('$this->parameters += ?;', [$this->builder->parameters])
 56:             ->addParameter('params', [])
 57:                 ->setTypeHint('array');
 58: 
 59:         $definitions = $this->builder->getDefinitions();
 60:         ksort($definitions);
 61: 
 62:         $meta = $containerClass->addProperty('meta')
 63:             ->setVisibility('protected')
 64:             ->setValue([Container::TYPES => $this->builder->getClassList()]);
 65: 
 66:         foreach ($definitions as $name => $def) {
 67:             $meta->value[Container::SERVICES][$name] = $def->getType() ?: null;
 68:             foreach ($def->getTags() as $tag => $value) {
 69:                 $meta->value[Container::TAGS][$tag][$name] = $value;
 70:             }
 71:         }
 72: 
 73:         foreach ($definitions as $name => $def) {
 74:             try {
 75:                 $name = (string) $name;
 76:                 $methodName = Container::getMethodName($name);
 77:                 if (!PhpHelpers::isIdentifier($methodName)) {
 78:                     throw new ServiceCreationException('Name contains invalid characters.');
 79:                 }
 80:                 $containerClass->addMethod($methodName)
 81:                     ->addComment(PHP_VERSION_ID < 70000 ? '@return ' . ($def->getImplement() ?: $def->getType()) : '')
 82:                     ->setReturnType(PHP_VERSION_ID >= 70000 ? ($def->getImplement() ?: $def->getType()) : null)
 83:                     ->setBody($name === ContainerBuilder::THIS_CONTAINER ? 'return $this;' : $this->generateService($name))
 84:                     ->setParameters($def->getImplement() ? [] : $this->convertParameters($def->parameters));
 85:             } catch (\Exception $e) {
 86:                 throw new ServiceCreationException("Service '$name': " . $e->getMessage(), 0, $e);
 87:             }
 88:         }
 89: 
 90:         $aliases = $this->builder->getAliases();
 91:         ksort($aliases);
 92:         $meta->value[Container::ALIASES] = $aliases;
 93: 
 94:         return $this->generatedClasses;
 95:     }
 96: 
 97: 
 98:     /**
 99:      * Generates body of service method.
100:      * @return string
101:      */
102:     private function generateService($name)
103:     {
104:         $def = $this->builder->getDefinition($name);
105: 
106:         if ($def->isDynamic()) {
107:             return PhpHelpers::formatArgs('throw new Nette\\DI\\ServiceCreationException(?);',
108:                 ["Unable to create dynamic service '$name', it must be added using addService()"]
109:             );
110:         }
111: 
112:         $entity = $def->getFactory()->getEntity();
113:         $serviceRef = $this->builder->getServiceName($entity);
114:         $factory = $serviceRef && !$def->getFactory()->arguments && !$def->getSetup() && $def->getImplementMode() !== $def::IMPLEMENT_MODE_CREATE
115:             ? new Statement(['@' . ContainerBuilder::THIS_CONTAINER, 'getService'], [$serviceRef])
116:             : $def->getFactory();
117: 
118:         $this->currentService = null;
119:         $code = '$service = ' . $this->formatStatement($factory) . ";\n";
120: 
121:         if ((PHP_VERSION_ID < 70000 || $def->getSetup()) && ($type = $def->getType()) && !$serviceRef && $type !== $entity
122:             && !(is_string($entity) && preg_match('#^[\w\\\\]+\z#', $entity) && is_subclass_of($entity, $type))
123:         ) {
124:             $code .= PhpHelpers::formatArgs("if (!\$service instanceof $type) {\n"
125:                 . "\tthrow new Nette\\UnexpectedValueException(?);\n}\n",
126:                 ["Unable to create service '$name', value returned by factory is not $type type."]
127:             );
128:         }
129: 
130:         $this->currentService = $name;
131:         foreach ($def->getSetup() as $setup) {
132:             $code .= $this->formatStatement($setup) . ";\n";
133:         }
134: 
135:         $code .= 'return $service;';
136: 
137:         if (!$def->getImplement()) {
138:             return $code;
139:         }
140: 
141:         $factoryClass = (new Nette\PhpGenerator\ClassType)
142:             ->addImplement($def->getImplement());
143: 
144:         $factoryClass->addProperty('container')
145:             ->setVisibility('private');
146: 
147:         $factoryClass->addMethod('__construct')
148:             ->addBody('$this->container = $container;')
149:             ->addParameter('container')
150:                 ->setTypeHint($this->className);
151: 
152:         $rm = new \ReflectionMethod($def->getImplement(), $def->getImplementMode());
153: 
154:         $factoryClass->addMethod($def->getImplementMode())
155:             ->setParameters($this->convertParameters($def->parameters))
156:             ->setBody(str_replace('$this', '$this->container', $code))
157:             ->setReturnType(PHP_VERSION_ID >= 70000 ? (Reflection::getReturnType($rm) ?: $def->getType()) : null);
158: 
159:         if (PHP_VERSION_ID < 70000) {
160:             $this->generatedClasses[] = $factoryClass;
161:             $factoryClass->setName(str_replace(['\\', '.'], '_', "{$this->className}_{$def->getImplement()}Impl_{$name}"));
162:             return "return new {$factoryClass->getName()}(\$this);";
163:         }
164: 
165:         return 'return new class ($this) ' . $factoryClass . ';';
166:     }
167: 
168: 
169:     /**
170:      * Formats PHP code for class instantiating, function calling or property setting in PHP.
171:      * @return string
172:      */
173:     private function formatStatement(Statement $statement)
174:     {
175:         $entity = $statement->getEntity();
176:         $arguments = $statement->arguments;
177: 
178:         if (is_string($entity) && Strings::contains($entity, '?')) { // PHP literal
179:             return $this->formatPhp($entity, $arguments);
180: 
181:         } elseif ($service = $this->builder->getServiceName($entity)) { // factory calling
182:             return $this->formatPhp('$this->?(...?)', [Container::getMethodName($service), $arguments]);
183: 
184:         } elseif ($entity === 'not') { // operator
185:             return $this->formatPhp('!?', [$arguments[0]]);
186: 
187:         } elseif (is_string($entity)) { // class name
188:             return $this->formatPhp("new $entity" . ($arguments ? '(...?)' : ''), $arguments ? [$arguments] : []);
189: 
190:         } elseif ($entity[0] === '') { // globalFunc
191:             return $this->formatPhp("$entity[1](...?)", [$arguments]);
192: 
193:         } elseif ($entity[0] instanceof Statement) {
194:             $inner = $this->formatPhp('?', [$entity[0]]);
195:             if (substr($inner, 0, 4) === 'new ') {
196:                 $inner = "($inner)";
197:             }
198:             return $this->formatPhp("$inner->?(...?)", [$entity[1], $arguments]);
199: 
200:         } elseif ($entity[1][0] === '$') { // property getter, setter or appender
201:             $name = substr($entity[1], 1);
202:             if ($append = (substr($name, -2) === '[]')) {
203:                 $name = substr($name, 0, -2);
204:             }
205:             if ($this->builder->getServiceName($entity[0])) {
206:                 $prop = $this->formatPhp('?->?', [$entity[0], $name]);
207:             } else {
208:                 $prop = $this->formatPhp($entity[0] . '::$?', [$name]);
209:             }
210:             return $arguments
211:                 ? $this->formatPhp($prop . ($append ? '[]' : '') . ' = ?', [$arguments[0]])
212:                 : $prop;
213: 
214:         } elseif ($service = $this->builder->getServiceName($entity[0])) { // service method
215:             return $this->formatPhp('?->?(...?)', [$entity[0], $entity[1], $arguments]);
216: 
217:         } else { // static method
218:             return $this->formatPhp("$entity[0]::$entity[1](...?)", [$arguments]);
219:         }
220:     }
221: 
222: 
223:     /**
224:      * Formats PHP statement.
225:      * @return string
226:      * @internal
227:      */
228:     public function formatPhp($statement, $args)
229:     {
230:         array_walk_recursive($args, function (&$val) {
231:             if ($val instanceof Statement) {
232:                 $val = new PhpLiteral($this->formatStatement($val));
233: 
234:             } elseif (is_string($val) && substr($val, 0, 2) === '@@') { // escaped text @@
235:                 $val = substr($val, 1);
236: 
237:             } elseif (is_string($val) && substr($val, 0, 1) === '@' && strlen($val) > 1) { // service reference
238:                 $name = substr($val, 1);
239:                 if ($name === ContainerBuilder::THIS_CONTAINER) {
240:                     $val = new PhpLiteral('$this');
241:                 } elseif ($name === $this->currentService) {
242:                     $val = new PhpLiteral('$service');
243:                 } else {
244:                     $val = new PhpLiteral($this->formatStatement(new Statement(['@' . ContainerBuilder::THIS_CONTAINER, 'getService'], [$name])));
245:                 }
246:             }
247:         });
248:         return PhpHelpers::formatArgs($statement, $args);
249:     }
250: 
251: 
252:     /**
253:      * Converts parameters from ServiceDefinition to PhpGenerator.
254:      * @return Nette\PhpGenerator\Parameter[]
255:      */
256:     private function convertParameters(array $parameters)
257:     {
258:         $res = [];
259:         foreach ($parameters as $k => $v) {
260:             $tmp = explode(' ', is_int($k) ? $v : $k);
261:             $param = $res[] = new Nette\PhpGenerator\Parameter(end($tmp));
262:             if (!is_int($k)) {
263:                 $param->setOptional(true)->setDefaultValue($v);
264:             }
265:             if (isset($tmp[1])) {
266:                 $param->setTypeHint($tmp[0]);
267:             }
268:         }
269:         return $res;
270:     }
271: }
272: 
Nette 2.4-20170829 API API documentation generated by ApiGen 2.8.0