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); }
/** * @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; }
protected function generate2ClassNames($tableName, $useSchemaName = null) { $tableName = preg_replace('/2/', '2_', $tableName); return parent::generateClassName($tableName, $useSchemaName); }
/** * 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; }
/** * {@inheritdoc} */ public function stickyAttributes() { return array_merge(parent::stickyAttributes(), ['baseNs']); }
/** * 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); }
/** * @inheritdoc */ public function attributeLabels() { return array_merge(parent::attributeLabels(), ['createType' => 'Creation Mode', 'saveDocType' => 'Save DocBlock to']); }
/** 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); }
/** * @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']); }
/** * 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; }
/** * @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; }
/** * @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; }
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; }
/** * 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.'); } }
/** * @inheritdoc */ public function stickyAttributes() { return array_merge(parent::stickyAttributes(), ['createBaseModel']); }
/** * @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]]); }
/** * @inheritdoc */ public function getTableNames() { return parent::getTableNames(); }
/** * @inheritdoc */ public function stickyAttributes() { return array_merge(parent::stickyAttributes(), ['ns', 'db', 'baseClass', 'generateRelations', 'generateLabelsFromComments', 'queryNs', 'queryBaseClass']); }
/** @inheritdoc */ public function hints() { return array_merge(parent::attributeLabels(), ['relationsInMain' => 'By default relations are saved in abstract model.']); }
/** * @inheritdoc */ protected function getTableNames() { $tableNames = parent::getTableNames(); if (($key = array_search('migration', $tableNames)) !== false) { unset($tableNames[$key]); return array_values($tableNames); } return $tableNames; }
public function rules() { return array_merge(parent::rules(), [[['tableNameHelper'], 'safe']]); }
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; }
public function stickyAttributes() { return array_merge(parent::stickyAttributes(), ['generateQuery']); }
/** * @inheritdoc */ public function rules() { return array_merge(parent::rules(), [[['relationClassName'], 'validateClass', 'params' => ['extends' => ActiveQuery::className()]]]); }
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; }
/** * @inheritdoc */ public function hints() { return array_merge(parent::hints(), ['tPrefix' => 'For example <code>PageModule</code>']); }