Since: 2.0
Author: Qiang Xue (qiang.xue@gmail.com)
Inheritance: extends yii\gii\Generator
 public function testModelGenerator()
 {
     $generator = new ModelGenerator();
     $generator->template = 'default';
     $generator->tableName = 'profile';
     $generator->modelClass = 'Profile';
     $valid = $generator->validate();
     $this->assertTrue($valid, 'Validation failed: ' . print_r($generator->getErrors(), true));
     $files = $generator->generate();
     $modelCode = $files[0]->content;
     $this->assertTrue(strpos($modelCode, "'id' => 'ID'") !== false, "ID label should be there:\n" . $modelCode);
     $this->assertTrue(strpos($modelCode, "'description' => 'Description',") !== false, "Description label should be there:\n" . $modelCode);
 }
Exemplo n.º 2
0
 /**
  * @inheritdoc
  */
 public function beforeValidate()
 {
     if ($this->template == 'base') {
         $this->ns = 'app\\base\\models';
     } else {
         $this->ns = 'app\\models';
     }
     return parent::beforeValidate();
 }
 public function generateRules($table)
 {
     $rules = parent::generateRules($table);
     foreach ($rules as &$r) {
         $r = str_replace(' => ', '=>', $r);
         $posEndAttr = strpos($r, ']', 2);
         $attrList = substr($r, 2, $posEndAttr);
         $r = substr($r, 0, 2) . str_replace(', ', ',', $attrList) . substr($r, $posEndAttr + 2);
     }
     return $rules;
 }
Exemplo n.º 4
0
 protected function generate2ClassNames($tableName, $useSchemaName = null)
 {
     $tableName = preg_replace('/2/', '2_', $tableName);
     return parent::generateClassName($tableName, $useSchemaName);
 }
Exemplo n.º 5
0
 /**
  * Generates validation rules for the specified table.
  * @param \yii\db\TableSchema $table the table schema
  * @return array the generated validation rules
  */
 public function generateRules($table)
 {
     $types = [];
     $parentRules = parent::generateRules($table);
     // delete not required fields from required string.
     foreach ($parentRules as $i => $parentRule) {
         if (strpos($parentRule, "'required']") !== false) {
             foreach ($this->_notInsertOnRequired as $column) {
                 $search1 = "'{$column}', ";
                 $search2 = ", '{$column}'";
                 $search3 = "'{$column}'";
                 $parentRule = str_replace($search1, '', $parentRule);
                 $parentRule = str_replace($search2, '', $parentRule);
                 $parentRule = str_replace($search3, '', $parentRule);
                 $parentRules[$i] = $parentRule;
             }
         }
     }
     foreach ($table->columns as $column) {
         /*TODO: (ruben) enhance the url string detection with regex (only when 'url' is the only word, or have an _ before or after the word.*/
         if (strstr($column->name, 'url')) {
             $types['url'][] = $column->name;
         }
     }
     $rules = [];
     foreach ($types as $type => $columns) {
         $rules[] = "[['" . implode("', '", $columns) . "'], '{$type}']";
     }
     $allRules = array_merge($parentRules, $rules);
     return $allRules;
 }
Exemplo n.º 6
0
 /**
  * {@inheritdoc}
  */
 public function stickyAttributes()
 {
     return array_merge(parent::stickyAttributes(), ['baseNs']);
 }
Exemplo n.º 7
0
 /**
  * Generates validation rules for the specified table and add enum value validation.
  * @param \yii\db\TableSchema $table the table schema
  * @return array the generated validation rules
  */
 public function generateRules($table)
 {
     $rules = [];
     //for enum fields create rules "in range" for all enum values
     $enum = $this->getEnum($table->columns);
     foreach ($enum as $field_name => $field_details) {
         $ea = array();
         foreach ($field_details['values'] as $field_enum_values) {
             $ea[] = 'self::' . $field_enum_values['const_name'];
         }
         $rules[] = "['" . $field_name . "', 'in', 'range' => [\n                    " . implode(",\n                    ", $ea) . ",\n                ]\n            ]";
     }
     return array_merge(parent::generateRules($table), $rules);
 }
Exemplo n.º 8
0
 /**
  * @inheritdoc
  */
 public function attributeLabels()
 {
     return array_merge(parent::attributeLabels(), ['createType' => 'Creation Mode', 'saveDocType' => 'Save DocBlock to']);
 }
Exemplo n.º 9
0
 /** Added by pafnow
  * Generates validation rules for the specified table.
  * @param \yii\db\TableSchema $table the table schema
  * @return array the generated validation rules
  */
 public function generateRules($table)
 {
     $table_clone = clone $table;
     $types = [];
     foreach ($table_clone->columns as $key => $column) {
         $column_clone = clone $column;
         $table_clone->columns[$key] = $column_clone;
         $type_comment = Json::getValue($column->comment, "type", false);
         if (empty($type_comment)) {
             continue;
         }
         $types[$type_comment][] = $column->name;
         if (!$column->allowNull && $column->defaultValue === null) {
             $types['required'][] = $column->name;
         }
         //Remove the column from the table so it is not generated again by the parent function
         unset($table_clone->columns[$key]);
     }
     $rules = [];
     foreach ($types as $type => $columns) {
         $rules[] = "[['" . implode("', '", $columns) . "'], '{$type}']";
     }
     return array_merge(parent::generateRules($table_clone), $rules);
 }
Exemplo n.º 10
0
 /**
  * @inheritdoc
  */
 public function hints()
 {
     return array_merge(parent::hints(), ['useMessages' => 'This indicates whether getters and setters for relations with SourceMessage table should be generated. In true case
             relations will be generated in get-set way instead of default']);
 }
Exemplo n.º 11
0
 /**
  * Generates validation rules for the specified table.
  * @param \yii\db\TableSchema $table the table schema
  * @return array the generated validation rules
  */
 public function generateRules($table)
 {
     $rules = parent::generateRules($table);
     foreach ($rules as $key => $rule) {
         $rules[$key] = preg_replace_callback("/[A-Za-z]+::className\\(\\)/", function ($matches) {
             $match = ArrayHelper::getValue($matches, 0);
             $class = ArrayHelper::getValue(explode('::', $match), 0);
             $fqn = ModelHelper::root($this->helperModel->getClass(ModelHelper::RK_MODEL_CM, $class));
             if ($fqn) {
                 return sprintf('%s::className()', $fqn);
             }
             return $match;
         }, $rule);
     }
     return $rules;
 }
Exemplo n.º 12
0
    /**
     * @inheritdoc
     */
    public function render($template, $params = [])
    {
        $output = parent::render($template, $params);
        switch ($template) {
            case 'model.php':
                // fix uses
                $tableName = $params['tableName'];
                if (array_key_exists($tableName, $this->relationUses) && $this->relationUses[$tableName]) {
                    $uses = array_unique($this->relationUses[$tableName]);
                    Helper::sortUses($uses);
                    $output = str_replace('use Yii;', 'use Yii;' . "\n" . 'use ' . implode(';' . "\n" . 'use ', $uses) . ';', $output);
                }
                // fix rules
                $output = preg_replace('~\'targetClass\' \\=\\> (\\w+)Base\\:\\:className\\(\\)~', '\'targetClass\' => $1::className()', $output);
                // fix relations
                $nsClassName = $this->ns . '\\' . $params['className'];
                if (class_exists($nsClassName) && is_subclass_of($nsClassName, 'yii\\boost\\db\\ActiveRecord')) {
                    $model = new $nsClassName();
                    $output = preg_replace_callback('~@return \\\\(yii\\\\db\\\\ActiveQuery)\\s+\\*/\\s+public function ([^\\(]+)\\(\\)~', function ($match) use($model) {
                        if (method_exists($model, $match[2])) {
                            return str_replace($match[1], get_class(call_user_func([$model, $match[2]])) . '|\\' . $match[1], $match[0]);
                        } else {
                            return $match[0];
                        }
                    }, $output);
                }
                $params['relationUses'] = $this->relationUses;
                if (array_key_exists($tableName, $this->allRelations)) {
                    $params['allRelations'] = $this->allRelations[$tableName];
                } else {
                    $params['allRelations'] = [];
                }
                if (array_key_exists($tableName, $this->singularRelations)) {
                    $params['singularRelations'] = $this->singularRelations[$tableName];
                } else {
                    $params['singularRelations'] = [];
                }
                if (array_key_exists($tableName, $this->pluralRelations)) {
                    $params['pluralRelations'] = $this->pluralRelations[$tableName];
                } else {
                    $params['pluralRelations'] = [];
                }
                $output = preg_replace('~\\}(\\s*)$~', parent::render('model-part.php', $params) . '}$1', $output);
                break;
            case 'query.php':
                $code = <<<CODE
    /*public function active()
    {
        return \$this->andWhere('[[status]]=1');
    }*/

CODE;
                $output = str_replace($code, '', $output);
                $output = preg_replace('~\\}(\\s*)$~', parent::render('query-part.php', $params) . '}$1', $output);
                break;
        }
        $output = preg_replace_callback('~(@return |return new )\\\\((?:\\w+\\\\)*\\w+\\\\query)\\\\base\\\\(\\w+Query)Base~', function ($match) {
            $nsClassName = $match[2] . '\\' . $match[3];
            if (class_exists($nsClassName)) {
                return $match[1] . '\\' . $nsClassName;
            } else {
                return $match[0];
            }
        }, $output);
        $output = preg_replace_callback('~(@see | @return |\\[\\[)\\\\((?:\\w+\\\\)*\\w+)\\\\base\\\\(\\w+)Base~', function ($match) {
            $nsClassName = $match[2] . '\\' . $match[3];
            if (class_exists($nsClassName)) {
                return $match[1] . '\\' . $nsClassName;
            } else {
                return $match[0];
            }
        }, $output);
        return $output;
    }
Exemplo n.º 13
0
 /**
  * @return array the generated relation declarations
  */
 protected function generateRelations()
 {
     if (!$this->generateRelations) {
         return [];
     }
     $relations = parent::generateRelations();
     $relationNames = [];
     // generate inverse relations
     $db = $this->getDbConnection();
     foreach ($this->getSchemaNames() as $schemaName) {
         foreach ($db->getSchema()->getTableSchemas($schemaName) as $table) {
             $className = $this->generateClassName($table->fullName);
             foreach ($table->foreignKeys as $refs) {
                 $refTable = $refs[0];
                 $refTableSchema = $db->getTableSchema($refTable);
                 unset($refs[0]);
                 $fks = array_keys($refs);
                 $leftRelationName = $this->generateRelationName($relationNames, $table, $fks[0], false);
                 $relationNames[$table->fullName][$leftRelationName] = true;
                 $hasMany = $this->isManyRelation($table, $fks);
                 $rightRelationName = $this->generateRelationName($relationNames, $refTableSchema, $className, $hasMany);
                 $relationNames[$refTableSchema->fullName][$rightRelationName] = true;
                 $relations[$table->fullName][$leftRelationName][0] = rtrim($relations[$table->fullName][$leftRelationName][0], ';') . "->inverseOf('" . lcfirst($rightRelationName) . "');";
                 $relations[$refTableSchema->fullName][$rightRelationName][0] = rtrim($relations[$refTableSchema->fullName][$rightRelationName][0], ';') . "->inverseOf('" . lcfirst($leftRelationName) . "');";
             }
         }
     }
     return $relations;
 }
Exemplo n.º 14
0
 public function generateLabels($table)
 {
     $labels = parent::generateLabels($table);
     array_walk($labels, function (&$value) {
         if (substr_compare($value, ' id', -3, 3, true) === 0) {
             $value = substr($value, 0, -3);
             // remove ID
         }
         $value = ucfirst(strtolower($value));
     });
     return $labels;
 }
Exemplo n.º 15
0
 /**
  * Validates the [[ns]] attribute.
  */
 public function validateNamespace($attribute)
 {
     parent::validateNamespace($attribute);
     $this->ns = ltrim($this->ns, '\\');
     if (false === strpos($this->ns, 'app\\')) {
         $this->addError('ns', '@app namespace must be used.');
     }
 }
Exemplo n.º 16
0
 /**
  * @inheritdoc
  */
 public function stickyAttributes()
 {
     return array_merge(parent::stickyAttributes(), ['createBaseModel']);
 }
Exemplo n.º 17
0
 /**
  * @inheritdoc
  */
 public function rules()
 {
     return array_merge(parent::rules(), [[['db', 'ns', 'tableName', 'moduleName', 'modelClass', 'baseClass'], 'filter', 'filter' => 'trim'], [['db', 'ns', 'tableName', 'baseClass'], 'required'], [['db', 'modelClass'], 'match', 'pattern' => '/^\\w+$/', 'message' => 'Only word characters are allowed.'], [['ns', 'baseClass'], 'match', 'pattern' => '/^[\\w\\\\]+$/', 'message' => 'Only word characters and backslashes are allowed.'], [['tableName'], 'match', 'pattern' => '/^(\\w+\\.)?([\\w\\*]+)$/', 'message' => 'Only word characters, and optionally an asterisk and/or a dot are allowed.'], [['db'], 'validateDb'], [['ns'], 'validateNamespace'], [['tableName'], 'validateTableName'], [['modelClass'], 'validateModelClass', 'skipOnEmpty' => false], [['baseClass'], 'validateClass', 'params' => ['extends' => ActiveRecord::className()]], [['generateRelations', 'generateLabelsFromComments'], 'boolean'], [['enableI18N'], 'boolean'], [['messageCategory'], 'validateMessageCategory', 'skipOnEmpty' => false]]);
 }
Exemplo n.º 18
0
 /**
  * @inheritdoc
  */
 public function getTableNames()
 {
     return parent::getTableNames();
 }
Exemplo n.º 19
0
 /**
  * @inheritdoc
  */
 public function stickyAttributes()
 {
     return array_merge(parent::stickyAttributes(), ['ns', 'db', 'baseClass', 'generateRelations', 'generateLabelsFromComments', 'queryNs', 'queryBaseClass']);
 }
Exemplo n.º 20
0
 /** @inheritdoc */
 public function hints()
 {
     return array_merge(parent::attributeLabels(), ['relationsInMain' => 'By default relations are saved in abstract model.']);
 }
Exemplo n.º 21
0
 /**
  * @inheritdoc
  */
 protected function getTableNames()
 {
     $tableNames = parent::getTableNames();
     if (($key = array_search('migration', $tableNames)) !== false) {
         unset($tableNames[$key]);
         return array_values($tableNames);
     }
     return $tableNames;
 }
Exemplo n.º 22
0
 public function rules()
 {
     return array_merge(parent::rules(), [[['tableNameHelper'], 'safe']]);
 }
Exemplo n.º 23
0
 public function generateRules($table)
 {
     $rules = parent::generateRules($table);
     if (isset($this->behaviorsType['phone']) && isset($this->behaviorsType['phone']['checked']) && $this->behaviorsType['phone']['checked']) {
         if ($this->behaviorType['phone']['phoneAttribute']) {
             $rules[] = "[['{$this->behaviorType['phone']['phoneAttribute']}'], 'borales\\extensions\\phoneInput\\PhoneInputValidator']";
         }
     }
     return $rules;
 }
Exemplo n.º 24
0
 public function stickyAttributes()
 {
     return array_merge(parent::stickyAttributes(), ['generateQuery']);
 }
Exemplo n.º 25
0
 /**
  * @inheritdoc
  */
 public function rules()
 {
     return array_merge(parent::rules(), [[['relationClassName'], 'validateClass', 'params' => ['extends' => ActiveQuery::className()]]]);
 }
Exemplo n.º 26
0
 protected function generateRelations()
 {
     $relations = parent::generateRelations();
     // inject namespace
     $ns = "\\{$this->ns}\\";
     foreach ($relations as $model => $relInfo) {
         foreach ($relInfo as $relName => $relData) {
             $relations[$model][$relName][0] = preg_replace('/(has[A-Za-z0-9]+\\()([a-zA-Z0-9]+::)/', '$1__NS__$2', $relations[$model][$relName][0]);
             $relations[$model][$relName][0] = str_replace('__NS__', $ns, $relations[$model][$relName][0]);
         }
     }
     return $relations;
 }
Exemplo n.º 27
0
 /**
  * @inheritdoc
  */
 public function hints()
 {
     return array_merge(parent::hints(), ['tPrefix' => 'For example <code>PageModule</code>']);
 }