Class yii\gii\generators\crud\Generator

Inheritanceyii\gii\generators\crud\Generator » yii\gii\Generator » yii\base\Model
Available since extension's version2.0
Source Code https://github.com/yiisoft/yii2-gii/blob/master/src/generators/crud/Generator.php

Generates CRUD

Public Properties

Hide inherited properties

Property Type Description Defined By
$baseControllerClass yii\gii\generators\crud\Generator
$columnNames array Model column names. yii\gii\generators\crud\Generator
$controllerClass yii\gii\generators\crud\Generator
$controllerID string The controller ID (without the module ID prefix). yii\gii\generators\crud\Generator
$description string The detailed description of the generator. yii\gii\Generator
$enableI18N boolean Whether the strings will be generated using Yii::t() or normal strings. yii\gii\Generator
$enablePjax boolean Whether to wrap the GridView or ListView widget with the yii\widgets\Pjax widget yii\gii\generators\crud\Generator
$indexWidgetType yii\gii\generators\crud\Generator
$messageCategory string The message category used by Yii::t() when $enableI18N is true. yii\gii\Generator
$modelClass yii\gii\generators\crud\Generator
$nameAttribute string This property is read-only. yii\gii\generators\crud\Generator
$searchAttributes array Searchable attributes. yii\gii\generators\crud\Generator
$searchModelClass yii\gii\generators\crud\Generator
$stickyDataFile string The file path that stores the sticky attribute values. yii\gii\Generator
$tableSchema boolean|\yii\db\TableSchema This property is read-only. yii\gii\generators\crud\Generator
$template string The name of the code template that the user has selected. yii\gii\Generator
$templatePath string The root path of the template files that are currently being used. yii\gii\Generator
$templates array A list of available code templates. yii\gii\Generator
$viewPath yii\gii\generators\crud\Generator

Public Methods

Hide inherited methods

Method Description Defined By
attributeLabels() yii\gii\generators\crud\Generator
autoCompleteData() Returns the list of auto complete values. yii\gii\Generator
defaultTemplate() Returns the root path to the default code template files. yii\gii\Generator
formView() Returns the view file for the input form of the generator. yii\gii\Generator
generate() Generates the code based on the current user input and the specified code template files. yii\gii\generators\crud\Generator
generateActionParamComments() Generates parameter tags for phpdoc yii\gii\generators\crud\Generator
generateActionParams() Generates action parameters yii\gii\generators\crud\Generator
generateActiveField() Generates code for active field yii\gii\generators\crud\Generator
generateActiveSearchField() Generates code for active search field yii\gii\generators\crud\Generator
generateColumnFormat() Generates column format yii\gii\generators\crud\Generator
generateSearchConditions() Generates search conditions yii\gii\generators\crud\Generator
generateSearchLabels() Generates the attribute labels for the search model. yii\gii\generators\crud\Generator
generateSearchRules() Generates validation rules for the search model. yii\gii\generators\crud\Generator
generateString() Generates a string depending on enableI18N property yii\gii\Generator
generateUrlParams() Generates URL parameters yii\gii\generators\crud\Generator
getColumnNames() yii\gii\generators\crud\Generator
getControllerID() yii\gii\generators\crud\Generator
getDescription() yii\gii\generators\crud\Generator
getName() yii\gii\generators\crud\Generator
getNameAttribute() yii\gii\generators\crud\Generator
getSearchAttributes() yii\gii\generators\crud\Generator
getTableSchema() Returns table schema for current model class or false if it is not an active record yii\gii\generators\crud\Generator
getTemplatePath() yii\gii\Generator
getViewPath() yii\gii\generators\crud\Generator
hints() Returns the list of hint messages. yii\gii\generators\crud\Generator
init() yii\gii\Generator
isReservedKeyword() yii\gii\Generator
render() Generates code using the specified code template and parameters. yii\gii\Generator
requiredTemplates() Returns a list of code template files that are required. yii\gii\generators\crud\Generator
rules() yii\gii\generators\crud\Generator
save() Saves the generated code into files. yii\gii\Generator
stickyAttributes() Returns the list of sticky attributes. yii\gii\generators\crud\Generator
successMessage() Returns the message to be displayed when the newly generated code is saved successfully. yii\gii\Generator
validateClass() An inline validator that checks if the attribute value refers to an existing class name. yii\gii\Generator
validateMessageCategory() Checks if message category is not empty when I18N is enabled. yii\gii\Generator
validateModelClass() Checks if model class is valid yii\gii\generators\crud\Generator
validateNewClass() An inline validator that checks if the attribute value refers to a valid namespaced class name. yii\gii\Generator
validateTemplate() Validates the template selection. yii\gii\Generator

Protected Methods

Hide inherited methods

Method Description Defined By
getClassDbDriverName() yii\gii\generators\crud\Generator

Property Details

Hide inherited properties

$baseControllerClass public property
public $baseControllerClass 'yii\web\Controller'
$columnNames public property

Model column names. This property is read-only.

public array $columnNames null
$controllerClass public property
public $controllerClass null
$controllerID public property

The controller ID (without the module ID prefix). This property is read-only.

public string $controllerID null
$enablePjax public property (available since version 2.0.5)

Whether to wrap the GridView or ListView widget with the yii\widgets\Pjax widget

public boolean $enablePjax false
$indexWidgetType public property
public $indexWidgetType 'grid'
$modelClass public property
public $modelClass null
$nameAttribute public property

This property is read-only.

public string $nameAttribute null
$searchAttributes public property

Searchable attributes. This property is read-only.

public array $searchAttributes null
$searchModelClass public property
public $searchModelClass ''
$tableSchema public property

This property is read-only.

public boolean|\yii\db\TableSchema $tableSchema null
$viewPath public property
public $viewPath null

Method Details

Hide inherited methods

attributeLabels() public method

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',
    ]);
}

            
autoCompleteData() public method

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 [];
}

            
defaultTemplate() public method

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';
}

            
formView() public method

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';
}

            
generate() public method

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;
}

            
generateActionParamComments() public method

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;
}

            
generateActionParams() public method

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);
}

            
generateActiveField() public method

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])";
}

            
generateActiveSearchField() public method

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')";
}

            
generateColumnFormat() public method

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';
}

            
generateSearchConditions() public method

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;
}

            
generateSearchLabels() public method

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;
}

            
generateSearchRules() public method

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;
}

            
generateString() public method

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 Yii::t()

                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;
}

            
generateUrlParams() public method

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);
}

            
getClassDbDriverName() protected method (available since version 2.0.6)

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;
}

            
getColumnNames() public method

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();
}

            
getControllerID() public method

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);
}

            
getDescription() public method

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.';
}

            
getName() public method

public string getName ( )
return string

Name of the code generator

                public function getName()
{
    return 'CRUD Generator';
}

            
getNameAttribute() public method

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];
}

            
getSearchAttributes() public method

public array getSearchAttributes ( )
return array

Searchable attributes

                public function getSearchAttributes()
{
    return $this->getColumnNames();
}

            
getTableSchema() public method

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;
}

            
getTemplatePath() public method
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}");
}

            
getViewPath() public method

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));
}

            
hints() public method

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.',
    ]);
}

            
init() public method
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);
    }
}

            
isReservedKeyword() public method
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);
}

            
render() public method

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);
}

            
requiredTemplates() public method

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'];
}

            
rules() public method

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'],
    ]);
}

            
save() public method

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;
}

            
stickyAttributes() public method

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']);
}

            
successMessage() public method

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.';
}

            
validateClass() public method

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.");
    }
}

            
validateMessageCategory() public method

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.");
    }
}

            
validateModelClass() public method

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).");
    }
}

            
validateNewClass() public method

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");
        }
    }
}

            
validateTemplate() public method

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'.");
            }
        }
    }
}