Exemple #1
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();
        $tableNameAsCamelCase = $table->getNameAsCamelCase();
        $tags = array(array('name' => 'see', 'description' => 'parent::setupDefaultEntityType()'));
        $docblock = new \Zend\Code\Generator\DocBlockGenerator('Устанавливаем тип entity по-умолчанию');
        $docblock->setTags($tags);
        $method = new \Zend\Code\Generator\MethodGenerator();
        $method->setName('setupDefaultEntityType');
        $method->setVisibility(\Zend\Code\Generator\AbstractMemberGenerator::VISIBILITY_PROTECTED);
        $method->setDocBlock($docblock);
        $method->setBody(<<<EOS
\$this->defaultEntityType = '\\Model\\Entity\\{$tableNameAsCamelCase}Entity';
EOS
);
        $file->getClass()->addMethodFromGenerator($method);
    }
Exemple #2
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();
        $tableNameAsVar = $part->getTable()->getNameAsVar();
        //$tableComment = $part->getTable()->getComment();
        $tags = array(array('name' => 'param', 'description' => 'array|' . $tableNameAsCamelCase . 'Model $' . $tableNameAsVar), array('name' => 'return', 'description' => '\\Model\\Entity\\' . $tableNameAsCamelCase));
        $docblock = new \Zend\Code\Generator\DocBlockGenerator('Добавить ' . $tableNameAsCamelCase);
        $docblock->setTags($tags);
        $method = new \Zend\Code\Generator\MethodGenerator();
        $method->setName('add' . $tableNameAsCamelCase);
        $method->setParameter(new \Zend\Code\Generator\ParameterGenerator($tableNameAsVar, 'mixed'));
        $method->setVisibility(\Zend\Code\Generator\AbstractMemberGenerator::VISIBILITY_PUBLIC);
        $method->setDocBlock($docblock);
        $method->setBody(<<<EOS
\${$tableNameAsVar}Id = null;
\$result = ModelResult();
\${$tableNameAsVar} = new \${$tableNameAsVar}Entity(\${$tableNameAsVar});
\${$tableNameAsVar}Data = \${$tableNameAsVar}->toArray();

// Фильтруем входные данные
\${$tableNameAsVar}Data = \$this->addFilter(\${$tableNameAsVar}Data);

// Валидируем данные
\$validator = \$this->addValidate(\${$tableNameAsVar}Data);
EOS
);
        $file->getClass()->addMethodFromGenerator($method);
    }
Exemple #3
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();
        $tableNameAsCamelCase = $part->getTable()->getNameAsCamelCase();
        $tags = array(array('name' => 'return', 'description' => 'void'));
        $docblock = new \Zend\Code\Generator\DocBlockGenerator('Настраиваем текущую сущность');
        $docblock->setTags($tags);
        $method = new \Zend\Code\Generator\MethodGenerator();
        $method->setName('setupEntity');
        $method->setVisibility(\Zend\Code\Generator\AbstractMemberGenerator::VISIBILITY_PUBLIC);
        $method->setDocBlock($docblock);
        $method->setBody(<<<EOS
\$this->setName('{$tableName}');
\$this->setEntityName('{$tableName}');
\$this->setEntityClassName('\\Model\\Entity\\{$tableNameAsCamelCase}Entity');
\$this->setCollectionClassName('\\Model\\Collection\\{$tableNameAsCamelCase}Collection');
EOS
);
        $file->getClass()->addMethodFromGenerator($method);
    }
Exemple #4
0
 /**
  * @param \Model\Generator\Part\Model|\Model\Generator\Part\PartInterface $part
  */
 public function preRun(PartInterface $part)
 {
     /**
      * @var $file \Model\Code\Generator\FileGenerator
      */
     $file = $part->getFile();
     /** @var Table $table */
     $table = $part->getTable();
     /** @var string $tableName */
     $tableName = $table->getName();
     /** @var $linkList|Link[] \Model\Cluster\Schema\Table\Column */
     $linkList = $table->getLink();
     foreach ($linkList as $link) {
         $_name = $link->getForeignEntity();
         switch ($link->getLinkType()) {
             case AbstractLink::LINK_TYPE_ONE_TO_ONE:
             case AbstractLink::LINK_TYPE_ONE_TO_MANY:
             case AbstractLink::LINK_TYPE_MANY_TO_ONE:
             case AbstractLink::LINK_TYPE_MANY_TO_MANY:
                 $name = 'WITH_' . strtoupper($_name);
                 $property = new \Zend\Code\Generator\PropertyGenerator($name, strtolower($_name), \Zend\Code\Generator\PropertyGenerator::FLAG_CONSTANT);
                 $tags = array(array('name' => 'const'), array('name' => 'var', 'description' => 'string'));
                 $docblock = new \Zend\Code\Generator\DocBlockGenerator('WITH сущность ' . $link->getForeignColumn()->getTable()->getNameAsCamelCase());
                 $docblock->setTags($tags);
                 $property->setDocBlock($docblock);
                 self::$_data[$tableName][$name] = $property;
                 $name = 'WITH_' . strtoupper($_name) . '_COUNT';
                 $property = new \Zend\Code\Generator\PropertyGenerator($name, strtolower($_name) . '_count', \Zend\Code\Generator\PropertyGenerator::FLAG_CONSTANT);
                 $tags = array(array('name' => 'const'), array('name' => 'var', 'description' => 'string'));
                 $docblock = new \Zend\Code\Generator\DocBlockGenerator('WITH сущность ' . $link->getForeignColumn()->getTable()->getNameAsCamelCase());
                 $docblock->setTags($tags);
                 $property->setDocBlock($docblock);
                 self::$_data[$tableName][$name] = $property;
                 break;
         }
         switch ($link->getLinkType()) {
             case AbstractLink::LINK_TYPE_ONE_TO_MANY:
             case AbstractLink::LINK_TYPE_MANY_TO_MANY:
                 $name = 'WITH_' . strtoupper($_name) . "_COLLECTION";
                 $property = new \Zend\Code\Generator\PropertyGenerator($name, $_name . '_collection', \Zend\Code\Generator\PropertyGenerator::FLAG_CONSTANT);
                 $tags = array(array('name' => 'const'), array('name' => 'var', 'description' => 'string'));
                 $docblock = new \Zend\Code\Generator\DocBlockGenerator('WITH сущность коллекции ' . $link->getForeignColumn()->getTable()->getNameAsCamelCase());
                 $docblock->setTags($tags);
                 $property->setDocBlock($docblock);
                 self::$_data[$tableName][$name] = $property;
                 break;
         }
     }
 }
Exemple #5
0
    public function postRun(PartInterface $part)
    {
        /**
         * @var $part \Model\Generator\Part\Entity
         */
        /**
         * @var $file \Model\Code\Generator\FileGenerator
         */
        $file = $part->getFile();
        $table = $part->getTable();
        $tags = array(array('name' => '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);
    }
Exemple #6
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();
     //$tableComment = $part->getTable()->getComment();
     $tags = array(array('name' => 'version', 'description' => '$Rev:$'), array('name' => 'license', 'description' => 'MIT'), array('name' => 'author', 'description' => 'Model_Generator'), array('name' => 'author', 'description' => 'Eugene Myazin <*****@*****.**>'), array('name' => 'author', 'description' => 'Mikhail Rybalka <*****@*****.**>'), array('name' => 'author', 'description' => 'Vadim Slutsky <*****@*****.**>'), array('name' => 'author', 'description' => 'Anton Sedyshev <*****@*****.**>'));
     if ($file->getClass()->getDocblock()) {
         $file->getClass()->getDocblock()->setTags($tags);
     } else {
         $docblock = new \Zend\Code\Generator\DocBlockGenerator('Abstract collection ' . $tableNameAsCamelCase);
         $docblock->setTags($tags);
         $file->getClass()->setDocblock($docblock);
     }
 }
Exemple #7
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();
        //        $tableNameAsCamelCase = $table->getNameAsCamelCase();
        /** @var $columnList Column[]  */
        $columnList = $table->getColumn();
        foreach ($columnList as $column) {
            if ($column->getColumnType() != 'enum' || substr($column->getName(), 0, 3) == 'is_' || count($column->getEnumValuesAsArray()) < 1) {
                continue;
            }
            $columnName = $column->getName();
            foreach ($column->getEnumValuesAsArray() as $enumValue) {
                $shortDescr = 'Проверить на соответствие ' . $column->getTable()->getName() . '.' . $columnName . ' значению ' . $enumValue;
                $docblock = new \Zend\Code\Generator\DocBlockGenerator($shortDescr);
                $docblock->setTags(array(array('name' => 'return', 'description' => 'bool')));
                $method = new \Zend\Code\Generator\MethodGenerator();
                $method->setName('is' . $column->getNameAsCamelCase() . implode('', array_map('ucfirst', explode('_', $enumValue))));
                $method->setVisibility(\Zend\Code\Generator\AbstractMemberGenerator::VISIBILITY_PUBLIC);
                $method->setDocBlock($docblock);
                if ($part->hasPlugin('ConstantList', AbstractPart::PART_MODEL)) {
                    $modelName = $table->getNameAsCamelCase() . 'Model';
                    $file->addUse("\\Model\\{$modelName}");
                    $enumValue = $modelName . '::' . strtoupper($column->getName() . '_' . $enumValue);
                } else {
                    $enumValue = "'{$enumValue}'";
                }
                $method->setBody(<<<EOS
return \$this->get('{$columnName}') == {$enumValue};
EOS
);
                $part->getFile()->getClass()->addMethodFromGenerator($method);
            }
        }
        foreach ($columnList as $column) {
            if ($column->getColumnType() != 'enum' || substr($column->getName(), 0, 3) != 'is_' || count($column->getEnumValuesAsArray()) != 2) {
                continue;
            }
            $inc = 0;
            foreach ($column->getEnumValuesAsArray() as $enumValue) {
                if (in_array($enumValue, array('y', 'n'))) {
                    $inc++;
                }
            }
            if ($inc != 2) {
                continue;
            }
            $columnName = $column->getName();
            $shortDescr = 'Проверить флаг ' . $column->getTable()->getName() . '.' . $columnName;
            $docblock = new \Zend\Code\Generator\DocBlockGenerator($shortDescr);
            $docblock->setTags(array(array('name' => 'return', 'description' => 'bool')));
            $method = new \Zend\Code\Generator\MethodGenerator();
            $method->setName('is' . substr($column->getNameAsCamelCase(), 2));
            $method->setVisibility(\Zend\Code\Generator\AbstractMemberGenerator::VISIBILITY_PUBLIC);
            $method->setDocBlock($docblock);
            $method->setBody(<<<EOS
return \$this->get('{$columnName}') == 'y';
EOS
);
            $part->getFile()->getClass()->addMethodFromGenerator($method);
        }
    }
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $path = new PathBuilder();
        $path = $path->addPart('config')->addPart('autoload')->addPart('database.eloquentzf2.config.local.php')->getPath();
        $dbConfig = (include $path);
        $dbConfig = $dbConfig['database_eloquent'];
        $moduleName = $input->getArgument('ModuleName');
        $modelName = $input->getArgument('ModelName');
        $tblName = $input->getArgument('TableName');
        $entityPath = $input->getArgument('EntityRelativePath');
        if ($dbConfig['host'] == 'localhost') {
            $dbConfig['host'] = '127.0.0.1';
        }
        $dbh = new \PDO('mysql:host=' . $dbConfig['host'] . ';dbname=' . $dbConfig['database'], $dbConfig['username'], $dbConfig['password'] ? $dbConfig['password'] : null);
        $columns = [];
        $priKey = null;
        $autoInc = true;
        $enums = [];
        foreach ($dbh->query('select * from information_schema.columns where table_schema = \'' . $dbConfig['database'] . '\' and table_name = \'' . $tblName . '\'') as $row) {
            $columns[] = $row['COLUMN_NAME'];
            if (strtolower($row['COLUMN_KEY']) == 'pri') {
                if (!$priKey) {
                    $priKey = $row['COLUMN_NAME'];
                    if ($row['EXTRA'] != 'auto_increment') {
                        $autoInc = false;
                    }
                } else {
                    $priKey = [$priKey];
                    $priKey[] = $row['COLUMN_NAME'];
                    $autoInc = false;
                }
            }
            if (strtolower($row['DATA_TYPE']) == 'enum') {
                $enums[$row['COLUMN_NAME']] = explode(',', rtrim(str_replace('enum(', '', $row['COLUMN_TYPE']), ')'));
                $enums[$row['COLUMN_NAME']] = array_map(function ($el) {
                    return trim($el, "'");
                }, $enums[$row['COLUMN_NAME']]);
            }
            if (strtolower($row['DATA_TYPE']) == 'tinyint') {
                $enums[$row['COLUMN_NAME']] = [true, false];
            }
        }
        $fillable = [];
        foreach ($columns as $column) {
            if (is_array($priKey)) {
                if (!in_array($column, $priKey)) {
                    $fillable[] = $column;
                }
            } else {
                if ($column != $priKey) {
                    $fillable[] = $column;
                }
            }
        }
        foreach ($fillable as $k => $v) {
            if (in_array($v, ['created_at', 'updated_at', 'deleted_at'])) {
                unset($fillable[$k]);
            }
        }
        $path = new PathBuilder();
        $path = $path->addPart('module')->addPart($moduleName)->addPart('src')->addPart($moduleName)->addPart('Entity');
        if ($entityPath) {
            $entityPath = trim($entityPath, '/');
            $path->addPart($entityPath);
        }
        $path = $path->addPart($modelName . '.php')->getPath();
        if (file_exists($path)) {
            throw new \RuntimeException('A file with the same model name already exists: ' . $path);
        }
        $prop1 = new \Zend\Code\Generator\PropertyGenerator('incrementing', $autoInc, \Zend\Code\Generator\PropertyGenerator::FLAG_PUBLIC);
        $prop1->setDocBlock('@var bool');
        $prop2 = new \Zend\Code\Generator\PropertyGenerator('table', $tblName, \Zend\Code\Generator\PropertyGenerator::FLAG_PROTECTED);
        $prop2->setDocBlock('@var string');
        $prop3 = new \Zend\Code\Generator\PropertyGenerator('primaryKey', $priKey, \Zend\Code\Generator\PropertyGenerator::FLAG_PROTECTED);
        $prop3->setDocBlock(is_array($priKey) ? '@var array' : '@var string');
        $prop4 = new \Zend\Code\Generator\PropertyGenerator('fillable', $fillable, \Zend\Code\Generator\PropertyGenerator::FLAG_PROTECTED);
        $prop4->setDocBlock('@var array The attributes that are mass assignable.');
        $class = new ClassGenerator($modelName, $moduleName . '\\Entity', null, 'AbstractEntity', [], [$prop1, $prop2, $prop3, $prop4], []);
        if ($entityPath) {
            $class->setNamespaceName($class->getNamespaceName() . '\\' . trim(str_replace('/', '\\', $entityPath), '/'));
        }
        $dbGenerator = new \Zend\Code\Generator\DocBlockGenerator();
        foreach ($columns as $column) {
            $dbGenerator->setTag(['name' => 'property', 'description' => 'string $' . $column]);
        }
        $class->addUse('MdoBundleEloquent\\Entity\\AbstractEntity');
        $class->setDocBlock($dbGenerator);
        // Set timestamps = false if no created_at / updated_at
        if (!in_array('created_at', $columns) && !in_array('updated_at', $columns)) {
            $prop = new \Zend\Code\Generator\PropertyGenerator('timestamps', false, \Zend\Code\Generator\PropertyGenerator::FLAG_PUBLIC);
            $prop->setDocBlock('@var bool');
            $class->addPropertyFromGenerator($prop);
        }
        // Set getUpdatedAtColumn() to null if no created_at
        if (!in_array('created_at', $columns) && in_array('updated_at', $columns)) {
            $method = new \Zend\Code\Generator\MethodGenerator('getCreatedAtColumn', [], \Zend\Code\Generator\PropertyGenerator::FLAG_PUBLIC);
            $method->setDocBlock('@return null');
            $class->addMethodFromGenerator($method);
            $method = new \Zend\Code\Generator\MethodGenerator('setCreatedAt', ['value'], \Zend\Code\Generator\PropertyGenerator::FLAG_PUBLIC);
            $method->setDocBlock('@return null');
            $class->addMethodFromGenerator($method);
        }
        // Set getCreatedAtColumn() to null if no created_at
        if (!in_array('updated_at', $columns) && in_array('created_at', $columns)) {
            $method = new \Zend\Code\Generator\MethodGenerator('getUpdatedAtColumn', [], \Zend\Code\Generator\PropertyGenerator::FLAG_PUBLIC);
            $method->setDocBlock('@return null');
            $class->addMethodFromGenerator($method);
            $method = new \Zend\Code\Generator\MethodGenerator('setUpdatedAt', ['value'], \Zend\Code\Generator\PropertyGenerator::FLAG_PUBLIC);
            $method->setDocBlock('@return null');
            $class->addMethodFromGenerator($method);
        }
        // Set use soft delete trait if deleted_at
        if (in_array('deleted_at', $columns)) {
            $class->addTrait('SoftDeletingTrait');
            $prop = new \Zend\Code\Generator\PropertyGenerator('dates', ['deleted_at'], \Zend\Code\Generator\PropertyGenerator::FLAG_PROTECTED);
            $prop->setDocBlock('@var array');
            $class->addPropertyFromGenerator($prop);
            $class->addUse('Illuminate\\Database\\Eloquent\\SoftDeletingTrait');
        }
        $method = new \Zend\Code\Generator\MethodGenerator('getDates', [], \Zend\Code\Generator\PropertyGenerator::FLAG_PUBLIC, 'return [];');
        $method->setDocBlock('@return null');
        $class->addMethodFromGenerator($method);
        // Set enums
        foreach ($enums as $enumColName => $values) {
            foreach ($values as $value) {
                if (is_bool($value)) {
                    $name = $value === TRUE ? 'yes' : 'no';
                    $prop = new \Zend\Code\Generator\PropertyGenerator(strtoupper($enumColName . '_' . $name), (int) $value);
                } else {
                    $prop = new \Zend\Code\Generator\PropertyGenerator(strtoupper($enumColName . '_' . $value), $value);
                }
                $prop->setConst(true);
                $class->addPropertyFromGenerator($prop);
            }
            $method = new \Zend\Code\Generator\MethodGenerator('get' . ucfirst($enumColName) . 'Values', [], \Zend\Code\Generator\PropertyGenerator::FLAG_STATIC);
            $method->setDocBlock('@return array');
            $body = 'return [';
            foreach ($values as $value) {
                if (is_bool($value)) {
                    $name = $value === TRUE ? 'yes' : 'no';
                } else {
                    $name = $value;
                }
                $body .= "\r\n" . '    ' . "'" . $name . "'" . ' => self::' . strtoupper($enumColName . '_' . $name) . ',';
            }
            $body .= "\r\n" . '];';
            $method->setBody($body);
            $class->addMethodFromGenerator($method);
        }
        $builder = new PathBuilder();
        $builder->make_path($path);
        file_put_contents($path, '<?php' . "\r\n" . $class->generate());
        $output->writeln('<info>write</info>: ' . $path);
        // Now that we wrote the eloquent class
        // Let's build the model validator class
        $class = new ClassGenerator($modelName . 'Validator', $moduleName . '\\Validator', null, 'AbstractFieldset', ['InputFilterProviderInterface'], [], []);
        $class->addUse('MdoBundle\\Form\\AbstractFieldset');
        $class->addUse('MdoBundle\\Validator\\ValidatorTrait\\ValidationRulesTrait');
        $class->addUse('Zend\\InputFilter\\InputFilterProviderInterface');
        $class->addUse('Zend\\Mvc\\I18n\\Translator');
        $class->addTrait('ValidationRulesTrait');
        $codeName = strtolower($modelName);
        $body = <<<phpCode
parent::__construct('{$codeName}');

\$this->validationRules = [

phpCode;
        foreach ($fillable as $item) {
            $body .= <<<phpCode
    '{$item}' => [
        'required',
        'validators' => [
            [
                'name' => 'NotEmpty',
                'break_chain_on_failure' => true,
                'options' => [
                    'message' => \$translator->translate('You must provide the field {$item}'),
                ],
            ],
        ]
    ],

phpCode;
        }
        $body .= <<<phpCode
];

return \$this->addElements([

phpCode;
        foreach ($fillable as $item) {
            $body .= <<<phpCode
    '{$item}',

phpCode;
        }
        $body .= <<<phpCode
]);
phpCode;
        $class->addMethod('__construct', [new ParameterGenerator('translator', 'Translator')], [], $body);
        $path = new PathBuilder();
        $path = $path->addPart('module')->addPart($moduleName)->addPart('src')->addPart($moduleName)->addPart('Validator')->addPart($modelName . 'Validator.php')->getPath();
        if (file_exists($path)) {
            throw new \RuntimeException('A file with the same model validator name already exists: ' . $path);
        }
        file_put_contents($path, '<?php' . "\r\n" . $class->generate());
        $output->writeln('<info>write</info>: ' . $path);
    }
Exemple #9
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();
        $linkList = $table->getLink();
        foreach ($linkList as $link) {
            $foreignEntity = $link->getForeignEntity();
            $columnName = $link->getForeignColumn()->getName();
            $columnComment = $link->getForeignColumn()->getComment();
            switch ($link->getLinkType()) {
                case AbstractLink::LINK_TYPE_ONE_TO_MANY:
                case AbstractLink::LINK_TYPE_MANY_TO_MANY:
                    if ($columnComment) {
                        $shortDescr = "Получить список " . mb_strtolower($columnComment, 'UTF-8') . ' (' . $table->getName() . '.' . $columnName . ')';
                    } else {
                        $shortDescr = 'Получить список ' . $link->getForeignEntity();
                    }
                    $docblock = new \Zend\Code\Generator\DocBlockGenerator($shortDescr);
                    $docblock->setTags(array(array('name' => 'return', 'description' => '\\Model\\Collection\\' . $link->getForeignColumn()->getTable()->getNameAsCamelCase() . 'Collection')));
                    $method = new \Zend\Code\Generator\MethodGenerator();
                    $method->setName('get' . $link->getForeignEntityAsCamelCase() . 'Collection');
                    $method->setVisibility(\Zend\Code\Generator\AbstractMemberGenerator::VISIBILITY_PUBLIC);
                    $method->setDocBlock($docblock);
                    $method->setBody(<<<EOS
return \$this->get('_{$foreignEntity}_collection');
EOS
);
                    try {
                        $part->getFile()->getClass()->addMethodFromGenerator($method);
                    } catch (\Exception $e) {
                    }
                case AbstractLink::LINK_TYPE_ONE_TO_ONE:
                case AbstractLink::LINK_TYPE_MANY_TO_ONE:
                    if ($columnComment) {
                        $shortDescr = "Получить связанную сущность" . mb_strtolower($columnComment, 'UTF-8') . ' (' . $table->getName() . '.' . $columnName . ')';
                    } else {
                        $shortDescr = 'Получить связанную сущность ' . $link->getForeignEntity();
                    }
                    $docblock = new \Zend\Code\Generator\DocBlockGenerator($shortDescr);
                    $docblock->setTags(array(array('name' => 'return', 'description' => '\\Model\\Entity\\' . $link->getForeignColumn()->getTable()->getNameAsCamelCase() . 'Entity')));
                    $method = new \Zend\Code\Generator\MethodGenerator();
                    $method->setName('get' . $link->getForeignEntityAsCamelCase());
                    $method->setVisibility(\Zend\Code\Generator\AbstractMemberGenerator::VISIBILITY_PUBLIC);
                    $method->setDocBlock($docblock);
                    $method->setBody(<<<EOS
return \$this->get('_{$foreignEntity}');
EOS
);
                    try {
                        $part->getFile()->getClass()->addMethodFromGenerator($method);
                    } catch (\Exception $e) {
                    }
            }
        }
    }
Exemple #10
0
 public function postRun(PartInterface $part)
 {
     /**
      * @var $part \Model\Generator\Part\Entity
      */
     /**
      * @var $file \Model\Code\Generator\FileGenerator
      */
     $file = $part->getFile();
     $table = $part->getTable();
     $tags = array(array('name' => 'var', 'description' => ' array связи'));
     $docblock = new \Zend\Code\Generator\DocBlockGenerator('Связи');
     $docblock->setTags($tags);
     $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);
 }
 /**
  * addProperties()
  *
  * @param array $properties
  * @return $this
  * @throws \InvalidArgumentException
  */
 public function addProperties(array $properties)
 {
     foreach ($properties as $propertyOptions) {
         $propertyObject = new PropertyGenerator();
         $this->_setDataToObject($propertyObject, $propertyOptions, $this->_propertyOptions);
         if (isset($propertyOptions['docblock'])) {
             $docBlock = $propertyOptions['docblock'];
             if (is_array($docBlock)) {
                 $docBlockObject = new \Zend\Code\Generator\DocBlockGenerator();
                 $docBlockObject->setWordWrap(false);
                 $this->_setDataToObject($docBlockObject, $docBlock, $this->_docBlockOptions);
                 $propertyObject->setDocBlock($docBlockObject);
             }
         }
         $this->addPropertyFromGenerator($propertyObject);
     }
     return $this;
 }