Class yii\gii\generators\module\Generator
Inheritance | yii\gii\generators\module\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/module/Generator.php |
This generator will generate the skeleton code needed by a module.
Public Properties
Property | Type | Description | Defined By |
---|---|---|---|
$controllerNamespace | string | The controller namespace of the module. | yii\gii\generators\module\Generator |
$description | string | The detailed description of the generator. | yii\gii\Generator |
$enableI18N | boolean | Whether the strings will be generated using Yii::t() or PHP strings. |
yii\gii\Generator |
$messageCategory | string | The message category used by Yii::t() when $enableI18N is true , defaults to app . |
yii\gii\Generator |
$moduleClass | string | yii\gii\generators\module\Generator | |
$moduleID | string | yii\gii\generators\module\Generator | |
$modulePath | string | The directory that contains the module class. | yii\gii\generators\module\Generator |
$name | string | The name of the generator. | yii\gii\Generator |
$stickyDataFile | string | The file path that stores the sticky attribute values. | yii\gii\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 |
Public Methods
Method | Description | Defined By |
---|---|---|
attributeLabels() | yii\gii\generators\module\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\module\Generator |
generateString() | Generates a string depending on the $enableI18N property |
yii\gii\Generator |
getControllerNamespace() | yii\gii\generators\module\Generator | |
getDescription() | Returns the detailed description of the generator. | yii\gii\generators\module\Generator |
getModulePath() | yii\gii\generators\module\Generator | |
getName() | Returns the name of the code generator. | yii\gii\generators\module\Generator |
getStickyDataFile() | Returns the file path that stores the sticky attribute values. | yii\gii\Generator |
getTemplatePath() | yii\gii\Generator | |
hints() | Returns the list of hint messages. | yii\gii\generators\module\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\module\Generator |
rules() | yii\gii\generators\module\Generator | |
save() | Saves the generated code into files. | yii\gii\Generator |
stickyAttributes() | Returns the list of sticky attributes. | yii\gii\Generator |
successMessage() | Returns the message to be displayed when the newly generated code is saved successfully. | yii\gii\generators\module\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 |
validateModuleClass() | Validates $moduleClass to make sure it is a fully qualified class name. | yii\gii\generators\module\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 |
Property Details
The controller namespace of the module.
The directory that contains the module class.
Method Details
public void attributeLabels ( ) |
public function attributeLabels()
{
return array_merge(
parent::attributeLabels(),
[
'moduleID' => 'Module ID',
'moduleClass' => 'Module Class',
]
);
}
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.
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()
{
$files = [];
$modulePath = $this->getModulePath();
$files[] = new CodeFile(
$modulePath . '/' . StringHelper::basename($this->moduleClass) . '.php',
$this->render("module.php")
);
$files[] = new CodeFile(
$modulePath . '/controllers/DefaultController.php',
$this->render("controller.php")
);
$files[] = new CodeFile(
$modulePath . '/views/default/index.php',
$this->render("view.php")
);
return $files;
}
Defined in: yii\gii\Generator::generateString()
Generates a string depending on the $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;
}
public string getControllerNamespace ( ) | ||
return | string |
The controller namespace of the module. |
---|
public function getControllerNamespace()
{
return substr($this->moduleClass, 0, strrpos($this->moduleClass, '\\')) . '\controllers';
}
Returns the detailed description of the generator.
public string getDescription ( ) |
public function getDescription()
{
return 'This generator helps you to generate the skeleton code needed by a Yii module.';
}
public string getModulePath ( ) | ||
return | string |
The directory that contains the module class |
---|
public function getModulePath()
{
return Yii::getAlias('@' . str_replace('\\', '/', substr($this->moduleClass, 0, strrpos($this->moduleClass, '\\'))));
}
Returns the name of the code generator.
public string getName ( ) |
public function getName()
{
return 'Module Generator';
}
Defined in: yii\gii\Generator::getStickyDataFile()
Returns the file path that stores the sticky attribute values.
public string getStickyDataFile ( ) |
public function getStickyDataFile()
{
return Yii::$app->getRuntimePath() . '/gii-' . Yii::getVersion() . '/' . str_replace('\\', '-', get_class($this)) . '.json';
}
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}");
}
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(),
[
'moduleID' => 'This refers to the ID of the module, e.g., <code>admin</code>.',
'moduleClass' => 'This is the fully qualified class name of the module, e.g., <code>app\modules\admin\Module</code>.',
]
);
}
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',
'fn',
'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',
'yield'
];
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 ['module.php', 'controller.php', 'view.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(), [
[['moduleID', 'moduleClass'], 'trim'],
[['moduleID', 'moduleClass'], 'required'],
[['moduleID'], 'match', 'pattern' => '/^[\w\\-]+$/', 'message' => 'Only word characters, slashes and dashes are allowed.'],
[['moduleClass'], 'match', 'pattern' => '/^[\w\\\\]+$/', 'message' => 'Only word characters and backslashes are allowed.'],
[['moduleClass'], 'validateModuleClass'],
]);
}
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;
}
Defined in: yii\gii\Generator::stickyAttributes()
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 ['template', 'enableI18N', 'messageCategory'];
}
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()
{
if (Yii::$app->hasModule($this->moduleID)) {
$link = Html::a('try it now', Yii::$app->getUrlManager()->createUrl($this->moduleID), ['target' => '_blank']);
return "The module has been generated successfully. You may $link.";
}
$output = <<<EOD
he module has been generated successfully.</p>
o access the module, you need to add this to your application configuration:</p>
$code = <<<EOD
p
......
'modules' => [
'{$this->moduleID}' => [
'class' => '{$this->moduleClass}',
],
],
......
return $output . '<pre>' . highlight_string($code, true) . '</pre>';
}
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) {
if (empty($this->messageCategory)) {
$this->addError('messageCategory', 'Message Category cannot be blank.');
} elseif (!preg_match('~^[\w./-]+$~', $this->messageCategory)) {
$this->addError('messageCategory', 'Message Category is not valid. It should contain only alphanumeric characters, ".", "-", "/", and "_".');
}
}
}
Validates $moduleClass to make sure it is a fully qualified class name.
public void validateModuleClass ( ) |
public function validateModuleClass()
{
if (empty($this->moduleClass) || substr_compare($this->moduleClass, '\\', -1, 1) === 0) {
$this->addError('moduleClass', 'Module class name must not be empty. Please enter a fully qualified class name. e.g. "app\modules\admin\Module".');
}
if (strpos($this->moduleClass, '\\') === false || Yii::getAlias('@' . str_replace('\\', '/', $this->moduleClass), false) === false) {
$this->addError('moduleClass', 'Module class must be properly namespaced.');
}
}
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'.");
}
}
}
}