Class yii\gii\generators\crud\Generator
Inheritance | yii\gii\generators\crud\Generator » yii\gii\Generator » yii\base\Model |
---|---|
Available since extension's version | 2.0 |
Source Code | https://github.com/yiisoft/yii2-gii/blob/master/src/generators/crud/Generator.php |
Generates CRUD
Public Properties
Public Methods
Protected Methods
Method | Description | Defined By |
---|---|---|
getClassDbDriverName() | yii\gii\generators\crud\Generator |
Property Details
Model column names. This property is read-only.
The controller ID (without the module ID prefix). This property is read-only.
Whether to wrap the GridView
or ListView
widget with the yii\widgets\Pjax
widget
Searchable attributes. This property is read-only.
This property is read-only.
Method Details
public void attributeLabels ( ) |
public function attributeLabels()
{
return array_merge(parent::attributeLabels(), [
'modelClass' => 'Model Class',
'controllerClass' => 'Controller Class',
'viewPath' => 'View Path',
'baseControllerClass' => 'Base Controller Class',
'indexWidgetType' => 'Widget Used in Index Page',
'searchModelClass' => 'Search Model Class',
'enablePjax' => 'Enable Pjax',
]);
}
Defined in: yii\gii\Generator::autoCompleteData()
Returns the list of auto complete values.
The array keys are the attribute names, and the array values are the corresponding auto complete values. Auto complete values can also be callable typed in order one want to make postponed data generation.
public array autoCompleteData ( ) | ||
return | array |
The list of auto complete values |
---|
public function autoCompleteData()
{
return [];
}
Defined in: yii\gii\Generator::defaultTemplate()
Returns the root path to the default code template files.
The default implementation will return the "templates" subdirectory of the directory containing the generator class file.
public string defaultTemplate ( ) | ||
return | string |
The root path to the default code template files. |
---|
public function defaultTemplate()
{
$class = new ReflectionClass($this);
return dirname($class->getFileName()) . '/default';
}
Defined in: yii\gii\Generator::formView()
Returns the view file for the input form of the generator.
The default implementation will return the "form.php" file under the directory that contains the generator class file.
public string formView ( ) | ||
return | string |
The view file for the input form of the generator. |
---|
public function formView()
{
$class = new ReflectionClass($this);
return dirname($class->getFileName()) . '/form.php';
}
Generates the code based on the current user input and the specified code template files.
This is the main method that child classes should implement. Please refer to yii\gii\generators\controller\Generator::generate() as an example on how to implement this method.
public yii\gii\CodeFile[] generate ( ) | ||
return | yii\gii\CodeFile[] |
A list of code files to be created. |
---|
public function generate()
{
$controllerFile = Yii::getAlias('@' . str_replace('\\', '/', ltrim($this->controllerClass, '\\')) . '.php');
$files = [
new CodeFile($controllerFile, $this->render('controller.php')),
];
if (!empty($this->searchModelClass)) {
$searchModel = Yii::getAlias('@' . str_replace('\\', '/', ltrim($this->searchModelClass, '\\') . '.php'));
$files[] = new CodeFile($searchModel, $this->render('search.php'));
}
$viewPath = $this->getViewPath();
$templatePath = $this->getTemplatePath() . '/views';
foreach (scandir($templatePath) as $file) {
if (empty($this->searchModelClass) && $file === '_search.php') {
continue;
}
if (is_file($templatePath . '/' . $file) && pathinfo($file, PATHINFO_EXTENSION) === 'php') {
$files[] = new CodeFile("$viewPath/$file", $this->render("views/$file"));
}
}
return $files;
}
Generates parameter tags for phpdoc
public array generateActionParamComments ( ) | ||
return | array |
Parameter tags for phpdoc |
---|
public function generateActionParamComments()
{
/* @var $class ActiveRecord */
$class = $this->modelClass;
$pks = $class::primaryKey();
if (($table = $this->getTableSchema()) === false) {
$params = [];
foreach ($pks as $pk) {
$params[] = '@param ' . (strtolower(substr($pk, -2)) === 'id' ? 'integer' : 'string') . ' $' . $pk;
}
return $params;
}
if (count($pks) === 1) {
return ['@param ' . $table->columns[$pks[0]]->phpType . ' $id'];
}
$params = [];
foreach ($pks as $pk) {
$params[] = '@param ' . $table->columns[$pk]->phpType . ' $' . $pk;
}
return $params;
}
Generates action parameters
public string generateActionParams ( ) |
public function generateActionParams()
{
/* @var $class ActiveRecord */
$class = $this->modelClass;
$pks = $class::primaryKey();
if (count($pks) === 1) {
return '$id';
}
return '$' . implode(', $', $pks);
}
Generates code for active field
public string generateActiveField ( $attribute ) | ||
$attribute | string |
public function generateActiveField($attribute)
{
$tableSchema = $this->getTableSchema();
if ($tableSchema === false || !isset($tableSchema->columns[$attribute])) {
if (preg_match('/^(password|pass|passwd|passcode)$/i', $attribute)) {
return "\$form->field(\$model, '$attribute')->passwordInput()";
}
return "\$form->field(\$model, '$attribute')";
}
$column = $tableSchema->columns[$attribute];
if ($column->phpType === 'boolean') {
return "\$form->field(\$model, '$attribute')->checkbox()";
}
if ($column->type === 'text') {
return "\$form->field(\$model, '$attribute')->textarea(['rows' => 6])";
}
if (preg_match('/^(password|pass|passwd|passcode)$/i', $column->name)) {
$input = 'passwordInput';
} else {
$input = 'textInput';
}
if (is_array($column->enumValues) && count($column->enumValues) > 0) {
$dropDownOptions = [];
foreach ($column->enumValues as $enumValue) {
$dropDownOptions[$enumValue] = Inflector::humanize($enumValue);
}
return "\$form->field(\$model, '$attribute')->dropDownList("
. preg_replace("/\n\s*/", ' ', VarDumper::export($dropDownOptions)).", ['prompt' => ''])";
}
if ($column->phpType !== 'string' || $column->size === null) {
return "\$form->field(\$model, '$attribute')->$input()";
}
return "\$form->field(\$model, '$attribute')->$input(['maxlength' => true])";
}
Generates code for active search field
public string generateActiveSearchField ( $attribute ) | ||
$attribute | string |
public function generateActiveSearchField($attribute)
{
$tableSchema = $this->getTableSchema();
if ($tableSchema === false) {
return "\$form->field(\$model, '$attribute')";
}
$column = $tableSchema->columns[$attribute];
if ($column->phpType === 'boolean') {
return "\$form->field(\$model, '$attribute')->checkbox()";
}
return "\$form->field(\$model, '$attribute')";
}
Generates column format
public string generateColumnFormat ( $column ) | ||
$column | \yii\db\ColumnSchema |
public function generateColumnFormat($column)
{
if ($column->phpType === 'boolean') {
return 'boolean';
}
if ($column->type === 'text') {
return 'ntext';
}
if (stripos($column->name, 'time') !== false && $column->phpType === 'integer') {
return 'datetime';
}
if (stripos($column->name, 'email') !== false) {
return 'email';
}
if (preg_match('/(\b|[_-])url(\b|[_-])/i', $column->name)) {
return 'url';
}
return 'text';
}
Generates search conditions
public array generateSearchConditions ( ) |
public function generateSearchConditions()
{
$columns = [];
if (($table = $this->getTableSchema()) === false) {
$class = $this->modelClass;
/* @var $model \yii\base\Model */
$model = new $class();
foreach ($model->attributes() as $attribute) {
$columns[$attribute] = 'unknown';
}
} else {
foreach ($table->columns as $column) {
$columns[$column->name] = $column->type;
}
}
$likeConditions = [];
$hashConditions = [];
foreach ($columns as $column => $type) {
switch ($type) {
case Schema::TYPE_TINYINT:
case Schema::TYPE_SMALLINT:
case Schema::TYPE_INTEGER:
case Schema::TYPE_BIGINT:
case Schema::TYPE_BOOLEAN:
case Schema::TYPE_FLOAT:
case Schema::TYPE_DOUBLE:
case Schema::TYPE_DECIMAL:
case Schema::TYPE_MONEY:
case Schema::TYPE_DATE:
case Schema::TYPE_TIME:
case Schema::TYPE_DATETIME:
case Schema::TYPE_TIMESTAMP:
$hashConditions[] = "'{$column}' => \$this->{$column},";
break;
default:
$likeKeyword = $this->getClassDbDriverName() === 'pgsql' ? 'ilike' : 'like';
$likeConditions[] = "->andFilterWhere(['{$likeKeyword}', '{$column}', \$this->{$column}])";
break;
}
}
$conditions = [];
if (!empty($hashConditions)) {
$conditions[] = "\$query->andFilterWhere([\n"
. str_repeat(' ', 12) . implode("\n" . str_repeat(' ', 12), $hashConditions)
. "\n" . str_repeat(' ', 8) . "]);\n";
}
if (!empty($likeConditions)) {
$conditions[] = "\$query" . implode("\n" . str_repeat(' ', 12), $likeConditions) . ";\n";
}
return $conditions;
}
Generates the attribute labels for the search model.
public array generateSearchLabels ( ) | ||
return | array |
The generated attribute labels (name => label) |
---|
public function generateSearchLabels()
{
/* @var $model \yii\base\Model */
$model = new $this->modelClass();
$attributeLabels = $model->attributeLabels();
$labels = [];
foreach ($this->getColumnNames() as $name) {
if (isset($attributeLabels[$name])) {
$labels[$name] = $attributeLabels[$name];
} else {
if (!strcasecmp($name, 'id')) {
$labels[$name] = 'ID';
} else {
$label = Inflector::camel2words($name);
if (!empty($label) && substr_compare($label, ' id', -3, 3, true) === 0) {
$label = substr($label, 0, -3) . ' ID';
}
$labels[$name] = $label;
}
}
}
return $labels;
}
Generates validation rules for the search model.
public array generateSearchRules ( ) | ||
return | array |
The generated validation rules |
---|
public function generateSearchRules()
{
if (($table = $this->getTableSchema()) === false) {
return ["[['" . implode("', '", $this->getColumnNames()) . "'], 'safe']"];
}
$types = [];
foreach ($table->columns as $column) {
switch ($column->type) {
case Schema::TYPE_TINYINT:
case Schema::TYPE_SMALLINT:
case Schema::TYPE_INTEGER:
case Schema::TYPE_BIGINT:
$types['integer'][] = $column->name;
break;
case Schema::TYPE_BOOLEAN:
$types['boolean'][] = $column->name;
break;
case Schema::TYPE_FLOAT:
case Schema::TYPE_DOUBLE:
case Schema::TYPE_DECIMAL:
case Schema::TYPE_MONEY:
$types['number'][] = $column->name;
break;
case Schema::TYPE_DATE:
case Schema::TYPE_TIME:
case Schema::TYPE_DATETIME:
case Schema::TYPE_TIMESTAMP:
default:
$types['safe'][] = $column->name;
break;
}
}
$rules = [];
foreach ($types as $type => $columns) {
$rules[] = "[['" . implode("', '", $columns) . "'], '$type']";
}
return $rules;
}
Defined in: yii\gii\Generator::generateString()
Generates a string depending on enableI18N property
public string generateString ( $string = '', $placeholders = [] ) | ||
$string | string |
The text be generated |
$placeholders | array |
The placeholders to use by |
public function generateString($string = '', $placeholders = [])
{
$string = addslashes($string);
if ($this->enableI18N) {
// If there are placeholders, use them
if (!empty($placeholders)) {
$ph = ', ' . VarDumper::export($placeholders);
} else {
$ph = '';
}
$str = "Yii::t('" . $this->messageCategory . "', '" . $string . "'" . $ph . ")";
} else {
// No I18N, replace placeholders by real words, if any
if (!empty($placeholders)) {
$phKeys = array_map(function($word) {
return '{' . $word . '}';
}, array_keys($placeholders));
$phValues = array_values($placeholders);
$str = "'" . str_replace($phKeys, $phValues, $string) . "'";
} else {
// No placeholders, just the given string
$str = "'" . $string . "'";
}
}
return $str;
}
Generates URL parameters
public string generateUrlParams ( ) |
public function generateUrlParams()
{
/* @var $class ActiveRecord */
$class = $this->modelClass;
$pks = $class::primaryKey();
if (count($pks) === 1) {
if (is_subclass_of($class, 'yii\mongodb\ActiveRecord')) {
return "'id' => (string)\$model->{$pks[0]}";
}
return "'id' => \$model->{$pks[0]}";
}
$params = [];
foreach ($pks as $pk) {
if (is_subclass_of($class, 'yii\mongodb\ActiveRecord')) {
$params[] = "'$pk' => (string)\$model->$pk";
} else {
$params[] = "'$pk' => \$model->$pk";
}
}
return implode(', ', $params);
}
protected string|null getClassDbDriverName ( ) | ||
return | string|null |
Driver name of modelClass db connection. In case db is not instance of \yii\db\Connection null will be returned. |
---|
protected function getClassDbDriverName()
{
/* @var $class ActiveRecord */
$class = $this->modelClass;
$db = $class::getDb();
return $db instanceof \yii\db\Connection ? $db->driverName : null;
}
public array getColumnNames ( ) | ||
return | array |
Model column names |
---|
public function getColumnNames()
{
/* @var $class ActiveRecord */
$class = $this->modelClass;
if (is_subclass_of($class, 'yii\db\ActiveRecord')) {
return $class::getTableSchema()->getColumnNames();
}
/* @var $model \yii\base\Model */
$model = new $class();
return $model->attributes();
}
public string getControllerID ( ) | ||
return | string |
The controller ID (without the module ID prefix) |
---|
public function getControllerID()
{
$pos = strrpos($this->controllerClass, '\\');
$class = substr(substr($this->controllerClass, $pos + 1), 0, -10);
return Inflector::camel2id($class);
}
public string getDescription ( ) | ||
return | string |
The detailed description of the generator. |
---|
public function getDescription()
{
return 'This generator generates a controller and views that implement CRUD (Create, Read, Update, Delete)
operations for the specified data model.';
}
public string getName ( ) | ||
return | string |
Name of the code generator |
---|
public function getName()
{
return 'CRUD Generator';
}
public string getNameAttribute ( ) |
public function getNameAttribute()
{
foreach ($this->getColumnNames() as $name) {
if (!strcasecmp($name, 'name') || !strcasecmp($name, 'title')) {
return $name;
}
}
/* @var $class \yii\db\ActiveRecord */
$class = $this->modelClass;
$pk = $class::primaryKey();
return $pk[0];
}
public array getSearchAttributes ( ) | ||
return | array |
Searchable attributes |
---|
public function getSearchAttributes()
{
return $this->getColumnNames();
}
Returns table schema for current model class or false if it is not an active record
public boolean|\yii\db\TableSchema getTableSchema ( ) |
public function getTableSchema()
{
/* @var $class ActiveRecord */
$class = $this->modelClass;
if (is_subclass_of($class, 'yii\db\ActiveRecord')) {
return $class::getTableSchema();
}
return false;
}
Defined in: yii\gii\Generator::getTemplatePath()
public string getTemplatePath ( ) | ||
return | string |
The root path of the template files that are currently being used. |
---|---|---|
throws | \yii\base\InvalidConfigException |
if $template is invalid |
public function getTemplatePath()
{
if (isset($this->templates[$this->template])) {
return $this->templates[$this->template];
}
throw new InvalidConfigException("Unknown template: {$this->template}");
}
public string getViewPath ( ) | ||
return | string |
The controller view path |
---|
public function getViewPath()
{
if (empty($this->viewPath)) {
return Yii::getAlias('@app/views/' . $this->getControllerID());
}
return Yii::getAlias(str_replace('\\', '/', $this->viewPath));
}
Returns the list of hint messages.
The array keys are the attribute names, and the array values are the corresponding hint messages. Hint messages will be displayed to end users when they are filling the form for the generator.
public array hints ( ) | ||
return | array |
The list of hint messages |
---|
public function hints()
{
return array_merge(parent::hints(), [
'modelClass' => 'This is the ActiveRecord class associated with the table that CRUD will be built upon.
You should provide a fully qualified class name, e.g., <code>app\models\Post</code>.',
'controllerClass' => 'This is the name of the controller class to be generated. You should
provide a fully qualified namespaced class (e.g. <code>app\controllers\PostController</code>),
and class name should be in CamelCase with an uppercase first letter. Make sure the class
is using the same namespace as specified by your application\'s controllerNamespace property.',
'viewPath' => 'Specify the directory for storing the view scripts for the controller. You may use path alias here, e.g.,
<code>/var/www/basic/controllers/views/post</code>, <code>@app/views/post</code>. If not set, it will default
to <code>@app/views/ControllerID</code>',
'baseControllerClass' => 'This is the class that the new CRUD controller class will extend from.
You should provide a fully qualified class name, e.g., <code>yii\web\Controller</code>.',
'indexWidgetType' => 'This is the widget type to be used in the index page to display list of the models.
You may choose either <code>GridView</code> or <code>ListView</code>',
'searchModelClass' => 'This is the name of the search model class to be generated. You should provide a fully
qualified namespaced class name, e.g., <code>app\models\PostSearch</code>.',
'enablePjax' => 'This indicates whether the generator should wrap the <code>GridView</code> or <code>ListView</code>
widget on the index page with <code>yii\widgets\Pjax</code> widget. Set this to <code>true</code> if you want to get
sorting, filtering and pagination without page refreshing.',
]);
}
Defined in: yii\gii\Generator::init()
public void init ( ) |
public function init()
{
parent::init();
if (!isset($this->templates['default'])) {
$this->templates['default'] = $this->defaultTemplate();
}
foreach ($this->templates as $i => $template) {
$this->templates[$i] = Yii::getAlias($template);
}
}
Defined in: yii\gii\Generator::isReservedKeyword()
public boolean isReservedKeyword ( $value ) | ||
$value | string |
The attribute to be validated |
return | boolean |
Whether the value is a reserved PHP keyword. |
---|
public function isReservedKeyword($value)
{
static $keywords = [
'__class__',
'__dir__',
'__file__',
'__function__',
'__line__',
'__method__',
'__namespace__',
'__trait__',
'abstract',
'and',
'array',
'as',
'break',
'case',
'catch',
'callable',
'cfunction',
'class',
'clone',
'const',
'continue',
'declare',
'default',
'die',
'do',
'echo',
'else',
'elseif',
'empty',
'enddeclare',
'endfor',
'endforeach',
'endif',
'endswitch',
'endwhile',
'eval',
'exception',
'exit',
'extends',
'final',
'finally',
'for',
'foreach',
'function',
'global',
'goto',
'if',
'implements',
'include',
'include_once',
'instanceof',
'insteadof',
'interface',
'isset',
'list',
'namespace',
'new',
'old_function',
'or',
'parent',
'php_user_filter',
'print',
'private',
'protected',
'public',
'require',
'require_once',
'return',
'static',
'switch',
'this',
'throw',
'trait',
'try',
'unset',
'use',
'var',
'while',
'xor',
];
return in_array(strtolower($value), $keywords, true);
}
Defined in: yii\gii\Generator::render()
Generates code using the specified code template and parameters.
Note that the code template will be used as a PHP file.
public string render ( $template, $params = [] ) | ||
$template | string |
The code template file. This must be specified as a file path relative to $templatePath. |
$params | array |
List of parameters to be passed to the template file. |
return | string |
The generated code |
---|
public function render($template, $params = [])
{
$view = new View();
$params['generator'] = $this;
return $view->renderFile($this->getTemplatePath() . '/' . $template, $params, $this);
}
Returns a list of code template files that are required.
Derived classes usually should override this method if they require the existence of certain template files.
public array requiredTemplates ( ) | ||
return | array |
List of code template files that are required. They should be file paths relative to $templatePath. |
---|
public function requiredTemplates()
{
return ['controller.php'];
}
Child classes should override this method like the following so that the parent rules are included:
return array_merge(parent::rules(), [
...rules for the child class...
]);
public void rules ( ) |
public function rules()
{
return array_merge(parent::rules(), [
[['controllerClass', 'modelClass', 'searchModelClass', 'baseControllerClass'], 'filter', 'filter' => 'trim'],
[['modelClass', 'controllerClass', 'baseControllerClass', 'indexWidgetType'], 'required'],
[['searchModelClass'], 'compare', 'compareAttribute' => 'modelClass', 'operator' => '!==', 'message' => 'Search Model Class must not be equal to Model Class.'],
[['modelClass', 'controllerClass', 'baseControllerClass', 'searchModelClass'], 'match', 'pattern' => '/^[\w\\\\]*$/', 'message' => 'Only word characters and backslashes are allowed.'],
[['modelClass'], 'validateClass', 'params' => ['extends' => BaseActiveRecord::className()]],
[['baseControllerClass'], 'validateClass', 'params' => ['extends' => Controller::className()]],
[['controllerClass'], 'match', 'pattern' => '/Controller$/', 'message' => 'Controller class name must be suffixed with "Controller".'],
[['controllerClass'], 'match', 'pattern' => '/(^|\\\\)[A-Z][^\\\\]+Controller$/', 'message' => 'Controller class name must start with an uppercase letter.'],
[['controllerClass', 'searchModelClass'], 'validateNewClass'],
[['indexWidgetType'], 'in', 'range' => ['grid', 'list']],
[['modelClass'], 'validateModelClass'],
[['enableI18N', 'enablePjax'], 'boolean'],
[['messageCategory'], 'validateMessageCategory', 'skipOnEmpty' => false],
['viewPath', 'safe'],
]);
}
Defined in: yii\gii\Generator::save()
Saves the generated code into files.
public boolean save ( $files, $answers, &$results ) | ||
$files | yii\gii\CodeFile[] |
The code files to be saved |
$answers | array | |
$results | string |
This parameter receives a value from this method indicating the log messages generated while saving the code files. |
return | boolean |
Whether files are successfully saved without any error. |
---|
public function save($files, $answers, &$results)
{
$lines = ['Generating code using template "' . $this->getTemplatePath() . '"...'];
$hasError = false;
foreach ($files as $file) {
$relativePath = $file->getRelativePath();
if (isset($answers[$file->id]) && !empty($answers[$file->id]) && $file->operation !== CodeFile::OP_SKIP) {
$error = $file->save();
if (is_string($error)) {
$hasError = true;
$lines[] = "generating $relativePath\n<span class=\"error\">$error</span>";
} else {
$lines[] = $file->operation === CodeFile::OP_CREATE ? " generated $relativePath" : " overwrote $relativePath";
}
} else {
$lines[] = " skipped $relativePath";
}
}
$lines[] = "done!\n";
$results = implode("\n", $lines);
return !$hasError;
}
Returns the list of sticky attributes.
A sticky attribute will remember its value and will initialize the attribute with this value when the generator is restarted.
public array stickyAttributes ( ) | ||
return | array |
List of sticky attributes |
---|
public function stickyAttributes()
{
return array_merge(parent::stickyAttributes(), ['baseControllerClass', 'indexWidgetType']);
}
Defined in: yii\gii\Generator::successMessage()
Returns the message to be displayed when the newly generated code is saved successfully.
Child classes may override this method to customize the message.
public string successMessage ( ) | ||
return | string |
The message to be displayed when the newly generated code is saved successfully. |
---|
public function successMessage()
{
return 'The code has been generated successfully.';
}
Defined in: yii\gii\Generator::validateClass()
An inline validator that checks if the attribute value refers to an existing class name.
If the extends
option is specified, it will also check if the class is a child class
of the class represented by the extends
option.
public void validateClass ( $attribute, $params ) | ||
$attribute | string |
The attribute being validated |
$params | array |
The validation options |
public function validateClass($attribute, $params)
{
$class = $this->$attribute;
try {
if (class_exists($class)) {
if (isset($params['extends'])) {
if (ltrim($class, '\\') !== ltrim($params['extends'], '\\') && !is_subclass_of($class, $params['extends'])) {
$this->addError($attribute, "'$class' must extend from {$params['extends']} or its child class.");
}
}
} else {
$this->addError($attribute, "Class '$class' does not exist or has syntax error.");
}
} catch (\Exception $e) {
$this->addError($attribute, "Class '$class' does not exist or has syntax error.");
}
}
Defined in: yii\gii\Generator::validateMessageCategory()
Checks if message category is not empty when I18N is enabled.
public void validateMessageCategory ( ) |
public function validateMessageCategory()
{
if ($this->enableI18N && empty($this->messageCategory)) {
$this->addError('messageCategory', "Message Category cannot be blank.");
}
}
Checks if model class is valid
public void validateModelClass ( ) |
public function validateModelClass()
{
/* @var $class ActiveRecord */
$class = $this->modelClass;
$pk = $class::primaryKey();
if (empty($pk)) {
$this->addError('modelClass', "The table associated with $class must have primary key(s).");
}
}
Defined in: yii\gii\Generator::validateNewClass()
An inline validator that checks if the attribute value refers to a valid namespaced class name.
The validator will check if the directory containing the new class file exist or not.
public void validateNewClass ( $attribute, $params ) | ||
$attribute | string |
The attribute being validated |
$params | array |
The validation options |
public function validateNewClass($attribute, $params)
{
$class = ltrim($this->$attribute, '\\');
if (($pos = strrpos($class, '\\')) === false) {
$this->addError($attribute, "The class name must contain fully qualified namespace name.");
} else {
$ns = substr($class, 0, $pos);
$path = Yii::getAlias('@' . str_replace('\\', '/', $ns), false);
if ($path === false) {
$this->addError($attribute, "The class namespace is invalid: $ns");
} elseif (!is_dir($path)) {
$this->addError($attribute, "Please make sure the directory containing this class exists: $path");
}
}
}
Defined in: yii\gii\Generator::validateTemplate()
Validates the template selection.
This method validates whether the user selects an existing template and the template contains all required template files as specified in requiredTemplates().
public void validateTemplate ( ) |
public function validateTemplate()
{
$templates = $this->templates;
if (!isset($templates[$this->template])) {
$this->addError('template', 'Invalid template selection.');
} else {
$templatePath = $this->templates[$this->template];
foreach ($this->requiredTemplates() as $template) {
if (!is_file(Yii::getAlias($templatePath . '/' . $template))) {
$this->addError('template', "Unable to find the required code template file '$template'.");
}
}
}
}