setParameter() public method

public setParameter ( ParameterGenerator | array | string $parameter ) : MethodGenerator
$parameter ParameterGenerator | array | string
return MethodGenerator
    /**
     * @param  State|\Scaffold\State $state
     * @return State|void
     */
    public function build(State $state)
    {
        $model = $state->getModel('options-factory');
        $generator = new ClassGenerator($model->getName());
        $generator->setImplementedInterfaces(['FactoryInterface']);
        $model->setGenerator($generator);
        $generator->addUse('Zend\\ServiceManager\\FactoryInterface');
        $generator->addUse('Zend\\ServiceManager\\ServiceLocatorInterface');
        $options = $state->getModel('options');
        $key = $options->getServiceName();
        $key = substr($key, 0, -7);
        $body = <<<EOF
\$config = \$serviceLocator->get('Config');
return new {$options->getClassName()}(
    isset(\$config['{$key}'])
        ? \$config['{$key}']
        : []
);
EOF;
        $method = new MethodGenerator('createService');
        $method->setParameter(new ParameterGenerator('serviceLocator', 'ServiceLocatorInterface'));
        $method->setBody($body);
        $doc = new DocBlockGenerator('');
        $doc->setTag(new Tag(['name' => 'inhertidoc']));
        $method->setDocBlock($doc);
        $generator->addMethodFromGenerator($method);
    }
    public function buildCreateService(ClassGenerator $generator, State $state)
    {
        $method = new MethodGenerator('createService');
        $method->setDocBlock(new DocBlockGenerator());
        $method->getDocBlock()->setShortDescription('{@inheritdoc}');
        $method->setParameter(new ParameterGenerator('serviceLocator', 'ServiceLocatorInterface'));
        $name = lcfirst($state->getEntityModel()->getClassName());
        $entity = $state->getEntityModel()->getName();
        $method->setBody(<<<EOF
            \$form = new Form('{$name}');

\$submit = new Element\\Submit('submit');
\$submit->setValue('Submit');
\$form->add(\$submit);

\$form->setInputFilter(\$this->getInputFilter());

/** @var EntityManager \$entityManager */
\$entityManager = \$serviceLocator->get('entity_manager');
\$form->setHydrator(new DoctrineObject(\$entityManager, '{$entity}'));

return \$form;
EOF
);
        $generator->addMethodFromGenerator($method);
    }
 /**
  * Build generators
  *
  * @param  State|\Scaffold\State $state
  * @return \Scaffold\State|void
  */
 public function build(State $state)
 {
     $model = $this->model;
     $generator = new ClassGenerator($model->getName());
     $generator->addUse('Zend\\ServiceManager\\FactoryInterface');
     $generator->addUse('Zend\\ServiceManager\\ServiceLocatorInterface');
     $generator->addUse('Zend\\ServiceManager\\ServiceManager');
     $generator->addUse($state->getServiceModel()->getName());
     $generator->setImplementedInterfaces(['FactoryInterface']);
     $method = new MethodGenerator('createService');
     $method->setParameter(new ParameterGenerator('serviceLocator', 'ServiceLocatorInterface'));
     $method->setBody('return new ' . $state->getServiceModel()->getClassName() . '($serviceLocator);');
     $doc = new DocBlockGenerator('Create service');
     $doc->setTag(new Tag\GenericTag('param', 'ServiceLocatorInterface|ServiceManager $serviceLocator'));
     $doc->setTag(new Tag\GenericTag('return', $state->getServiceModel()->getClassName()));
     $method->setDocBlock($doc);
     $generator->addMethodFromGenerator($method);
     $model->setGenerator($generator);
 }
 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);
 }
 /**
  * Generate the init() method
  */
 protected function addInitMethod()
 {
     // set action body
     $bodyContent = ['if (!defined(\'' . $this->moduleRootConstant . '\')) {', '    define(\'' . $this->moduleRootConstant . '\', realpath(__DIR__));', '}'];
     $bodyContent = implode(AbstractGenerator::LINE_FEED, $bodyContent);
     // create method body
     $body = new BodyGenerator();
     $body->setContent($bodyContent);
     // create method
     $method = new MethodGenerator();
     $method->setName('init');
     $method->setBody($body->generate());
     $method->setParameter(new ParameterGenerator('manager', 'ModuleManagerInterface'));
     // check for api docs
     if ($this->config['flagAddDocBlocks']) {
         $method->setDocBlock(new DocBlockGenerator('Init module', 'Initialize module on loading', [new ParamTag('manager', ['ModuleManagerInterface'])]));
     }
     // add method
     $this->addMethodFromGenerator($method);
     $this->addUse('Zend\\ModuleManager\\Feature\\InitProviderInterface');
     $this->addUse('Zend\\ModuleManager\\ModuleManagerInterface');
     $this->setImplementedInterfaces(array_merge($this->getImplementedInterfaces(), ['InitProviderInterface']));
 }
 /**
  * @param string           $columnName
  * @param ConstraintObject $foreignKey
  */
 protected function addOptionsSetter($columnName, ConstraintObject $foreignKey)
 {
     $body = '$this->' . $columnName . 'Options = $' . $columnName . 'Options;';
     $parameter = new ParameterGenerator($columnName . 'Options', 'array');
     $setMethodName = 'set' . ucfirst($columnName) . 'Options';
     $setMethod = new MethodGenerator($setMethodName);
     $setMethod->addFlag(MethodGenerator::FLAG_PUBLIC);
     $setMethod->setParameter($parameter);
     $setMethod->setDocBlock(new DocBlockGenerator('Set ' . $columnName . ' options', null, [['name' => 'param', 'description' => 'array $' . $columnName . 'Options']]));
     $setMethod->setBody($body);
     $this->addMethodFromGenerator($setMethod);
 }
 protected function buildDelete(ClassGenerator $generator, State $state)
 {
     $body = '$this->getEntityManager()->remove($model);';
     $method = new MethodGenerator('delete');
     $method->setParameter(new ParameterGenerator('model', $state->getEntityModel()->getClassName()));
     $method->setDocBlock(new DocBlockGenerator());
     $method->getDocBlock()->setTag(new Tag\GenericTag('param', $state->getEntityModel()->getClassName() . ' $model'));
     $method->setBody($body);
     $generator->addMethodFromGenerator($method);
 }
Example #8
0
 /**
  * @param $objectClass
  * @param $serviceManagerClass
  *
  * @return MethodGenerator
  */
 protected function generateCreateServiceMethod($objectClass, $serviceManagerClass, $instanceName)
 {
     // init body
     $methodBody = array();
     // add service locator if needed
     if ($serviceManagerClass !== 'serviceLocator') {
         $methodBody[] = '// get service locator to fetch other services';
         $methodBody[] = '$serviceLocator = $' . $serviceManagerClass . '->getServiceLocator();';
         $methodBody[] = '';
     }
     // add class instantiation
     $methodBody[] = '// get all services that need to be injected';
     $methodBody[] = ';';
     $methodBody[] = '';
     $methodBody[] = '// instantiate class';
     $methodBody[] = '$' . $instanceName . ' = new ' . $objectClass . '();';
     $methodBody[] = '';
     $methodBody[] = '// inject all services ';
     $methodBody[] = ';';
     $methodBody[] = '';
     $methodBody[] = '// return instance of class';
     $methodBody[] = 'return $' . $instanceName . ';';
     // create method
     $method = new MethodGenerator();
     $method->setName('createService');
     $method->setParameter(new ParameterGenerator($serviceManagerClass, 'ServiceLocatorInterface'));
     $method->setBody(implode(AbstractGenerator::LINE_FEED, $methodBody));
     // add optional doc block
     if ($this->flagCreateApiDocs) {
         $method->setDocBlock(new DocBlockGenerator('Create service', 'Please add a proper description for this method', array($this->generateParamTag('ServiceLocatorInterface $' . $serviceManagerClass), $this->generateReturnTag($objectClass))));
     }
     return $method;
 }
Example #9
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();
 }
 private function getServiceCode()
 {
     $code = new ClassGenerator($this->service->getName(), $this->namespace, null, '\\SoapClient');
     $doc = $this->service->getDoc();
     if ($doc) {
         $docBlock = new DocBlockGenerator($doc);
         $code->setDocBlock($docBlock);
     }
     foreach ($this->service->getFunctions() as $function) {
         $method = new MethodGenerator($function->getMethod());
         $docBlock = new DocBlockGenerator($function->getDoc());
         foreach ($function->getParams() as $param) {
             $methodParam = new ParameterGenerator($param->getName());
             if (false === $param->isPrimitive()) {
                 $methodParam->setType('\\' . $this->getFullNamespace($param->getType()));
             }
             $method->setParameter($methodParam);
             $tag = new Tag();
             $tag->setName('property');
             $type = $param->getType();
             if (false === $param->isPrimitive()) {
                 $type = '\\' . $this->getFullNamespace($param->getType());
             }
             $tag->setDescription(sprintf('%s $%s', $type, $param->getName()));
             $docBlock->setTag($tag);
         }
         $tag = new Tag();
         $tag->setName('returns');
         $tag->setDescription("\\" . $this->getFullNamespace($function->getReturns()));
         $docBlock->setTag($tag);
         $method->setBody(sprintf('return $this->__soapCall("%s", func_get_args());', $function->getName()));
         $method->setDocBlock($docBlock);
         $code->addMethodFromGenerator($method);
     }
     return $code;
 }
 /**
  * @param $columnName
  * @param $columnType
  *
  * @return MethodGenerator
  */
 protected function generateSetMethod($columnName, $columnType)
 {
     if (in_array($columnType, ['string', 'integer'])) {
         $body = '$this->' . $columnName . ' = (' . $columnType . ') $' . $columnName . ';';
         $parameter = new ParameterGenerator($columnName);
     } else {
         $body = '$this->' . $columnName . ' = $' . $columnName . ';';
         $parameter = new ParameterGenerator($columnName, $columnType);
     }
     $setMethodName = 'set' . ucfirst($columnName);
     $setMethod = new MethodGenerator($setMethodName);
     $setMethod->addFlag(MethodGenerator::FLAG_PROTECTED);
     $setMethod->setParameter($parameter);
     $setMethod->setDocBlock(new DocBlockGenerator('Set ' . $columnName, null, [['name' => 'param', 'description' => $columnType . ' $' . $columnName]]));
     $setMethod->setBody($body);
     return $setMethod;
 }
Example #12
0
 public function buildController($model)
 {
     $class = new ClassGenerator($model->config->name . 'sController');
     $class->setExtendedClass('\\lithium\\action\\Controller');
     $class->setNamespaceName('app\\controllers');
     $publicActions = new PropertyGenerator('publicActions', array(), PropertyGenerator::FLAG_PUBLIC);
     $class->setProperty($publicActions);
     $messageMethod = new MethodGenerator('message');
     $messageMethod->setParameter('value');
     $messageMethod->setBody("\\lithium\\storage\\Session::write('message', \$value);");
     $class->setMethod($messageMethod);
     foreach (array('index', 'create', 'edit', 'view', 'delete') as $action) {
         $method = new MethodGenerator($action);
         $single = strtolower("{$model->config->name}");
         $plurals = $single . "s";
         switch ($action) {
             case 'index':
                 $body = "\${$plurals} = {$model->config->name}::findAll();\n\n";
                 $body .= "return compact('{$plurals}');";
                 $method->setBody($body);
                 break;
             case 'create':
                 $body = "if (\$this->request->data) {\n\n";
                 $body .= "\t\${$single} = new {$model->config->name}(\$this->request->data);\n\n";
                 $body .= "\tif(\${$single}->save()) {\n";
                 $body .= "\t\t\$this->message('Successfully to create {$model->config->name}');\n";
                 $body .= "\t\t\$this->redirect('{$model->config->name}s::index');\n";
                 $body .= "\t} else {\n";
                 $body .= "\t\t\$this->message('Failed to create {$model->config->name}, please check the error');\n";
                 $body .= "\t\t\$errors = \${$single}->getErrors();\n";
                 $body .= "\t}\n\n";
                 $body .= "}\n\n";
                 $body .= "return compact('{$single}', 'errors');";
                 $method->setBody($body);
                 break;
             case 'edit':
                 $body = "if (\$this->request->id) {\n\n";
                 $body .= "\t\${$single} = {$model->config->name}::get(\$this->request->id);\n";
                 $body .= "\t\${$single}->properties = \$this->request->data;\n\n";
                 $body .= "\tif(\${$single}->save()) {\n";
                 $body .= "\t\t\$this->message('Successfully to update {$model->config->name}');\n";
                 $body .= "\t\t\$this->redirect('{$model->config->name}s::index');\n";
                 $body .= "\t} else {\n";
                 $body .= "\t\t\$this->message('Failed to update {$model->config->name}, please check the error');\n";
                 $body .= "\t\t\$errors = \${$single}->getErrors();\n";
                 $body .= "\t}\n\n";
                 $body .= "}\n\n";
                 $body .= "return compact('{$single}', 'errors');";
                 $method->setBody($body);
                 break;
             case 'view':
                 $body = "if (\$this->request->id) {\n";
                 $body .= "\t\${$single} = {$model->config->name}::get(\$this->request->id);\n";
                 $body .= "}\n\n";
                 $body .= "return compact('{$single}');";
                 $method->setBody($body);
                 break;
             case 'delete':
                 $body = "if (\$this->request->id) {\n";
                 $body .= "\t\${$single} = {$model->config->name}::get(\$this->request->id);\n";
                 $body .= "\t\${$single}->delete();\n";
                 $body .= "\t\$this->message('Success to delete {$model->config->name}');\n";
                 $body .= "\t\$this->redirect('{$model->config->name}s::index');\n";
                 $body .= "\treturn true;\n";
                 $body .= "}\n\n";
                 $body .= "\$this->message('{$model->config->name} id cannot be empty');\n";
                 $body .= "\$this->redirect(\$this->request->referer());\n";
                 $body .= "return false;";
                 $method->setBody($body);
                 break;
         }
         $class->setMethod($method);
     }
     return $class;
 }
Example #13
0
    /**
     * @param AbstractLink $link
     * @return MethodGenerator
     */
    protected function getDeleteLinkMethodWithoutLinkTable(AbstractLink $link)
    {
        $localEntity = $link->getLocalEntity();
        $localEntityAsVar = $link->getLocalEntityAsVar();
        $localEntityAsCamelCase = $link->getLocalEntityAsCamelCase();
        $foreignTableAsCamelCase = $link->getForeignTable()->getNameAsCamelCase();
        $foreignEntity = $link->getForeignEntity();
        $foreignEntityAsVar = $link->getForeignEntityAsVar();
        $foreignEntityAsCamelCase = $link->getForeignEntityAsCamelCase();
        $localColumn = $link->getLocalColumn()->getName();
        $foreignColumn = $link->getForeignColumn()->getName();
        $tags = array(array('name' => 'param', 'description' => 'mixed $' . $localEntityAsVar), array('name' => 'param', 'description' => 'mixed $' . $foreignEntityAsVar), array('name' => 'return', 'description' => '\\Model\\Result\\Result'));
        $docblock = new DocBlockGenerator('Отвязать ' . $localEntityAsCamelCase . ' от ' . $foreignEntityAsCamelCase);
        $docblock->setTags($tags);
        $nullValue = new ValueGenerator('array()', ValueGenerator::TYPE_CONSTANT);
        $method = new MethodGenerator();
        $method->setName('deleteLink' . $localEntityAsCamelCase . 'To' . $foreignEntityAsCamelCase);
        $method->setParameter(new ParameterGenerator($localEntityAsVar, 'mixed', $nullValue));
        $method->setParameter(new ParameterGenerator($foreignEntityAsVar, 'mixed', $nullValue));
        $method->setVisibility(AbstractMemberGenerator::VISIBILITY_PUBLIC);
        $method->setDocBlock($docblock);
        if ($link->isDirect()) {
            $method->setBody(<<<EOS
\${$localEntityAsVar}Ids = array_unique(\$this->getIdsFromMixed(\${$localEntityAsVar}));
\${$foreignEntityAsVar}Ids = array_unique({$foreignTableAsCamelCase}Model::getInstance()->getIdsFromMixed(\${$foreignEntityAsVar}));

\$result = new Result();
\$result->setResult(true);

if (count(\${$localEntityAsVar}Ids) == 0 && count(\${$foreignEntityAsVar}Ids) == 0) {
    return \$result;
}

\$cond = array();
if (count(\${$localEntityAsVar}Ids) != 0) {
    \$cond['{$foreignColumn}'] = \${$localEntityAsVar}Ids;
}

if (count(\${$foreignEntityAsVar}Ids) != 0) {
    \$cond['{$localColumn}'] = \${$foreignEntityAsVar}Ids;
}

try {
    \$this->getDb()->update(\$this->getRawName(), array('{$localColumn}' => null), \$cond);
} catch (\\Exception \$e) {
    \$result->setResult(false);
    \$result->addError("Delete link {$localEntity} to {$foreignEntity} failed", 'delete_link_failed');
}

return \$result;
EOS
);
        } else {
            $method->setBody(<<<EOS
return {$foreignTableAsCamelCase}Model::getInstance()->deleteLink{$foreignEntityAsCamelCase}To{$localEntityAsCamelCase}(\${$foreignEntityAsVar}, \${$localEntityAsVar});
EOS
);
        }
        return $method;
    }
Example #14
0
    public function generateMethodsByRelated($part)
    {
        /** @var $part \Model\Generator\Part\Model */
        /** @var $file \Model\Code\Generator\FileGenerator */
        $file = $part->getFile();
        $table = $part->getTable();
        $linkList = $table->getLink();
        foreach ($linkList as $link) {
            $localColumnName = $link->getLocalColumn()->getName();
            $localColumnNameAsVar = $link->getLocalColumn()->getNameAsVar();
            $localColumnNameAsCamelCase = $link->getLocalColumn()->getNameAsCamelCase();
            $localEntityName = $link->getLocalEntity();
            $localEntityNameAsCamelCase = $link->getLocalEntityAsCamelCase();
            $localEntityNameAsVar = $link->getLocalEntityAsVar();
            $localTableName = $link->getLocalTable()->getName();
            $localTableNameAsVar = $link->getLocalTable()->getNameAsVar();
            $localTableNameAsCamelCase = $link->getLocalTable()->getNameAsCamelCase();
            $foreignEntityName = $link->getForeignEntity();
            $foreignEntityNameAsCamelCase = $link->getForeignEntityAsCamelCase();
            $foreignEntityNameAsVar = $link->getForeignEntityAsVar();
            $foreignColumnName = $link->getForeignColumn()->getName();
            $foreignColumnNameAsVar = $link->getForeignColumn()->getNameAsVar();
            $foreignColumnNameAsCamelCase = $link->getForeignColumn()->getNameAsCamelCase();
            $foreignTableName = $link->getForeignTable()->getName();
            $foreignTableNameAsVar = $link->getForeignTable()->getNameAsVar();
            $foreignTableNameAsCamelCase = $link->getForeignTable()->getNameAsCamelCase();
            $linkTableName = $link->getLinkTable() ? $link->getLinkTable()->getName() : '';
            $linkTableLocalColumnName = $link->getLinkTableLocalColumn() ? $link->getLinkTableLocalColumn()->getName() : '';
            $linkTableForeignColumnName = $link->getLinkTableForeignColumn() ? $link->getLinkTableForeignColumn()->getName() : '';
            $tags = array(array('name' => 'param', 'description' => "{$foreignTableNameAsCamelCase}Entity|\\Model\\Collection\\{$foreignTableNameAsCamelCase}Collection|int|string|array \$" . $foreignEntityNameAsVar), array('name' => 'param', 'description' => $localTableNameAsCamelCase . 'Cond' . ' $cond Дядя Кондиций :-)'), array('name' => 'return', 'description' => $localTableNameAsCamelCase . 'Entity'));
            $file->addUse('\\Model\\Entity\\' . $foreignTableNameAsCamelCase . 'Entity');
            $file->addUse('\\Model\\Cond\\' . $foreignTableNameAsCamelCase . 'Cond');
            $file->addUse('\\Model\\Collection\\' . $foreignTableNameAsCamelCase . 'Collection');
            $docblock = new DocBlockGenerator("Получить запись {$localEntityName} по {$foreignEntityNameAsVar}");
            $docblock->setTags($tags);
            $params = array(new ParameterGenerator($foreignEntityNameAsVar));
            $methodName = 'get';
            if ($localEntityNameAsCamelCase == $localTableNameAsCamelCase) {
                $methodName .= 'By' . $foreignEntityNameAsCamelCase;
            } else {
                $methodName .= $localEntityNameAsCamelCase . 'By' . $foreignEntityNameAsCamelCase;
            }
            $nullValue = new \Zend\Code\Generator\ValueGenerator('null', \Zend\Code\Generator\ValueGenerator::TYPE_CONSTANT);
            $method = new \Zend\Code\Generator\MethodGenerator();
            $method->setName($methodName);
            $method->setVisibility(\Zend\Code\Generator\AbstractMemberGenerator::VISIBILITY_PUBLIC);
            $method->setDocBlock($docblock);
            $method->setParameters($params);
            $method->setParameter(new \Zend\Code\Generator\ParameterGenerator('cond', $localTableNameAsCamelCase . 'Cond', $nullValue));
            // Только прямая связь
            if (($link->getLinkType() == AbstractLink::LINK_TYPE_MANY_TO_ONE || $link->getLinkType() == AbstractLink::LINK_TYPE_ONE_TO_ONE) && !$link->getLinkTable() && $link->isDirect()) {
                $method->setBody(<<<EOS
\$cond = \$this->prepareCond(\$cond);

\${$foreignTableNameAsVar}Ids = {$foreignTableNameAsCamelCase}Model::getInstance()->getIdsFromMixed(\${$foreignEntityNameAsVar});

if (!\${$foreignTableNameAsVar}Ids) {
    return \$cond->getEmptySelectResult();
}

\$cond->where(array('`{$localTableName}`.`{$localColumnName}`' => \${$foreignTableNameAsVar}Ids));

return \$this->get(\$cond);
EOS
);
            } elseif (($link->getLinkType() == AbstractLink::LINK_TYPE_ONE_TO_ONE || $link->getLinkType() == AbstractLink::LINK_TYPE_ONE_TO_MANY) && !$link->getLinkTable()) {
                if ($localColumnName == $foreignColumnName && $link->getLinkType() == AbstractLink::LINK_TYPE_ONE_TO_ONE) {
                    $method->setBody(<<<EOS
\$cond = \$this->prepareCond(\$cond);

\${$localEntityNameAsVar}Ids = \$this->getIdsFromMixed(\${$foreignTableNameAsVar});

if (!\${$localEntityNameAsVar}Ids) {
    return \$cond->getEmptySelectResult();
}

\$cond->where(array('`{$localTableName}`.`{$localColumnName}`' => \${$localEntityNameAsVar}Ids));

return \$this->get(\$cond);
EOS
);
                } else {
                    $method->setBody(<<<EOS
\$cond = \$this->prepareCond(\$cond);

\${$foreignTableNameAsVar}CollectionCond = {$foreignTableNameAsCamelCase}Cond::init()->columns(array('id', '{$foreignColumnName}'));
/** @var {$foreignTableNameAsCamelCase}Collection|{$foreignTableNameAsCamelCase}Entity[] \${$foreignTableNameAsCamelCase}Collection */
\${$foreignTableNameAsVar}Collection = {$foreignTableNameAsCamelCase}Model::getInstance()->getCollectionById(\${$foreignEntityNameAsVar}, \${$foreignTableNameAsVar}CollectionCond);

\${$localEntityNameAsVar}Ids = array();
foreach (\${$foreignTableNameAsVar}Collection as \${$foreignTableNameAsVar}) {
    \${$localEntityNameAsVar}Ids[] = \${$foreignTableNameAsVar}->get{$localEntityNameAsCamelCase}Id();
}
\${$localEntityNameAsVar}Ids = \$this->getIdsFromMixed(\${$localEntityNameAsVar}Ids);

if (!\${$localEntityNameAsVar}Ids) {
    return \$cond->getEmptySelectResult();
}

\$cond->where(array('`{$localTableName}`.`{$localColumnName}`' => \${$localEntityNameAsVar}Ids));

return \$this->get(\$cond);
EOS
);
                    $file->addUse('\\Model\\Cond\\' . $foreignTableNameAsCamelCase . 'Cond');
                }
            } elseif ($link->getLinkTable()) {
                $method->setBody(<<<EOS
\$cond = \$this->prepareCond(\$cond);

\${$foreignTableNameAsVar}Ids = {$foreignTableNameAsCamelCase}Model::getInstance()->getIdsFromMixed(\${$foreignEntityNameAsVar});

if (!\${$foreignTableNameAsVar}Ids) {
    return \$cond->getEmptySelectResult();
}

\$cond->joinRule('join_link_table_{$linkTableName}', Cond::JOIN_INNER, '`{$linkTableName}`', '`{$linkTableName}`.`{$linkTableLocalColumnName}` = `{$localTableName}`.`{$localColumnName}`');
\$cond->where(array('`{$linkTableName}`.`{$linkTableForeignColumnName}`' => \${$foreignTableNameAsVar}Ids));

return \$this->execute(\$cond);
EOS
);
            } else {
                throw new ErrorException('Unknown getter');
            }
            try {
                $part->getFile()->getClass()->addMethodFromGenerator($method);
            } catch (\Exception $e) {
            }
        }
    }
    /**
     * @param ClassGenerator $generator
     * @param State          $state
     */
    public function addGetObject(ClassGenerator $generator, State $state)
    {
        $className = $state->getServiceModel()->getClassName();
        $doc = "@param array \$methods\n@return \\PHPUnit_Framework_MockObject_MockObject|" . $className;
        $class = $state->getServiceModel()->getName();
        $repository = ucfirst($state->getRepositoryModel()->getClassName());
        $body = <<<EOF
if (count(\$methods)) {
    \$object = \$this->getMockBuilder('{$class}')
        ->disableOriginalConstructor()
        ->setMethods(\$methods)
        ->getMock();
} else {
    \$object = new {$className}(\$this->getServiceManager());
}

\$object->set{$repository}(\$this->getRepository());
\$object->setEntityManager(\$this->getEntityManager());

return \$object;
EOF;
        $method = new MethodGenerator('getObject', [], MethodGenerator::FLAG_PUBLIC, $body, $doc);
        $method->setParameter(new ParameterGenerator('methods', 'array', []));
        $generator->addMethodFromGenerator($method);
    }
Example #16
0
 /**
  * Generate method
  *
  * @param string $methodName
  * @return void
  */
 protected function generateMethod($methodName)
 {
     $methodReflection = $this->_method[$methodName];
     $docBlock = new DocBlockGenerator();
     $docBlock->setShortDescription("Delicate {$methodName}() to __call() method ");
     if ($methodReflection->getDocComment()) {
         $docBlockReflection = new DocBlockReflection($methodReflection);
         $docBlock->fromReflection($docBlockReflection);
     }
     $method = new MethodGenerator();
     $method->setName($methodName);
     $method->setDocBlock($docBlock);
     $method->setBody(sprintf(self::METHOD_TEMPLATE, $methodName));
     if ($methodReflection->isPublic()) {
         $method->setVisibility(MethodGenerator::VISIBILITY_PUBLIC);
     } else {
         if ($methodReflection->isProtected()) {
             $method->setVisibility(MethodGenerator::VISIBILITY_PROTECTED);
         } else {
             if ($methodReflection->isPrivate()) {
                 $method->setVisibility(MethodGenerator::VISIBILITY_PRIVATE);
             }
         }
     }
     foreach ($methodReflection->getParameters() as $parameter) {
         $parameterGenerator = new ParameterGenerator();
         $parameterGenerator->setPosition($parameter->getPosition());
         $parameterGenerator->setName($parameter->getName());
         $parameterGenerator->setPassedByReference($parameter->isPassedByReference());
         if ($parameter->isDefaultValueAvailable()) {
             $parameterGenerator->setDefaultValue($parameter->getDefaultValue());
         }
         if ($parameter->isArray()) {
             $parameterGenerator->setType('array');
         }
         if ($typeClass = $parameter->getClass()) {
             $parameterGenerator->setType($typeClass->getName());
         }
         $method->setParameter($parameterGenerator);
     }
     $this->addMethodFromGenerator($method);
 }
 /**
  * generates method initFilters for grid
  *
  * @param \Zend\Code\Generator\ClassGenerator $class
  * @param DataSetDescriptorInterface $dataSet
  */
 protected function generateInitFiltersMehod(ClassGenerator $class, DataSetDescriptorInterface $dataSet)
 {
     $body = "";
     foreach ($dataSet->listGenerator() as $column) {
         $name = $column->getName();
         $type = $this->getFieldType($column);
         $body .= sprintf($this->codeLibrary()->get('grid.initFilters.' . $type), $name, $name);
     }
     $method = new MethodGenerator("initFilters");
     $method->setBody($body);
     $method->setFlags(\Zend\Code\Generator\MethodGenerator::FLAG_PROTECTED);
     $parameter = new \Zend\Code\Generator\ParameterGenerator("query");
     $parameter->setType("\\Zend\\Db\\Sql\\Select");
     $method->setParameter($parameter);
     $class->addMethodFromGenerator($method);
 }
 /**
  * Entity Generator
  * @return JsonModel
  */
 public function entityAction()
 {
     $isOK = $this->checkValidate();
     if ($isOK !== true) {
         return $isOK;
     }
     $tblName = $this->params()->fromPost('tbl_name', '');
     $module = $this->params()->fromPost('module', '');
     $module = empty($module) ? 'Application' : $module;
     $toCamelCase = new UnderscoreToCamelCase();
     $className = $toCamelCase->filter(substr($tblName, 4));
     $nameSpace = $module . '\\Entity';
     $class = $this->initClass($className, $nameSpace);
     $class->addUse('Zend\\Stdlib\\ArraySerializableInterface');
     $class->setImplementedInterfaces(array('ArraySerializableInterface'));
     $columns = $this->getDbMeta()->getColumnNames($tblName);
     $exchangeBody = '';
     $getArrayBody = 'return array(' . PHP_EOL;
     foreach ($columns as $col) {
         $name = $toCamelCase->filter($col);
         $property = lcfirst($name);
         $class->addProperty($property, null, PropertyGenerator::FLAG_PROTECTED);
         $get = new MethodGenerator('get' . $name);
         $get->setBody('return $this->' . $property . ';');
         $set = new MethodGenerator('set' . $name);
         $set->setParameter('value')->setBody('$this->' . $property . ' = $value;');
         $class->addMethods(array($get, $set));
         $exchangeBody .= '$this->' . $property . ' = (!empty($data[\'' . $col . '\'])) ? $data[\'' . $col . '\'] : null;' . PHP_EOL;
         $getArrayBody .= "\t'" . $col . '\' => $this->' . $property . ',' . PHP_EOL;
     }
     $exchange = new MethodGenerator('exchangeArray');
     $exchange->setParameter(array('type' => 'array', 'name' => 'data'));
     $exchange->setBody($exchangeBody);
     $getArray = new MethodGenerator('getArrayCopy');
     $getArray->setBody($getArrayBody . ');');
     $class->addMethods(array($exchange, $getArray));
     $code = '<?php' . PHP_EOL . $class->generate();
     return new JsonModel(array('status' => true, 'code' => $code));
 }
 /**
  * creates Module class
  */
 protected function createModuleClass()
 {
     $moduleClassFilePath = $this->moduleRoot() . '/Module.php';
     if (!file_exists($moduleClassFilePath)) {
         $this->console('creating Module Class');
         $moduleClassFile = new FileGenerator();
         $moduleClassFile->setNamespace($this->params->getParam('moduleName'));
         $moduleClass = new ClassGenerator();
         $moduleClass->setDocBlock($this->getFileDocBlock())->getDocBlock()->setShortDescription($this->codeLibrary()->get('module.moduleClassDescription'));
         $moduleClass->setName('Module');
         // onbootstrap
         $onBootstrapMethod = new MethodGenerator();
         $onBootstrapMethod->setName('onBootstrap')->setBody($this->codeLibrary()->get('module.onBootstrap.body'));
         $onBootstrapMethod->setDocBlock(new DocBlockGenerator($this->codeLibrary()->get('module.onBootstrap.shortdescription'), $this->codeLibrary()->get('module.onBootstrap.longdescription'), array(new ParamTag('e', '\\Zend\\Mvc\\MvcEvent'))));
         $eventParam = new ParameterGenerator('e', '\\Zend\\Mvc\\MvcEvent');
         $onBootstrapMethod->setParameter($eventParam);
         $moduleClass->addMethodFromGenerator($onBootstrapMethod);
         // config
         $configMethod = new MethodGenerator('getConfig', array(), MethodGenerator::FLAG_PUBLIC, $this->codeLibrary()->get('module.config.body'), new DocBlockGenerator($this->codeLibrary()->get('module.config.shortdescription'), $this->codeLibrary()->get('module.config.longdescription'), array()));
         $moduleClass->addMethodFromGenerator($configMethod);
         // getAutoloaderConfig
         $getAutoloaderConfigMethod = new MethodGenerator('getAutoloaderConfig', array(), MethodGenerator::FLAG_PUBLIC, $this->codeLibrary()->get('module.getAutoloaderConfig.body'), new DocBlockGenerator($this->codeLibrary()->get('module.getAutoloaderConfig.shortdescription'), $this->codeLibrary()->get('module.getAutoloaderConfig.longdescription'), array()));
         $moduleClass->addMethodFromGenerator($getAutoloaderConfigMethod);
         // adding class method and generating file
         $moduleClassFile->setClass($moduleClass);
         file_put_contents($moduleClassFilePath, $moduleClassFile->generate());
     }
 }
Example #20
0
 /**
  * get setter methods for a parameter based on type
  * @param  Generator\ClassGenerator $cg
  * @param  string                   $name        - the parameter name
  * @param  int                      $type        - The type of parameter to be handled
  * @param  string                   $targetClass - the target class name to be set (only used in relational setters)
  * @return array                    $methods
  */
 private function getSetterMethods(&$cg, $name, $type, $targetClass = null)
 {
     $methods = array();
     switch ($type) {
         case self::PARAM_TYPE_ITEM:
             $method = new Generator\MethodGenerator();
             $method->setDocBlock('@param string $' . $name);
             $method->setParameter(new ParameterGenerator($name));
             $method->setBody('$this->' . $name . ' = $' . $name . ';');
             $method->setName('set' . $this->camelCaseMethodName($name));
             $methods[] = $method;
             break;
         case self::PARAM_TYPE_RELATION_SINGLE:
             $method = new Generator\MethodGenerator();
             $method->setDocBlock('@param ' . $targetClass . ' $' . $name);
             $method->setParameter(new ParameterGenerator($name, $this->getTargetType($targetClass)));
             $method->setBody('$this->' . $name . ' = $' . $name . ';');
             $method->setName('set' . $this->camelCaseMethodName($name));
             $methods[] = $method;
             break;
         case self::PARAM_TYPE_RELATION_COLLECTION:
             $singledName = Inflector::singularize($name);
             $method = new Generator\MethodGenerator();
             $method->setDocBlock('@param ' . $targetClass . ' $' . $singledName);
             $method->setParameter(new ParameterGenerator($singledName, $this->getTargetType($targetClass)));
             $method->setBody('$this->' . $name . '[] = $' . $singledName . ';');
             $singleMethodName = 'add' . $this->camelCaseMethodName($singledName);
             $method->setName($singleMethodName);
             $methods[] = $method;
             $pluralName = Inflector::pluralize($name);
             if ($singledName === $pluralName) {
                 // Unable to generate a pluralized collection method
                 break;
             }
             $pluralMethod = new Generator\MethodGenerator();
             $pluralMethod->setDocBlock('@param array $' . $name);
             $pluralMethod->setName('add' . $this->camelCaseMethodName($pluralName));
             $pluralMethod->setParameter(new ParameterGenerator($pluralName, 'array'));
             $body = "foreach (\${$pluralName} as \${$singledName}) \n{\n";
             $body .= "    \$this->{$singleMethodName}(\${$singledName});\n}";
             $pluralMethod->setBody($body);
             $methods[] = $pluralMethod;
             break;
     }
     // All setter methods will return $this
     for ($x = 0; $x < sizeof($methods); $x++) {
         /** @var Generator\MethodGenerator $methods [$x] * */
         $docBlock = $methods[$x]->getDocBlock();
         $docBlock->setShortDescription($docBlock->getShortDescription() . "\n@return " . $cg->getName() . ' $this');
         $methods[$x]->setDocBlock($docBlock);
         $methods[$x]->setBody($methods[$x]->getBody() . "\nreturn \$this;");
     }
     return $methods;
 }
Example #21
0
 /**
  * @param \ReflectionMethod $method
  * @return MethodGenerator
  */
 private function generateMethod(\ReflectionMethod $method)
 {
     $gen = new MethodGenerator($method->getName());
     foreach ($method->getParameters() as $param) {
         $paramgen = new ParameterGenerator($param->getName(), $param->getClass() ? '\\' . $param->getClass()->name : null, null, $param->isPassedByReference());
         // setting default value here because the construtor ignores "null" as default
         if ($param->isDefaultValueAvailable()) {
             $paramgen->setDefaultValue($param->getDefaultValue());
         }
         $gen->setParameter($paramgen);
     }
     $gen->setBody('return $this->__proxy_run(C::CALL, __FUNCTION__, func_get_args());');
     return $gen;
 }
 /**
  * creates setter method for given field
  *
  * @param FieldDescriptorInterface $column
  * @param string $name
  * @return \Zend\Code\Generator\MethodGenerator
  */
 protected function createSetMethod(FieldDescriptorInterface $column, $name)
 {
     $propertyName = lcfirst($name);
     $parameter = new \Zend\Code\Generator\ParameterGenerator();
     $parameter->setName("value");
     $method = new MethodGenerator();
     $method->setParameter($parameter);
     $type = $this->getFieldType($column);
     $method->setBody(sprintf($this->codeLibrary()->get('model.setMethod' . ucfirst($type) . '.body'), $propertyName));
     $method->setName("set" . $name);
     $docblock = new \Zend\Code\Generator\DocblockGenerator(sprintf($this->codeLibrary()->get('model.setMethod.description'), $propertyName));
     $docblock->setTag(array("name" => "param", "description" => $type));
     $method->setDocBlock($docblock);
     return $method;
 }
 /**
  * Add form setter
  *
  * @param $formClass
  */
 protected function addFormSetter($formClass)
 {
     $formParam = lcfirst($formClass);
     $body = '$this->' . $formParam . ' = $' . $formParam . ';';
     $parameter = new ParameterGenerator($formParam, $formClass);
     $setMethodName = 'set' . $formClass;
     $setMethod = new MethodGenerator($setMethodName);
     $setMethod->addFlag(MethodGenerator::FLAG_PUBLIC);
     $setMethod->setParameter($parameter);
     $setMethod->setDocBlock(new DocBlockGenerator('Set ' . $formClass, null, [['name' => 'param', 'description' => $formClass . ' $' . $formParam]]));
     $setMethod->setBody($body);
     $this->addMethodFromGenerator($setMethod);
 }
 public function getConstructorGenerator()
 {
     if (!$this->constructorGenerator && ($extendedClass = $this->getClassGenerator()->getExtendedClass())) {
         $constructorGenerator = new CodeGenerator\MethodGenerator();
         $constructorGenerator->setName('__construct');
         $wsdlParameter = new CodeGenerator\ParameterGenerator();
         $wsdlParameter->setName('wsdl');
         $wsdlParameter->setDefaultValue($this->getWsdl());
         $constructorGenerator->setParameter($wsdlParameter);
         $optionsParameter = new CodeGenerator\ParameterGenerator();
         $optionsParameter->setName('options');
         $optionsParameter->setDefaultValue(array());
         $constructorGenerator->setParameter($optionsParameter);
         $constructorGenerator->setBody("parent::__construct(\$wsdl, \$options);");
         $this->constructorGenerator = $constructorGenerator;
     }
     return $this->constructorGenerator;
 }
Example #25
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);
 }
 /**
  * Add a selectWith() method if table has an external dependency
  *
  * @return MethodGenerator
  */
 protected function addSelectWithMethod()
 {
     /** @var TableObject $currentTable */
     $currentTable = $this->tableObjects[$this->tableName];
     $foreignKeys = array();
     /** @var $tableConstraint ConstraintObject */
     foreach ($currentTable->getConstraints() as $tableConstraint) {
         if (!$tableConstraint->isForeignKey()) {
             continue;
         }
         $foreignKeys[] = $tableConstraint;
     }
     if (empty($foreignKeys)) {
         return true;
     }
     $body = array();
     /** @var ConstraintObject $foreignKey */
     foreach ($foreignKeys as $foreignKey) {
         $refTableName = $foreignKey->getReferencedTableName();
         /** @var TableObject $refTableObject */
         $refTableObject = $this->tableObjects[$refTableName];
         $body[] = '$select->join(';
         $body[] = '    \'' . $refTableName . '\',';
         $body[] = '    \'' . $this->tableName . '.' . $foreignKey->getColumns()[0] . ' = ' . $refTableName . '.' . $foreignKey->getReferencedColumns()[0] . '\',';
         $body[] = '    array(';
         /** @var ColumnObject $column */
         foreach ($refTableObject->getColumns() as $column) {
             $body[] = '        \'' . $refTableName . '.' . $column->getName() . '\' => \'' . $column->getName() . '\',';
         }
         $body[] = '    )';
         $body[] = ');';
         $body[] = '';
     }
     $body[] = 'return parent::selectWith($select);';
     $body = implode(AbstractGenerator::LINE_FEED, $body);
     $this->addUse('Zend\\Db\\ResultSet\\ResultSetInterface');
     $this->addUse('Zend\\Db\\Sql\\Select');
     $selectMethod = new MethodGenerator('selectWith');
     $selectMethod->addFlag(MethodGenerator::FLAG_PUBLIC);
     $selectMethod->setParameter(new ParameterGenerator('select', 'Select'));
     $selectMethod->setDocBlock(new DocBlockGenerator('Add join tables', null, array(array('name' => 'param', 'description' => 'Select $select'), array('name' => 'return', 'description' => 'ResultSetInterface'))));
     $selectMethod->setBody($body);
     $this->addMethodFromGenerator($selectMethod);
     return true;
 }
Example #27
0
    /**
     * @group ZF-7268
     */
    public function testDefaultValueGenerationDoesNotIncludeTrailingSemicolon()
    {
        $method = new MethodGenerator('setOptions');
        $default = new ValueGenerator();
        $default->setValue(array());

        $param   = new ParameterGenerator('options', 'array');
        $param->setDefaultValue($default);

        $method->setParameter($param);
        $generated = $method->generate();
        $this->assertRegexp('/array \$options = array\(\)\)/', $generated, $generated);
    }
Example #28
0
 private function handleAdder(Generator\ClassGenerator $generator, PHPProperty $prop, PHPClass $class)
 {
     $type = $prop->getType();
     $propName = $type->getArg()->getName();
     $docblock = new DocBlockGenerator();
     $docblock->setShortDescription("Adds as {$propName}");
     if ($prop->getDoc()) {
         $docblock->setLongDescription($prop->getDoc());
     }
     $return = new ReturnTag();
     $return->setTypes("self");
     $docblock->setTag($return);
     $patramTag = new ParamTag($propName, $this->getPhpType($type->getArg()->getType()));
     $docblock->setTag($patramTag);
     $method = new MethodGenerator("addTo" . Inflector::classify($prop->getName()));
     $parameter = new ParameterGenerator($propName);
     $tt = $type->getArg()->getType();
     if (!$this->isNativeType($tt)) {
         if ($p = $this->isOneType($tt)) {
             if ($t = $p->getType()) {
                 $patramTag->setTypes($this->getPhpType($t));
                 if (!$this->isNativeType($t)) {
                     $parameter->setType($this->getPhpType($t));
                 }
             }
         } elseif (!$this->isNativeType($tt)) {
             $parameter->setType($this->getPhpType($tt));
         }
     }
     $methodBody = "\$this->" . $prop->getName() . "[] = \$" . $propName . ";" . PHP_EOL;
     $methodBody .= "return \$this;";
     $method->setBody($methodBody);
     $method->setDocBlock($docblock);
     $method->setParameter($parameter);
     $generator->addMethodFromGenerator($method);
 }
 /**
  * Add a selectWith() method if table has an external dependency
  *
  * @return MethodGenerator
  */
 protected function addSelectWithMethod()
 {
     $foreignKeys = $this->loadedTables[$this->tableName]['foreignKeys'];
     if (empty($foreignKeys)) {
         return true;
     }
     $body = [];
     /** @var ConstraintObject $foreignKey */
     foreach ($foreignKeys as $foreignKey) {
         $refTableName = $foreignKey->getReferencedTableName();
         $refTableColumns = $this->loadedTables[$refTableName]['columns'];
         $body[] = '$select->join(';
         $body[] = '    \'' . $refTableName . '\',';
         $body[] = '    \'' . $this->tableName . '.' . $foreignKey->getColumns()[0] . ' = ' . $refTableName . '.' . $foreignKey->getReferencedColumns()[0] . '\',';
         $body[] = '    [';
         /** @var ColumnObject $column */
         foreach ($refTableColumns as $column) {
             $body[] = '        \'' . $refTableName . '.' . $column->getName() . '\' => \'' . $column->getName() . '\',';
         }
         $body[] = '    ]';
         $body[] = ');';
         $body[] = '';
     }
     $body[] = 'return parent::selectWith($select);';
     $body = implode(AbstractGenerator::LINE_FEED, $body);
     $this->addUse('Zend\\Db\\ResultSet\\ResultSetInterface');
     $this->addUse('Zend\\Db\\Sql\\Select');
     $selectMethod = new MethodGenerator('selectWith');
     $selectMethod->addFlag(MethodGenerator::FLAG_PUBLIC);
     $selectMethod->setParameter(new ParameterGenerator('select', 'Select'));
     $selectMethod->setDocBlock(new DocBlockGenerator('Add join tables', null, [['name' => 'param', 'description' => 'Select $select'], ['name' => 'return', 'description' => 'ResultSetInterface']]));
     $selectMethod->setBody($body);
     $this->addMethodFromGenerator($selectMethod);
     return true;
 }
Example #30
0
 protected function getFactoryMethod(\ReflectionMethod $method, $classConfig)
 {
     $factoryMethod = new Generator\MethodGenerator($this->dic->getFactoryMethodName($method->name));
     $factoryMethod->setParameter(new Generator\ParameterGenerator('object'));
     $factoryMethod->setStatic(true);
     $arguments = $method->getParameters();
     $body = '$i = 0;' . PHP_EOL;
     $methodArgumentStringParts = array();
     if (count($arguments) > 0) {
         $factoryMethod->setParameter(new \Zend\Code\Generator\ParameterGenerator('parameters', 'array', array()));
         foreach ($arguments as $argument) {
             /** @var \ReflectionParameter $argument */
             $argumentName = $argument->name;
             $methodArgumentStringParts[] = '$' . $argumentName;
         }
         $body .= 'if (!$parameters) {' . PHP_EOL;
         foreach ($arguments as $argument) {
             /** @var \ReflectionParameter $argument */
             $injectionParameter = new \rg\injektor\generators\InjectionParameter($argument, $classConfig, $this->config, $this->dic, InjectionParameter::MODE_NO_ARGUMENTS);
             try {
                 if ($injectionParameter->getClassName()) {
                     $this->factoryGenerator->processFileForClass($injectionParameter->getClassName());
                 }
                 if ($injectionParameter->getFactoryName()) {
                     $this->usedFactories[] = $injectionParameter->getFactoryName();
                 }
                 $body .= '    ' . $injectionParameter->getProcessingBody();
             } catch (\Exception $e) {
                 $body .= '    ' . $injectionParameter->getDefaultProcessingBody();
             }
         }
         $body .= '}' . PHP_EOL;
         $body .= 'else if (array_key_exists(0, $parameters)) {' . PHP_EOL;
         foreach ($arguments as $argument) {
             /** @var \ReflectionParameter $argument */
             $injectionParameter = new \rg\injektor\generators\InjectionParameter($argument, $classConfig, $this->config, $this->dic, InjectionParameter::MODE_NUMERIC);
             try {
                 if ($injectionParameter->getClassName()) {
                     $this->factoryGenerator->processFileForClass($injectionParameter->getClassName());
                 }
                 if ($injectionParameter->getFactoryName()) {
                     $this->usedFactories[] = $injectionParameter->getFactoryName();
                 }
                 $body .= '    ' . $injectionParameter->getProcessingBody();
             } catch (\Exception $e) {
                 $body .= '    ' . $injectionParameter->getDefaultProcessingBody();
             }
         }
         $body .= '}' . PHP_EOL;
         $body .= 'else {' . PHP_EOL;
         foreach ($arguments as $argument) {
             /** @var \ReflectionParameter $argument */
             $injectionParameter = new \rg\injektor\generators\InjectionParameter($argument, $classConfig, $this->config, $this->dic, InjectionParameter::MODE_STRING);
             try {
                 if ($injectionParameter->getClassName()) {
                     $this->factoryGenerator->processFileForClass($injectionParameter->getClassName());
                 }
                 if ($injectionParameter->getFactoryName()) {
                     $this->usedFactories[] = $injectionParameter->getFactoryName();
                 }
                 $body .= '    ' . $injectionParameter->getProcessingBody();
             } catch (\Exception $e) {
                 $body .= '    ' . $injectionParameter->getDefaultProcessingBody();
             }
         }
         $body .= '}' . PHP_EOL;
     }
     $body .= '$result = $object->' . $method->name . '(' . implode(', ', $methodArgumentStringParts) . ');' . PHP_EOL . PHP_EOL;
     $body .= PHP_EOL . 'return $result;';
     $factoryMethod->setBody($body);
     return $factoryMethod;
 }