Ejemplo n.º 1
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.º 2
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.º 3
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.º 4
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.º 5
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.º 6
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.º 7
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);
    }
Ejemplo n.º 8
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.º 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();
 }
Ejemplo n.º 10
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);
 }
Ejemplo n.º 11
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;
    }
Ejemplo n.º 12
0
    public function generateMethodsByLink($part)
    {
        /** @var $part \Model\Generator\Part\Model */
        /** @var $file \Model\Code\Generator\FileGenerator */
        $file = $part->getFile();
        $table = $part->getTable();
        $tableNameAsCamelCase = $part->getTable()->getNameAsCamelCase();
        $indexList = $table->getIndex();
        /*        $userStat = $part->getTable()->getSchema()->getTable('user');
                $indexList = $userStat->getIndex();
                foreach ($indexList as $index) {
                    print_r($index->toArray());
                    $column = reset($index);
                    if ($index->count() > 1 || !($link = $table->getLinkByColumn($column))) {
        
                    }
                }
                die;*/
        $methods = array();
        foreach ($indexList as $index) {
            if ($index->getName() == 'PRIMARY') {
                continue;
            }
            $column = reset($index);
            if ($index->count() > 1 || !($link = $table->getLinkByColumn($column, $table->getName()))) {
                continue;
            }
            if ($link->getLocalTable() == $table->getName()) {
                $direct = true;
            } else {
                $direct = false;
            }
            $columnAsCamelCase = $link->getForeignTable()->getnameAsCamelCase();
            $columnAsVar = $link->getForeignTable()->getnameAsVar();
            $columnName = $link->getForeignTable()->getName();
            $localColumnName = $link->getLocalColumn()->getName();
            $localTableName = $link->getLocalTable()->getName();
            $type = "{$columnAsCamelCase}Entity|{$columnAsCamelCase}Collection|array|string|integer";
            $file->addUse('\\Model\\Entity\\' . $columnAsCamelCase . 'Entity');
            $file->addUse('\\Model\\Collection\\' . $columnAsCamelCase . 'Collection');
            $tags[] = array('name' => 'param', 'description' => "{$type} \$" . $columnAsVar);
            $params[] = new \Zend\Code\Generator\ParameterGenerator($columnAsVar);
            $docblock = new DocBlockGenerator('Получить один элемен по ');
            $docblock->setTags($tags);
            $method = new \Zend\Code\Generator\MethodGenerator();
            $method->setName('getBy' . $columnAsCamelCase);
            $method->setParameters($params);
            $method->setVisibility(\Zend\Code\Generator\AbstractMemberGenerator::VISIBILITY_PUBLIC);
            $method->setStatic(true);
            $method->setDocBlock($docblock);
            //            print_r($link->toArray());z
            if (($link->getLinkType() == AbstractLink::LINK_TYPE_ONE_TO_ONE || $link->getLinkType() == AbstractLink::LINK_TYPE_MANY_TO_ONE) && $direct) {
                $method->setBody(<<<EOS
\$cond = \$this->prepareCond(\$cond);

\${$columnAsVar}Ids = {$columnAsCamelCase}Model::getInstance()->getIdsFromMixed(\${$columnAsVar});

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

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

return \$this->get(\$cond);
EOS
);
            } elseif (($link->getLinkType() == AbstractLink::LINK_TYPE_ONE_TO_ONE || $link->getLinkType() == AbstractLink::LINK_TYPE_MANY_TO_ONE) && !$direct) {
                $localTableName = $link->getLocalTable()->getName();
                $localColumnName = $link->getLocalColumn()->getName();
                $localTableNameAsVar = $link->getLocalTable()->getNameAsVar();
                $localTableNameAsCamelCase = $link->getLocalTable()->getNameAsCamelCase();
                $method->setBody(<<<EOS
\$cond = \$this->prepareCond(\$cond);

\${$columnAsVar}Collection = {$columnAsCamelCase}Model::getInstance()->getCollectionBy{$columnAsCamelCase}(\${$columnAsVar});

\${$localTableNameAsVar}Ids = array();
foreach (\${$columnAsVar}Collection as \${$columnAsVar}) {
    \${$localTableNameAsVar}Ids[] = \${$columnAsVar}->get{$localTableNameAsCamelCase}Id();
}
\${$localTableNameAsVar}Ids = \$this->getIdsFromMixed(\${$localTableNameAsVar}Ids);

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

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

return \$this->get(\$cond);
EOS
);
            } elseif ($link->getLinkType() == AbstractLink::LINK_TYPE_MANY_TO_MANY) {
                die('ok');
            }
            $methods[] = $method;
        }
        return $methods;
    }
Ejemplo n.º 13
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);
     $linkList = $table->getLink();
     /*if ($table->getColumn('parent_id')) {
                 echo $table->getName();
     
                 print_r($linkList);
                 die;
             }*/
     $relation = array();
     foreach ($linkList as $link) {
         $linkLocalColumnName = $link->getLocalColumn()->getName();
         if ($link->getForeignTable() == $link->getLocalTable() && $link->getLocalColumn() == $link->getForeignColumn()) {
             continue;
         }
         $foreignAliasName = $link->getForeignEntity();
         $rel = $link->toArray();
         unset($rel['name']);
         switch ($link->getLinkType()) {
             case AbstractLink::LINK_TYPE_ONE_TO_ONE:
                 $rel['type'] = new ValueGenerator('AbstractModel::ONE_TO_ONE', ValueGenerator::TYPE_CONSTANT);
                 break;
             case AbstractLink::LINK_TYPE_ONE_TO_MANY:
                 $rel['type'] = new ValueGenerator('AbstractModel::ONE_TO_MANY', ValueGenerator::TYPE_CONSTANT);
                 break;
             case AbstractLink::LINK_TYPE_MANY_TO_ONE:
                 $rel['type'] = new ValueGenerator('AbstractModel::MANY_TO_ONE', ValueGenerator::TYPE_CONSTANT);
                 break;
             case AbstractLink::LINK_TYPE_MANY_TO_MANY:
                 $rel['type'] = new ValueGenerator('AbstractModel::MANY_TO_MANY', ValueGenerator::TYPE_CONSTANT);
                 break;
         }
         if ($link->getLocalColumn()->getName() != 'id' && !$link->getLinkTable() || $link->getLocalColumn()->getName() == 'id' && !$link->getLinkTable() && !$link->getLocalColumn()->isAutoincrement()) {
             $rel['required_link'] = !$link->getLocalColumn()->isNullable();
             $rel['link_method'] = 'link' . $link->getLocalEntityAsCamelCase() . 'To' . $link->getForeignEntityAsCamelCase();
             $rel['unlink_method'] = 'deleteLink' . $link->getLocalEntityAsCamelCase() . 'To' . $link->getForeignEntityAsCamelCase();
         } else {
             if ($table->getName() == 'tag') {
                 if ($link->getLocalEntityAlias() != $link->getLocalTable()->getName()) {
                     $foreignAliasName .= '_as_' . $link->getLocalEntityAlias();
                 }
             }
             $rel['required_link'] = false;
             $rel['link_method'] = 'link' . $link->getLocalEntityAsCamelCase() . 'To' . $link->getForeignEntityAsCamelCase();
             $rel['unlink_method'] = 'deleteLink' . $link->getLocalEntityAsCamelCase() . 'To' . $link->getForeignEntityAsCamelCase();
         }
         $rel['local_entity'] = $link->getLocalEntity();
         $rel['foreign_entity'] = $link->getForeignEntity();
         $relation[$foreignAliasName] = $rel;
         $relation[$foreignAliasName]['foreign_model'] = '\\Model\\' . $link->getForeignTable()->getNameAsCamelCase() . 'Model';
     }
     $property = new PropertyGenerator('relation', $relation, PropertyGenerator::FLAG_PROTECTED);
     //$property->setDocBlock($docblock);
     $method = new MethodGenerator();
     $method->setName('initRelation');
     $method->setFinal(true);
     $method->setVisibility(AbstractMemberGenerator::VISIBILITY_PROTECTED);
     $body = preg_replace("#^(\\s*)protected #", "\\1", $property->generate()) . "\n";
     $body .= "\$this->setRelation(\$relation); \n";
     $body .= "\$this->setupRelation();";
     $docblock = new DocBlockGenerator('Настройка связей');
     $method->setDocBlock($docblock);
     $method->setBody($body);
     //$file->getClass()->addPropertyFromGenerator($property);
     $file->getClass()->addMethodFromGenerator($method);
 }
Ejemplo n.º 14
0
    private function buildProxyClass(string $entityInterfaceName, string $proxyNamespace, string $proxyClassName) : string
    {
        $reflectionClass = new ReflectionClass($entityInterfaceName);
        if (!$reflectionClass->isInterface()) {
            throw InvalidInterfaceException::fromInvalidInterface($entityInterfaceName);
        }
        $classGenerator = new ClassGenerator();
        $classGenerator->setNamespaceName($proxyNamespace);
        $classGenerator->setName($proxyClassName);
        $classGenerator->setImplementedInterfaces([$entityInterfaceName, ProxyInterface::class]);
        $classGenerator->addProperty('initializer', null, PropertyGenerator::FLAG_PRIVATE);
        $classGenerator->addProperty('relationId', null, PropertyGenerator::FLAG_PRIVATE);
        $classGenerator->addProperty('realEntity', null, PropertyGenerator::FLAG_PRIVATE);
        $constructorGenerator = new MethodGenerator('__construct', [['name' => 'initializer', 'type' => 'callable'], ['name' => 'relationId']]);
        $constructorGenerator->setBody('
            $this->initializer = $initializer;
            $this->relationId = $relationId;
        ');
        $classGenerator->addMethodFromGenerator($constructorGenerator);
        $getRelationIdGenerator = new MethodGenerator('__getRelationId');
        $getRelationIdGenerator->setBody('
            return $this->relationId;
        ');
        $classGenerator->addMethodFromGenerator($getRelationIdGenerator);
        $getRealEntityGenerator = new MethodGenerator('__getRealEntity');
        $getRealEntityGenerator->setBody('
            if (null === $this->realEntity) {
                $this->realEntity = ($this->initializer)();
                \\Assert\\Assertion::isInstanceOf($this->realEntity, \\' . $entityInterfaceName . '::class);
            };

            return $this->realEntity;
        ');
        $classGenerator->addMethodFromGenerator($getRealEntityGenerator);
        foreach ($reflectionClass->getMethods(ReflectionMethod::IS_PUBLIC) as $reflectionMethod) {
            $parameters = [];
            $parameterGenerators = [];
            $returnType = $reflectionMethod->getReturnType();
            foreach ($reflectionMethod->getParameters() as $reflectionParameter) {
                $parameterGenerator = new ParameterGenerator($reflectionParameter->getName(), $reflectionParameter->getType(), $reflectionParameter->isDefaultValueAvailable() ? $reflectionParameter->getDefaultValue() : null);
                $parameterGenerator->setVariadic($reflectionParameter->isVariadic());
                $parameterGenerators[] = $parameterGenerator;
                if ($reflectionParameter->isVariadic()) {
                    $parameters[] = '...$' . $reflectionParameter->getName();
                } else {
                    $parameters[] = '$' . $reflectionParameter->getName();
                }
            }
            $methodGenerator = new MethodGenerator();
            $methodGenerator->setName($reflectionMethod->getName());
            $methodGenerator->setVisibility(MethodGenerator::VISIBILITY_PUBLIC);
            $methodGenerator->setParameters($parameterGenerators);
            $methodGenerator->setReturnType($returnType);
            $body = '
                if (null === $this->realEntity) {
                    $this->realEntity = ($this->initializer)();
                    \\Assert\\Assertion::isInstanceOf($this->realEntity, \\' . $entityInterfaceName . '::class);
                };
            ';
            if ('void' !== $returnType) {
                $body .= 'return ';
            }
            $body .= '$this->realEntity->' . $reflectionMethod->getName() . '(' . implode(', ', $parameters) . ');';
            $methodGenerator->setBody($body);
            $classGenerator->addMethodFromGenerator($methodGenerator);
        }
        $fileGenerator = new FileGenerator();
        $fileGenerator->setClass($classGenerator);
        $filename = null === $this->proxyFolder ? tempnam(sys_get_temp_dir(), $proxyClassName) : sprintf('%s/%s.php', $this->proxyFolder, $proxyClassName);
        $fileGenerator->setFilename($filename);
        $fileGenerator->write();
        return $filename;
    }
Ejemplo n.º 15
0
    public function postRun(PartInterface $part)
    {
        /**
         * @var $part \Model\Generator\Part\Entity
         */
        /**
         * @var $file \Model\Code\Generator\FileGenerator
         */
        $file = $part->getFile();
        $file->addUse('Model\\Filter\\Filter');
        $columnCollection = $part->getTable()->getColumn();
        $template = '';
        /** @var $column Column */
        foreach ($columnCollection as $column) {
            $name = $column->getName();
            if ($columnConfig = $part->getColumntConfig($column)) {
                if ($columnConfig && isset($columnConfig['filters'])) {
                    foreach ($columnConfig['filters'] as $filter) {
                        $filterParams = isset($validator['params']) ? $this->varExportMin($validator['params'], true) : null;
                        if ($filterParams && $filterParams != 'NULL') {
                            $template .= "\$this->addFilterRule('{$name}', Filter::getFilterInstance('{$filter['name']}', {$filterParams}));\n";
                        } else {
                            $template .= "\$this->addFilterRule('{$name}', Filter::getFilterInstance('{$filter['name']}'));\n";
                        }
                    }
                }
            }
            /*
                        $filterArray = $column->getFilter();
            
                        foreach ($filterArray as $filter) {
                            if (empty($filter['params'])) {
                                $template .= "\$this->addFilterRule('$name', Filter::getFilterInstance('{$filter['name']}'));\n";
                            } else {
                                $filterParams = $this->varExportMin($filter['params'], true);
                                $template .= "\$this->addFilterRule('$name', Filter::getFilterInstance('{$filter['name']}', {$filterParams}));\n";
                            }
                        }
            */
            if ($column->isNullable()) {
                $template .= "\$this->addFilterRule('{$name}', Filter::getFilterInstance('\\Model\\Filter\\Null'));\n";
            }
        }
        //$tableNameAsCamelCase = $part->getTable()->getNameAsCamelCase();
        $tags = array(array('name' => 'return', 'description' => 'array Model массив с фильтрами по полям'));
        $docblock = new DocBlockGenerator('Получить правила для фильтрации ');
        $docblock->setTags($tags);
        $method = new MethodGenerator();
        $method->setName('initFilterRules');
        $method->setVisibility(AbstractMemberGenerator::VISIBILITY_PUBLIC);
        $method->setStatic(false);
        $method->setFinal(true);
        $method->setDocBlock($docblock);
        $method->setBody(<<<EOS
{$template}
\$this->setupFilterRules();
return \$this->getFilterRules();
EOS
);
        $file->getClass()->addMethodFromGenerator($method);
    }