Ejemplo n.º 1
0
    public function addToString()
    {
        $classGenerator = $this->getClassGenerator();
        $methodGenerator = new CodeGenerator\MethodGenerator();
        $methodGenerator->setName('__toString');
        $idAttribute = 'id';
        $body = <<<METHODBODY
\$attributes = array(\$this->{$idAttribute});

METHODBODY;
        foreach (static::$secondaryProperties as $attributeName => $propertyName) {
            $body .= <<<METHODBODY
if (!empty(\$this->{$propertyName})) {
    \$attributes[] = "{$attributeName}={\$this->{$propertyName}}";
}

METHODBODY;
        }
        $body .= <<<METHODBODY
foreach (\$this->attributes as \$attributeName => \$value) {
    if (!empty(\$value)) {
        \$attributes[] = "{\$attributeName}={\$value}";
    }
}
return implode('!', \$attributes);
METHODBODY;
        $methodGenerator->setBody($body);
        $classGenerator->addMethodFromGenerator($methodGenerator);
    }
Ejemplo n.º 2
0
 /**
  * Build method factory
  *
  * @param ClassGenerator $generator
  */
 public function buildFactory(ClassGenerator $generator)
 {
     $docBlock = new DocBlockGenerator('@return ' . $this->config->getName());
     $factory = new MethodGenerator();
     $factory->setDocBlock($docBlock);
     $factory->setName('factory');
     $factory->setBody('return new ' . $this->config->getName() . '();');
     $generator->addMethodFromGenerator($factory);
 }
Ejemplo n.º 3
0
 /**
  * @param string $name
  * @param Code $code
  * @return PhpMethod
  */
 public function addMethod($name, Code $code)
 {
     $this->code[$name] = $code;
     $method = new MethodGenerator();
     $method->setName($name);
     $method->setVisibility(MethodGenerator::VISIBILITY_PUBLIC);
     // $code remains object until turning to string
     $method->setBody($code);
     $this->addMethodFromGenerator($method);
     return $method;
 }
Ejemplo n.º 4
0
 /**
  * Build method factory
  *
  * @param ClassGenerator  $generator
  * @param \Scaffold\State $state
  */
 public function buildFactory(ClassGenerator $generator, State $state)
 {
     $repository = ucfirst($state->getRepositoryModel()->getClassName());
     $docBlock = new DocBlockGenerator();
     $docBlock->setTag(new Tag\GenericTag('return', $this->config->getName()));
     $factory = new MethodGenerator();
     $factory->setDocBlock($docBlock);
     $factory->setName('factory');
     $factory->setBody('return $this->get' . $repository . '()->factory();');
     $generator->addMethodFromGenerator($factory);
 }
Ejemplo n.º 5
0
    public function postRun(PartInterface $part)
    {
        /**
         * @var $part \Model\Generator\Part\Entity
         */
        /**
         * @var $file \Model\Code\Generator\FileGenerator
         */
        $file = $part->getFile();
        $table = $part->getTable();
        $tags = array(array('name' => 'return', 'description' => 'array'));
        $docblock = new DocBlockGenerator('Initialize indexes');
        $docblock->setTags($tags);
        $resultIndexList = array();
        $indexList = $table->getIndex();
        foreach ($indexList as $index) {
            $resIndex = $index->toArray();
            $resIndex['column_list'] = array();
            switch ($index->getType()) {
                case AbstractIndex::TYPE_PRIMARY:
                    $resIndex['type'] = new ValueGenerator('AbstractModel::INDEX_PRIMARY', ValueGenerator::TYPE_CONSTANT);
                    break;
                case AbstractIndex::TYPE_KEY:
                    $resIndex['type'] = new ValueGenerator('AbstractModel::INDEX_KEY', ValueGenerator::TYPE_CONSTANT);
                    break;
                case AbstractIndex::TYPE_UNIQUE:
                    $resIndex['type'] = new ValueGenerator('AbstractModel::INDEX_UNIQUE', ValueGenerator::TYPE_CONSTANT);
                    break;
            }
            foreach ($resIndex['columns'] as $col) {
                $resIndex['column_list'][] = $col['column_name'];
            }
            unset($resIndex['columns']);
            $resultIndexList[$index->getName()] = $resIndex;
        }
        $property = new PropertyGenerator('indexList', $resultIndexList, PropertyGenerator::FLAG_PROTECTED);
        $body = preg_replace("#^(\\s*)protected #", "\\1", $property->generate()) . "\n";
        $method = new MethodGenerator();
        $method->setName('initIndexList');
        $method->setVisibility(AbstractMemberGenerator::VISIBILITY_PUBLIC);
        $method->setFinal(true);
        $method->setDocBlock($docblock);
        $method->setBody(<<<EOS
{$body}
\$this->indexList = \$indexList;
\$this->setupIndexList();
EOS
);
        $file->getClass()->addMethodFromGenerator($method);
    }
Ejemplo n.º 6
0
 /**
  * Generate an __invoke method
  */
 protected function addInvokeMethod()
 {
     // set action body
     $body = ['// add view helper code here', '$output = \'\';', '', 'return $output;'];
     $body = implode(AbstractGenerator::LINE_FEED, $body);
     // create method
     $method = new MethodGenerator();
     $method->setName('__invoke');
     $method->setBody($body);
     // check for api docs
     if ($this->config['flagAddDocBlocks']) {
         $method->setDocBlock(new DocBlockGenerator('Called when view helper is executed', null, [new ReturnTag(['string'])]));
     }
     // add method
     $this->addMethodFromGenerator($method);
 }
Ejemplo n.º 7
0
 /**
  * Generate an init method
  */
 protected function addInitMethod()
 {
     // set action body
     $body = array('// add input objects here');
     $body = implode(AbstractGenerator::LINE_FEED, $body);
     // create method
     $method = new MethodGenerator();
     $method->setName('init');
     $method->setBody($body);
     // check for api docs
     if ($this->config['flagAddDocBlocks']) {
         $method->setDocBlock(new DocBlockGenerator('Generate input filter by adding inputs'));
     }
     // add method
     $this->addMethodFromGenerator($method);
 }
 /**
  * Generate an __invoke method
  */
 protected function addInvokeMethod()
 {
     // set action body
     $body = ['// add controller plugin code here'];
     $body = implode(AbstractGenerator::LINE_FEED, $body);
     // create method
     $method = new MethodGenerator();
     $method->setName('__invoke');
     $method->setBody($body);
     // check for api docs
     if ($this->config['flagAddDocBlocks']) {
         $method->setDocBlock(new DocBlockGenerator('Called when controller plugin is executed', null, [new ReturnTag(['mixed'])]));
     }
     // add method
     $this->addMethodFromGenerator($method);
 }
Ejemplo n.º 9
0
 /**
  * Generate an init method
  */
 protected function addInitMethod()
 {
     // set action body
     $body = ['// add form elements and form configuration here'];
     $body = implode(AbstractGenerator::LINE_FEED, $body);
     // create method
     $method = new MethodGenerator();
     $method->setName('init');
     $method->setBody($body);
     // check for api docs
     if ($this->config['flagAddDocBlocks']) {
         $method->setDocBlock(new DocBlockGenerator('Generate form by adding elements'));
     }
     // add method
     $this->addMethodFromGenerator($method);
 }
Ejemplo n.º 10
0
    public function postRun(PartInterface $part)
    {
        /**
         * @var $part \Model\Generator\Part\Entity
         */
        /**
         * @var $file \Model\Code\Generator\FileGenerator
         */
        $file = $part->getFile();
        $table = $part->getTable();
        $tags = array(array('name' => 'var', 'description' => 'array значения по-умолчанию для полей'));
        $docblock = new \Zend\Code\Generator\DocBlockGenerator('Значения по-умолчанию для полей');
        $docblock->setTags($tags);
        $columnCollection = $table->getColumn();
        if (!$columnCollection) {
            return;
        }
        $defaults = '';
        /** @var $column Column */
        foreach ($columnCollection as $column) {
            $columnName = $column->getName();
            $defaultValue = $column->getColumnDefault();
            if (substr($columnName, -5) == '_date') {
                $defaults .= "\$this->setDefaultRule('" . $columnName . "', date('Y-m-d H:i:s'));\n    ";
            } elseif ($defaultValue == 'CURRENT_TIMESTAMP') {
                $defaults .= "\$this->setDefaultRule('" . $columnName . "', date('Y-m-d H:i:s'));\n    ";
            } elseif (!empty($defaultValue)) {
                $defaults .= '$this->setDefaultRule(\'' . $columnName . '\', \'' . (string) $defaultValue . '\');' . "\n    ";
            } elseif (is_null($defaultValue) && $column->isNullable()) {
                $defaults .= '$this->setDefaultRule(\'' . $columnName . '\', null);' . "\n    ";
            }
        }
        $tags = array(array('name' => 'return', 'description' => 'void'));
        $docblock = new DocBlockGenerator('Инициализация значений по-умолчанию');
        $docblock->setTags($tags);
        $method = new MethodGenerator();
        $method->setName('initDefaultsRules');
        $method->setVisibility(AbstractMemberGenerator::VISIBILITY_PUBLIC);
        $method->setFinal(true);
        $method->setDocBlock($docblock);
        $method->setBody(<<<EOS
    {$defaults}
\$this->setupDefaultsRules();
EOS
);
        $file->getClass()->addMethodFromGenerator($method);
    }
Ejemplo n.º 11
0
 /**
  * Generate a filter method
  */
 protected function addFilterMethod()
 {
     // set action body
     $body = ['// add filter code here', 'return $value;'];
     $body = implode(AbstractGenerator::LINE_FEED, $body);
     // create method
     $method = new MethodGenerator();
     $method->setName('filter');
     $method->setBody($body);
     $method->setParameters([new ParameterGenerator('value', 'mixed')]);
     // check for api docs
     if ($this->config['flagAddDocBlocks']) {
         $method->setDocBlock(new DocBlockGenerator('Called when filter is executed', null, [new ParamTag('value', ['mixed']), new ReturnTag(['mixed'])]));
     }
     // add method
     $this->addMethodFromGenerator($method);
 }
Ejemplo n.º 12
0
 /**
  * Generate the create service method
  *
  * @param string $className
  * @param string $managerName
  */
 protected function addCreateServiceMethod($className, $managerName)
 {
     // set action body
     $body = array('/** @var ServiceLocatorAwareInterface $' . $managerName . ' */', '$serviceLocator = $' . $managerName . '->getServiceLocator();', '', '$instance = new ' . $className . '();', '', 'return $instance;');
     $body = implode(AbstractGenerator::LINE_FEED, $body);
     // create method
     $method = new MethodGenerator();
     $method->setName('createService');
     $method->setBody($body);
     $method->setParameters(array(new ParameterGenerator($managerName, 'ServiceLocatorInterface')));
     // check for api docs
     if ($this->config['flagAddDocBlocks']) {
         $method->setDocBlock(new DocBlockGenerator('Create service', null, array(new ParamTag($managerName, array('ServiceLocatorInterface')), new ReturnTag(array($className)))));
     }
     // add method
     $this->addMethodFromGenerator($method);
 }
Ejemplo n.º 13
0
 /**
  * Generate a isValid method
  */
 protected function addIsValidMethod()
 {
     // set action body
     $body = ['$this->setValue((string) $value);', '', '// add validation code here', '$isValid = true;', '', 'if (!$isValid) {', '    $this->error(self::INVALID);', '    return false;', '}', '', 'return true;'];
     $body = implode(AbstractGenerator::LINE_FEED, $body);
     // create method
     $method = new MethodGenerator();
     $method->setName('isValid');
     $method->setBody($body);
     $method->setParameters([new ParameterGenerator('value', 'mixed')]);
     // check for api docs
     if ($this->config['flagAddDocBlocks']) {
         $method->setDocBlock(new DocBlockGenerator('Called when validator is executed', null, [new ParamTag('value', ['mixed']), new ReturnTag(['mixed'])]));
     }
     // add method
     $this->addMethodFromGenerator($method);
 }
 /**
  * Generate the create service method
  *
  * @param string $className
  * @param string $moduleName
  * @param string $tableName
  */
 protected function addCreateServiceMethod($className, $moduleName, $tableName)
 {
     $managerName = 'serviceLocator';
     $tableGatewayName = ucfirst($tableName) . 'TableGateway';
     $tableGatewayService = $moduleName . '\\' . $this->config['namespaceTableGateway'] . '\\' . ucfirst($tableName);
     // set action body
     $body = ['/** @var ' . $tableGatewayName . ' $tableGateway */', '$tableGateway = $serviceLocator->get(\'' . $tableGatewayService . '\');', '', '$instance = new ' . $className . '($tableGateway);', '', 'return $instance;'];
     $body = implode(AbstractGenerator::LINE_FEED, $body);
     // create method
     $method = new MethodGenerator();
     $method->setName('createService');
     $method->setBody($body);
     $method->setParameters([new ParameterGenerator($managerName, 'ServiceLocatorInterface')]);
     // check for api docs
     if ($this->config['flagAddDocBlocks']) {
         $method->setDocBlock(new DocBlockGenerator('Create service', null, [new ParamTag($managerName, ['ServiceLocatorInterface']), new ReturnTag([$className])]));
     }
     // add method
     $this->addMethodFromGenerator($method);
 }
Ejemplo n.º 15
0
 public function transform()
 {
     $classGenerator = $this->getService()->getClassGenerator();
     if ($createContactBatch = $classGenerator->getMethod('CreateContactBatch')) {
         $newMethod = new CodeGenerator\MethodGenerator();
         $newMethod->setName($createContactBatch->getName());
         $docblock = $createContactBatch->getDocBlock();
         $docblock->setTag((new CodeGenerator\DocBlock\Tag\ParamTag())->setParamName('id')->setDataType('int'));
         $newMethod->setDocBlock($docblock);
         $parameters = $createContactBatch->getParameters();
         $idParameter = new CodeGenerator\ParameterGenerator();
         $idParameter->setName('id');
         $createContactBatch->setParameter($idParameter);
         $newMethod->setParameters(array("id" => $idParameter, "CreateContactBatch" => $parameters['CreateContactBatch']));
         $body = $createContactBatch->getBody();
         $body = str_replace('array()', 'array($id)', $body);
         $newMethod->setBody($body);
         $classGenerator->removeMethod('CreateContactBatch');
         $classGenerator->addMethodFromGenerator($newMethod);
     }
 }
 public function fixPathParameters($classGenerator, $method, $newParameters)
 {
     $oldMethod = $classGenerator->getMethod($method);
     $newMethod = new CodeGenerator\MethodGenerator();
     $newMethod->setName($oldMethod->getName());
     $docblock = $oldMethod->getDocBlock();
     $parameters = $oldMethod->getParameters();
     $body = $oldMethod->getBody();
     $newParameterSpec = array();
     foreach ($newParameters as $name => $type) {
         $docblock->setTag((new CodeGenerator\DocBlock\Tag\ParamTag())->setParamName($name)->setDataType($type));
         $newParameter = new CodeGenerator\ParameterGenerator();
         $newParameter->setName($name);
         $newMethod->setParameter($newParameter);
         $newParameterSpec[$name] = $newParameter;
     }
     $newMethod->setParameters(array_merge($newParameterSpec, array($method => $parameters[$method])));
     $body = str_replace('array()', 'array($' . implode(', $', array_keys($newParameters)) . ')', $body);
     $newMethod->setDocBlock($docblock);
     $newMethod->setBody($body);
     $classGenerator->removeMethod($method);
     $classGenerator->addMethodFromGenerator($newMethod);
 }
Ejemplo n.º 17
0
    public function postRun(PartInterface $part)
    {
        /**
         * @var $part \Model\Generator\Part\Entity
         */
        /**
         * @var $file \Model\Code\Generator\FileGenerator
         */
        $file = $part->getFile();
        $tableNameAsCamelCase = $part->getTable()->getNameAsCamelCase();
        $tags = array(array('name' => 'return', 'description' => '\\Model\\' . $tableNameAsCamelCase . 'Model экземпляр модели'));
        $docblock = new DocBlockGenerator('Получить экземпляр модели ' . $tableNameAsCamelCase);
        $docblock->setTags($tags);
        $method = new MethodGenerator();
        $method->setName('getInstance');
        $method->setVisibility(AbstractMemberGenerator::VISIBILITY_PUBLIC);
        $method->setStatic(true);
        $method->setDocBlock($docblock);
        $method->setBody(<<<EOS
return parent::getInstance();
EOS
);
        $file->getClass()->addMethodFromGenerator($method);
    }
Ejemplo n.º 18
0
    /**
     * @param PartInterface $part
     */
    public function preRun(PartInterface $part)
    {
        /**
         * @var $part \Model\Generator\Part\Entity
         */
        /**
         * @var $file \Model\Code\Generator\FileGenerator
         */
        $file = $part->getFile();
        /**
         * @var $table \Model\Cluster\Schema\Table
         */
        $table = $part->getTable();
        /** @var $columnList Column[]  */
        $columnList = $table->getColumn();
        foreach ($columnList as $column) {
            $columnName = $column->getName();
            $columnComment = $column->getComment();
            if ($columnComment) {
                $shortDescription = "Get " . mb_strtolower($columnComment, 'UTF-8') . ' (' . $column->getTable()->getName() . '.' . $columnName . ')';
            } else {
                $shortDescription = 'Get ' . $column->getTable()->getName() . '.' . $columnName;
            }
            $docBlock = new DocBlockGenerator($shortDescription);
            $docBlock->setTags(array(array('name' => 'return', 'description' => $column->getTypeAsPhp())));
            $method = new MethodGenerator();
            $method->setName('get' . $column->getNameAsCamelCase());
            $method->setVisibility(AbstractMemberGenerator::VISIBILITY_PUBLIC);
            $method->setDocBlock($docBlock);
            $method->setBody(<<<EOS
return \$this->get('{$columnName}');
EOS
);
            $part->getFile()->getClass()->addMethodFromGenerator($method);
        }
    }
Ejemplo n.º 19
0
    public function postRun(PartInterface $part)
    {
        /**
         * @var $part \Model\Generator\Part\Entity
         */
        /**
         * @var $file \Model\Code\Generator\FileGenerator
         */
        $file = $part->getFile();
        $tableName = $part->getTable()->getName();
        $schema = $part->getTable()->getSchema()->getName();
        $docblock = new DocBlockGenerator('Конструктор');
        $method = new MethodGenerator();
        $method->setName('__construct');
        $method->setVisibility(AbstractMemberGenerator::VISIBILITY_PUBLIC);
        $method->setDocBlock($docblock);
        $method->setBody(<<<EOS
\$this->setName('{$tableName}');
\$this->setDbAdapterName('{$schema}_db');
parent::__construct();
EOS
);
        $file->getClass()->addMethodFromGenerator($method);
    }
Ejemplo n.º 20
0
    /**
     * @group ZF-6444
     */
    public function testMethodWithFinalModifierIsNotEmittedWhenMethodIsAbstract()
    {
        $methodGenerator = new MethodGenerator();
        $methodGenerator->setName('foo');
        $methodGenerator->setParameters(array('one'));
        $methodGenerator->setFinal(true);
        $methodGenerator->setAbstract(true);

        $expected = <<<EOS
    abstract public function foo(\$one)
    {
    }

EOS;
        $this->assertEquals($expected, $methodGenerator->generate());
    }
Ejemplo n.º 21
0
    protected function viewStub($part)
    {
        /**
         * @var $part \Model\Generator\Part\Model
         */
        /**
         * @var $file \Model\Code\Generator\FileGenerator
         */
        $file = $part->getFile();
        $table = $part->getTable();
        $tableNameAsCamelCase = $table->getNameAsCamelCase();
        $entity = $tableNameAsCamelCase . 'Entity';
        $collection = $tableNameAsCamelCase . 'Collection';
        $p = new \Zend\Code\Generator\ParameterGenerator('cond');
        $p->setType('Cond');
        $p->setDefaultValue(null);
        $params[] = $p;
        $docblock = new DocBlockGenerator('Получить объект условий в виде представления \'Extended\'

$param Cond $cond
$return Cond
        ');
        $method = new MethodGenerator();
        $method->setName('getCondAsExtendedView');
        $method->setVisibility(AbstractMemberGenerator::VISIBILITY_PUBLIC);
        $method->setFinal(false);
        $method->setDocBlock($docblock);
        $method->setParameters($params);
        $method->setBody(<<<EOS
\$cond = \$this->prepareCond(\$cond);
\$cond->where(array('status' => 'active'));
return \$cond;
EOS
);
        $file->getClass()->addMethodFromGenerator($method);
        $p = new \Zend\Code\Generator\ParameterGenerator('cond');
        $p->setType('Cond');
        $p->setDefaultValue(null);
        $params[] = $p;
        $docblock = new DocBlockGenerator('Получить элемент в виде представления \'Extended\'

@param Cond $cond
@return ' . $entity);
        $method = new MethodGenerator();
        $method->setName('getAsExtendedView');
        $method->setVisibility(AbstractMemberGenerator::VISIBILITY_PUBLIC);
        $method->setFinal(false);
        $method->setDocBlock($docblock);
        $method->setParameters($params);
        $method->setBody(<<<EOS
\$cond = \$this->getCondAsExtendedView(\$cond);
return \$this->get(\$cond);
EOS
);
        $file->getClass()->addMethodFromGenerator($method);
        $p = new \Zend\Code\Generator\ParameterGenerator('cond');
        $p->setType('Cond');
        $p->setDefaultValue(null);
        $params[] = $p;
        $docblock = new DocBlockGenerator('Получить коллекцию в виде представления \'Extended\'

@param Cond $cond
@return ' . $collection);
        $method = new MethodGenerator();
        $method->setName('getCollectionAsExtendedView');
        $method->setVisibility(AbstractMemberGenerator::VISIBILITY_PUBLIC);
        $method->setFinal(false);
        $method->setDocBlock($docblock);
        $method->setParameters($params);
        $method->setBody(<<<EOS
\$cond = \$this->getCondAsExtendedView(\$cond);
return \$this->getCollection(\$cond);
EOS
);
        $file->getClass()->addMethodFromGenerator($method);
    }
Ejemplo n.º 22
0
 /**
  * Generate an hydrate method
  */
 protected function addHydrateMethod()
 {
     // set action body
     $body = ['// add extended hydrator logic here', 'return parent::hydrate($data, $object);'];
     $body = implode(AbstractGenerator::LINE_FEED, $body);
     // create method
     $method = new MethodGenerator();
     $method->setName('hydrate');
     $method->setBody($body);
     $method->setParameters([new ParameterGenerator('data', 'array'), new ParameterGenerator('object', 'object')]);
     // check for api docs
     if ($this->config['flagAddDocBlocks']) {
         $method->setDocBlock(new DocBlockGenerator('Hydrate an object by populating data', null, [new ParamTag('data', ['array']), new ParamTag('object', ['object']), new ReturnTag(['object'])]));
     }
     // add method
     $this->addMethodFromGenerator($method);
 }
Ejemplo n.º 23
0
 private function buildClass($replacement)
 {
     $type = $this->splitNsandClass($replacement['originalFullyQualifiedType']);
     $class = new ClassGenerator();
     $class->setName($type['class']);
     $class->setNamespaceName($type['ns']);
     $class->setExtendedClass('\\Brads\\Ppm\\Proxy');
     $properties = [];
     $methods = [];
     $implementedInterfaces = [];
     foreach ($versions as $version => $info) {
         foreach ($info['files'] as $file) {
             echo "Parsing: " . $this->vendorDir . '/' . $package . '/' . $version . '/' . $file . "\n";
             $parsedFile = new ReflectionFile($this->vendorDir . '/' . $package . '/' . $version . '/' . $file);
             $parsedClass = $parsedFile->getFileNamespace($info['toNs'])->getClass($info['toNs'] . '\\' . $type['class']);
             if ($parsedClass->getInterfaceNames() != null) {
                 $implementedInterfaces = array_merge($implementedInterfaces, $parsedClass->getInterfaceNames());
             }
             foreach ($parsedClass->getMethods() as $method) {
                 if ($method->isPublic()) {
                     $generatedMethod = new MethodGenerator();
                     $generatedMethod->setName($method->name);
                     $generatedMethod->setBody('echo "Hello world!";');
                     $generatedMethod->setAbstract($method->isAbstract());
                     $generatedMethod->setFinal($method->isFinal());
                     $generatedMethod->setStatic($method->isStatic());
                     $generatedMethod->setVisibility(MethodGenerator::VISIBILITY_PUBLIC);
                     foreach ($method->getParameters() as $param) {
                         $generatedParam = new ParameterGenerator();
                         $generatedParam->setName($param->name);
                         if ($param->hasType()) {
                             $generatedParam->setType($param->getType());
                         }
                         //$generatedParam->setDefaultValue($param->getDefaultValue());
                         $generatedParam->setPosition($param->getPosition());
                         $generatedParam->setVariadic($param->isVariadic());
                         $generatedParam->setPassedByReference($param->isPassedByReference());
                         $generatedMethod->setParameter($generatedParam);
                     }
                     $existingMethod = Linq::from($methods)->firstOrDefault(null, function (MethodGenerator $v) use($method) {
                         return $v->getName() == $method->name;
                     });
                     if ($existingMethod != null) {
                         $existingParams = $existingMethod->getParameters();
                         foreach ($generatedMethod->getParameters() as $newParam) {
                             $existingParam = Linq::from($existingParams)->firstOrDefault(function (ParameterGenerator $v) {
                                 return $v->getName() == $newParam->getName();
                             });
                             if ($existingParam == null) {
                                 $existingMethod->setParameter($newParam);
                             }
                         }
                     } else {
                         $methods[] = $generatedMethod;
                     }
                 }
             }
             foreach ($parsedClass->getProperties() as $prop) {
                 //$properties[] = PropertyGenerator::fromReflection($prop);
             }
         }
     }
     $class->setImplementedInterfaces($implementedInterfaces);
     $class->addMethods($methods);
     $class->addProperties($properties);
     return (new FileGenerator(['classes' => [$class]]))->generate();
 }
Ejemplo n.º 24
0
 /**
  * Generate the create service method
  *
  * @param string $className
  * @param        $moduleName
  * @param string $entityModule
  * @param        $entityClass
  */
 protected function addCreateServiceMethod($className, $moduleName, $entityModule, $entityClass)
 {
     // prepare repository params
     $repositoryClass = str_replace('Entity', '', $entityClass) . 'Repository';
     $repositoryParam = lcfirst($repositoryClass);
     $repositoryService = $entityModule . '\\' . $this->config['namespaceRepository'] . '\\' . str_replace('Entity', '', $entityClass);
     // prepare form params
     if (in_array($className, ['CreateController', 'UpdateController'])) {
         $formClass = str_replace('Entity', '', $entityClass) . 'DataForm';
         $formParam = lcfirst($formClass);
         $formService = $moduleName . '\\Data\\Form';
     } elseif (in_array($className, ['DeleteController'])) {
         $formClass = str_replace('Entity', '', $entityClass) . 'DeleteForm';
         $formParam = lcfirst($formClass);
         $formService = $moduleName . '\\Delete\\Form';
     } else {
         $formClass = null;
         $formParam = null;
         $formService = null;
     }
     // set action body
     $body = [];
     $body[] = '$serviceLocator = $controllerManager->getServiceLocator();';
     $body[] = '';
     if ($formClass) {
         $body[] = '/** @var ServiceLocatorInterface $formElementManager */';
         $body[] = '$formElementManager = $serviceLocator->get(\'FormElementManager\');';
         $body[] = '';
     }
     $body[] = '/** @var ' . $repositoryClass . ' $' . $repositoryParam . ' */';
     $body[] = '$' . $repositoryParam . ' = $serviceLocator->get(\'' . $repositoryService . '\');';
     $body[] = '';
     if ($formClass) {
         $body[] = '/** @var ' . $formClass . ' $' . $formParam . ' */';
         $body[] = '$' . $formParam . ' = $formElementManager->get(\'' . $formService . '\');';
         $body[] = '';
     }
     $body[] = '$instance = new ' . $className . '();';
     $body[] = '$instance->set' . $repositoryClass . '($' . $repositoryParam . ');';
     if ($formClass) {
         $body[] = '$instance->set' . $formClass . '($' . $formParam . ');';
     }
     $body[] = '';
     $body[] = 'return $instance;';
     $body = implode(AbstractGenerator::LINE_FEED, $body);
     // create method
     $method = new MethodGenerator();
     $method->setName('createService');
     $method->setBody($body);
     $method->setParameters([new ParameterGenerator('controllerManager', 'ServiceLocatorInterface')]);
     // check for api docs
     if ($this->config['flagAddDocBlocks']) {
         $method->setDocBlock(new DocBlockGenerator('Create service', null, [new ParamTag('controllerManager', ['ServiceLocatorInterface', 'ServiceLocatorAwareInterface']), new ReturnTag([$className])]));
     }
     // add method
     $this->addMethodFromGenerator($method);
 }
Ejemplo n.º 25
0
 /**
  * Create a PhpMethod code generation object named after a given alias
  *
  * @param  string          $alias
  * @param  string          $class Class to which alias refers
  * @return MethodGenerator
  */
 protected function getCodeGenMethodFromAlias($alias, $class)
 {
     $alias = $this->normalizeAlias($alias);
     $method = new MethodGenerator();
     $method->setName($alias);
     $method->setBody(sprintf('return $this->get(\'%s\');', $class));
     return $method;
 }
Ejemplo n.º 26
0
    public function testSetMethodNameAlreadyExistsThrowsException()
    {
        $methodA = new MethodGenerator();
        $methodA->setName("foo");
        $methodB = new MethodGenerator();
        $methodB->setName("foo");

        $classGenerator = new ClassGenerator();
        $classGenerator->addMethodFromGenerator($methodA);

        $this->setExpectedException(
            'Zend\Code\Generator\Exception\InvalidArgumentException',
            'A method by name foo already exists in this class.'
        );

        $classGenerator->addMethodFromGenerator($methodB);
    }
Ejemplo n.º 27
0
 /**
  * Generate the getConfig() method
  *
  * @return MethodGenerator
  */
 protected function generateGetConfigMethod()
 {
     // create method body
     $body = new ValueGenerator();
     $body->initEnvironmentConstants();
     $body->setValue('include __DIR__ . \'/config/module.config.php\'');
     // create method
     $method = new MethodGenerator();
     $method->setName('getConfig');
     $method->setBody('return ' . $body->generate() . ';' . AbstractGenerator::LINE_FEED);
     // add optional doc block
     if ($this->flagCreateApiDocs) {
         $method->setDocBlock(new DocBlockGenerator('Get module configuration', null, array($this->generateReturnTag('array'))));
     }
     return $method;
 }
Ejemplo n.º 28
0
 /**
  * @param ClassGenerator $class
  * @param Attribute $tagAttribute
  */
 protected function addAttribute(ClassGenerator $class, Attribute $tagAttribute)
 {
     $methodName = str_replace(':', '-', $tagAttribute->getName());
     $methodName = ucfirst($this->stringToCamelCaseConverter->convert($methodName, '-'));
     $method = new MethodGenerator();
     if ($tagAttribute->isFlag()) {
         $method->setName('is' . $methodName);
         $method->setParameter(new ParameterGenerator('v', 'bool', true));
     } else {
         $method->setName('set' . $methodName);
         $method->setParameter(new ParameterGenerator('v', 'string'));
     }
     $body = [];
     $body[] = '$this->attributes[\'' . $tagAttribute->getName() . '\'] = $v;';
     $body[] = 'return $this;';
     $method->setBody(implode(PHP_EOL, $body));
     $docBlock = new DocBlockGenerator();
     $docBlock->setTag(new GenericTag('var', 'string'));
     $docBlock->setTag(new GenericTag('return', '$this'));
     if (!is_null($tagAttribute->getDescription())) {
         $docBlock->setLongDescription($tagAttribute->getDescription());
     }
     $method->setDocBlock($docBlock);
     $class->addMethodFromGenerator($method);
 }
Ejemplo n.º 29
0
 /**
  * Generate an hydrate method
  */
 protected function addHydrateMethod()
 {
     $refTableData = $this->loadedTables[$this->refTableName];
     /** @var ColumnObject $firstColumn */
     $firstColumn = reset($refTableData['columns']);
     // set action body
     $body = [];
     $body[] = 'if (isset($data[\'' . $this->refTableName . '.' . $firstColumn->getName() . '\'])) {';
     /** @var ColumnObject $column */
     foreach ($refTableData['columns'] as $column) {
         $body[] = '    $' . $column->getName() . ' = $data[\'' . $this->refTableName . '.' . $column->getName() . '\'];';
     }
     $body[] = '} else {';
     /** @var ColumnObject $column */
     foreach ($refTableData['columns'] as $column) {
         $body[] = '    $' . $column->getName() . ' = $value;';
     }
     $body[] = '}';
     $body[] = '';
     $body[] = '$' . $this->refTableName . ' = new ' . $this->entityClass . '();';
     $body[] = '$' . $this->refTableName . '->exchangeArray(';
     $body[] = '    [';
     /** @var ColumnObject $column */
     foreach ($refTableData['columns'] as $column) {
         $body[] = '        \'' . $column->getName() . '\' => $' . $column->getName() . ',';
     }
     $body[] = '    ]';
     $body[] = ');';
     $body[] = '';
     $body[] = 'return $' . $this->refTableName . ';';
     $body = implode(AbstractGenerator::LINE_FEED, $body);
     // create method
     $method = new MethodGenerator();
     $method->setName('hydrate');
     $method->setBody($body);
     $method->setParameters([new ParameterGenerator('value'), new ParameterGenerator('data', 'array', [])]);
     // check for api docs
     if ($this->config['flagAddDocBlocks']) {
         $method->setDocBlock(new DocBlockGenerator('Hydrate an entity by populating data', null, [new ParamTag('value'), new ParamTag('data', ['array']), new ReturnTag([$this->entityClass])]));
     }
     // add method
     $this->addMethodFromGenerator($method);
 }
Ejemplo n.º 30
0
    public function postRun(PartInterface $part)
    {
        /**
         * @var $part \Model\Generator\Part\Entity
         */
        /**
         * @var $file \Model\Code\Generator\FileGenerator
         */
        $file = $part->getFile();
        $columnCollection = $part->getTable()->getColumn();
        $template = '';
        /** @var $column Column */
        foreach ($columnCollection as $column) {
            $name = $column->getName();
            $requiredFlag = !($column->isNullable() || $column->getName() == 'id');
            if ($columnConfig = $part->getColumntConfig($column)) {
                if ($columnConfig && isset($columnConfig['validators'])) {
                    foreach ($columnConfig['validators'] as $validator) {
                        if (isset($validator['params'])) {
                            $validatorParams = $this->prepareValidatorParams($validator['params'], $column);
                            $validatorParams = $this->varExportMin($validatorParams, true);
                        } else {
                            $validatorParams = null;
                        }
                        if ($validatorParams && $validatorParams != 'NULL') {
                            $template .= "\$this->addValidatorRule('{$name}', Model::getValidatorAdapter()->getValidatorInstance('{$validator['name']}', {$validatorParams}), " . ($requiredFlag ? 'true' : 'false') . ");\n";
                        } else {
                            $template .= "\$this->addValidatorRule('{$name}', Model::getValidatorAdapter()->getValidatorInstance('{$validator['name']}'), " . ($requiredFlag ? 'true' : 'false') . ");\n";
                        }
                    }
                }
            }
        }
        $template = rtrim($template, "\r\n, ");
        //$tableNameAsCamelCase = $part->getTable()->getNameAsCamelCase();
        $tags = array(array('name' => 'return', 'description' => 'array Model массив с фильтрами по полям'));
        $docblock = new DocBlockGenerator('Получить правила для фильтрации ');
        $docblock->setTags($tags);
        $method = new MethodGenerator();
        $method->setName('initValidatorRules');
        $method->setVisibility(AbstractMemberGenerator::VISIBILITY_PUBLIC);
        $method->setStatic(false);
        $method->setFinal(true);
        $method->setDocBlock($docblock);
        $method->setBody(<<<EOS
{$template}
\$this->setupValidatorRules();
EOS
);
        $file->getClass()->addMethodFromGenerator($method);
    }