Exemplo n.º 1
0
 /**
  * Generates PHP class.
  * @return PhpClassType
  */
 public function generateClass($parentClass = 'DIContainer')
 {
     unset($this->definitions[self::THIS_CONTAINER]);
     $this->addDefinition(self::THIS_CONTAINER)->setClass($parentClass);
     $this->prepareClassList();
     $class = new PhpClassType('Container');
     $class->addExtend($parentClass);
     $class->addMethod('__construct')->addBody('parent::__construct(?);', array($this->expand($this->parameters)));
     $classes = $class->addProperty('classes', array());
     foreach ($this->classes as $name => $foo) {
         try {
             $classes->value[$name] = $this->getByType($name);
         } catch (ServiceCreationException $e) {
             $classes->value[$name] = new PhpLiteral('FALSE, //' . strstr($e->getMessage(), ':'));
         }
     }
     $definitions = $this->definitions;
     ksort($definitions);
     $meta = $class->addProperty('meta', array());
     foreach ($definitions as $name => $def) {
         if ($def->shared) {
             foreach ($this->expand($def->tags) as $tag => $value) {
                 $meta->value[$name][DIContainer::TAGS][$tag] = $value;
             }
         }
     }
     foreach ($definitions as $name => $def) {
         try {
             $type = ($tmp = $def->class) ? $tmp : 'object';
             $methodName = DIContainer::getMethodName($name, $def->shared);
             if (!PhpHelpers::isIdentifier($methodName)) {
                 throw new ServiceCreationException('Name contains invalid characters.');
             }
             if ($def->shared && !$def->internal && PhpHelpers::isIdentifier($name)) {
                 $class->addDocument("@property {$type} \${$name}");
             }
             $method = $class->addMethod($methodName)->addDocument("@return {$type}")->setVisibility($def->shared || $def->internal ? 'protected' : 'public')->setBody($name === self::THIS_CONTAINER ? 'return $this;' : $this->generateService($name));
             foreach ($this->expand($def->parameters) as $k => $v) {
                 $tmp = explode(' ', is_int($k) ? $v : $k);
                 $param = is_int($k) ? $method->addParameter(end($tmp)) : $method->addParameter(end($tmp), $v);
                 if (isset($tmp[1])) {
                     $param->setTypeHint($tmp[0]);
                 }
             }
         } catch (Exception $e) {
             throw new ServiceCreationException("Service '{$name}': " . $e->getMessage(), NULL, $e);
         }
     }
     return $class;
 }