Class yii\gii\generators\extension\Generator

Inheritanceyii\gii\generators\extension\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/extension/Generator.php

This generator will generate the skeleton files needed by an extension.

Public Methods

Hide inherited methods

Method Description Defined By
attributeLabels() yii\gii\generators\extension\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\extension\Generator
generateString() Generates a string depending on enableI18N property yii\gii\Generator
getDescription() yii\gii\generators\extension\Generator
getKeywordsArrayJson() yii\gii\generators\extension\Generator
getName() yii\gii\generators\extension\Generator
getOutputPath() yii\gii\generators\extension\Generator
getTemplatePath() yii\gii\Generator
hints() Returns the list of hint messages. yii\gii\generators\extension\Generator
init() yii\gii\Generator
isReservedKeyword() yii\gii\Generator
optsLicense() yii\gii\generators\extension\Generator
optsType() yii\gii\generators\extension\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\extension\Generator
rules() yii\gii\generators\extension\Generator
save() Saves the generated code into files. yii\gii\Generator
stickyAttributes() Returns the list of sticky attributes. yii\gii\generators\extension\Generator
successMessage() Returns the message to be displayed when the newly generated code is saved successfully. yii\gii\generators\extension\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
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

Hide inherited properties

$authorEmail public property
public $authorEmail null
$authorName public property
public $authorName null
$description public property
public $description null
$keywords public property
public $keywords "yii2,extension"
$keywordsArrayJson public property

A json encoded array with the given keywords. This property is read-only.

public string $keywordsArrayJson null
$license public property
public $license null
$namespace public property
public $namespace null
$outputPath public property
public $outputPath "@app/runtime/tmp-extensions"
$packageName public property
public $packageName "yii2-"
$title public property
public $title null
$type public property
public $type "yii2-extension"
$vendorName public property
public $vendorName null

Method Details

Hide inherited methods

attributeLabels() public method

public void attributeLabels ( )

                public function attributeLabels()
{
    return [
        'vendorName'  => 'Vendor Name',
        'packageName' => 'Package Name',
        'license'     => 'License',
    ];
}

            
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()
{
    $files = [];
    $modulePath = $this->getOutputPath();
    $files[] = new CodeFile(
        $modulePath . '/' . $this->packageName . '/composer.json',
        $this->render("composer.json")
    );
    $files[] = new CodeFile(
        $modulePath . '/' . $this->packageName . '/AutoloadExample.php',
        $this->render("AutoloadExample.php")
    );
    $files[] = new CodeFile(
        $modulePath . '/' . $this->packageName . '/README.md',
        $this->render("README.md")
    );
    return $files;
}

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

            
getDescription() public method

public string getDescription ( )
return string

The detailed description of the generator.

                public function getDescription()
{
    return 'This generator helps you to generate the files needed by a Yii extension.';
}

            
getKeywordsArrayJson() public method

public string getKeywordsArrayJson ( )
return string

A json encoded array with the given keywords

                public function getKeywordsArrayJson()
{
    return json_encode(explode(',', $this->keywords), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
}

            
getName() public method

public string getName ( )
return string

Name of the code generator

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

            
getOutputPath() public method

public boolean getOutputPath ( )
return boolean

The directory that contains the module class

                public function getOutputPath()
{
    return Yii::getAlias(str_replace('\\', '/', $this->outputPath));
}

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

            
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 [
        'vendorName'  => 'This refers to the name of the publisher, your GitHub user name is usually a good choice, eg. <code>myself</code>.',
        'packageName' => 'This is the name of the extension on packagist, eg. <code>yii2-foobar</code>.',
        'namespace'   => 'PSR-4, eg. <code>myself\foobar\</code> This will be added to your autoloading by composer. Do not use yii, yii2 or yiisoft in the namespace.',
        'keywords'    => 'Comma separated keywords for this extension.',
        'outputPath'  => 'The temporary location of the generated files.',
        'title'       => 'A more descriptive name of your application for the README file.',
        'description' => 'A sentence or subline describing the main purpose of the extension.',
    ];
}

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

            
optsLicense() public method

public array optsLicense ( )
return array

Options for license drop-down

                public function optsLicense()
{
    $licenses = [
        'Apache-2.0',
        'BSD-2-Clause',
        'BSD-3-Clause',
        'BSD-4-Clause',
        'GPL-2.0',
        'GPL-2.0+',
        'GPL-3.0',
        'GPL-3.0+',
        'LGPL-2.1',
        'LGPL-2.1+',
        'LGPL-3.0',
        'LGPL-3.0+',
        'MIT'
    ];
    return array_combine($licenses, $licenses);
}

            
optsType() public method

public array optsType ( )
return array

Options for type drop-down

                public function optsType()
{
    $licenses = [
        'yii2-extension',
        'library',
    ];
    return array_combine($licenses, $licenses);
}

            
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 ['composer.json', 'AutoloadExample.php', 'README.md'];
}

            
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(),
        [
            [['vendorName', 'packageName'], 'filter', 'filter' => 'trim'],
            [
                [
                    'vendorName',
                    'packageName',
                    'namespace',
                    'type',
                    'license',
                    'title',
                    'description',
                    'authorName',
                    'authorEmail',
                    'outputPath'
                ],
                'required'
            ],
            [['keywords'], 'safe'],
            [['authorEmail'], 'email'],
            [
                ['vendorName', 'packageName'],
                'match',
                'pattern' => '/^[a-z0-9\-\.]+$/',
                'message' => 'Only lowercase word characters, dashes and dots are allowed.'
            ],
            [
                ['namespace'],
                'match',
                'pattern' => '/^[a-zA-Z0-9_\\\]+\\\$/',
                'message' => 'Only letters, numbers, underscores and backslashes are allowed. PSR-4 namespaces must end with a namespace separator.'
            ],
        ]
    );
}

            
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 ['vendorName', 'outputPath', 'authorName', 'authorEmail'];
}

            
successMessage() public method

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()
{
    $outputPath = realpath(\Yii::getAlias($this->outputPath));
    $output1 = <<<EOD
em>The extension has been generated successfully.</em></p>
o enable it in your application, you need to create a git repository
require it via composer.</p>

    $code1 = <<<EOD
$outputPath}/{$this->packageName}
init
add -A
commit
remote add origin https://path.to/your/repo
push -u origin master

    $output2 = <<<EOD
he next step is just for <em>initial development</em>, skip it if you directly publish the extension on packagist.org</p>
dd the newly created repo to your composer.json.</p>

    $code2 = <<<EOD
ositories":[
{
    "type": "git",
    "url": "https://path.to/your/repo"
}

    $output3 = <<<EOD
lass="well">Note: You may use the url <code>file://{$outputPath}/{$this->packageName}</code> for testing.</p>
equire the package with composer</p>

    $code3 = <<<EOD
oser.phar require {$this->vendorName}/{$this->packageName}:dev-master

    $output4 = <<<EOD
nd use it in your application.</p>

    $code4 = <<<EOD
this->namespace}AutoloadExample::widget();

    $output5 = <<<EOD
hen you have finished development register your extension at <a href='https://packagist.org/' target='_blank'>packagist.org</a>.</p>

    $return = $output1 . '<pre>' . highlight_string($code1, true) . '</pre>';
    $return .= $output2 . '<pre>' . highlight_string($code2, true) . '</pre>';
    $return .= $output3 . '<pre>' . highlight_string($code3, true) . '</pre>';
    $return .= $output4 . '<pre>' . highlight_string($code4, true) . '</pre>';
    $return .= $output5;
    return $return;
}

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

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