Generator.php 12.5 KB
Newer Older
Qiang Xue committed
1 2 3 4 5 6 7 8 9 10
<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\gii;

use Yii;
Qiang Xue committed
11 12
use ReflectionClass;
use yii\base\InvalidConfigException;
Qiang Xue committed
13
use yii\base\Model;
Alexander Makarov committed
14
use yii\web\View;
Qiang Xue committed
15

Qiang Xue committed
16

Qiang Xue committed
17
/**
18 19 20 21 22 23 24 25 26 27 28 29
 * This is the base class for all generator classes.
 *
 * A generator instance is responsible for taking user inputs, validating them,
 * and using them to generate the corresponding code based on a set of code template files.
 *
 * A generator class typically needs to implement the following methods:
 *
 * - [[getName()]]: returns the name of the generator
 * - [[getDescription()]]: returns the detailed description of the generator
 * - [[generate()]]: generates the code based on the current user input and the specified code template files.
 *   This is the place where main code generation code resides.
 *
30 31 32 33 34
 * @property string $description The detailed description of the generator. This property is read-only.
 * @property string $stickyDataFile The file path that stores the sticky attribute values. This property is
 * read-only.
 * @property string $templatePath The root path of the template files that are currently being used. This
 * property is read-only.
35
 *
Qiang Xue committed
36 37 38
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
Qiang Xue committed
39
abstract class Generator extends Model
Qiang Xue committed
40
{
41 42 43 44
	/**
	 * @var array a list of available code templates. The array keys are the template names,
	 * and the array values are the corresponding template paths or path aliases.
	 */
Alexander Makarov committed
45
	public $templates = [];
Qiang Xue committed
46
	/**
Qiang Xue committed
47
	 * @var string the name of the code template that the user has selected.
48
	 * The value of this property is internally managed by this class.
Qiang Xue committed
49
	 */
Qiang Xue committed
50
	public $template;
Qiang Xue committed
51 52 53 54

	/**
	 * @return string name of the code generator
	 */
Qiang Xue committed
55
	abstract public function getName();
56 57 58 59 60 61 62 63
	/**
	 * 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.
	 * @return CodeFile[] a list of code files to be created.
	 */
	abstract public function generate();
Qiang Xue committed
64

65
	/**
Qiang Xue committed
66
	 * @inheritdoc
67
	 */
Qiang Xue committed
68
	public function init()
Qiang Xue committed
69
	{
Qiang Xue committed
70 71
		parent::init();
		if (!isset($this->templates['default'])) {
Qiang Xue committed
72
			$this->templates['default'] = $this->defaultTemplate();
Qiang Xue committed
73
		}
74 75 76
		foreach ($this->templates as $i => $template) {
			$this->templates[$i] = Yii::getAlias($template);
		}
Qiang Xue committed
77 78
	}

Qiang Xue committed
79
	/**
80 81 82 83 84
	 * 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.
	 * @return array list of code template files that are required. They should be file paths
	 * relative to [[templatePath]].
Qiang Xue committed
85
	 */
86
	public function requiredTemplates()
Qiang Xue committed
87
	{
Alexander Makarov committed
88
		return [];
Qiang Xue committed
89 90
	}

Qiang Xue committed
91
	/**
92 93 94 95
	 * 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.
	 * @return array list of sticky attributes
Qiang Xue committed
96
	 */
Qiang Xue committed
97 98
	public function stickyAttributes()
	{
Alexander Makarov committed
99
		return ['template'];
Qiang Xue committed
100 101
	}

102 103 104 105 106 107
	/**
	 * 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.
	 * @return array the list of hint messages
	 */
Qiang Xue committed
108 109
	public function hints()
	{
Alexander Makarov committed
110
		return [];
Qiang Xue committed
111 112
	}

113 114 115 116 117 118 119 120 121 122 123
	/**
	 * 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.
	 * @return array the list of auto complete values
	 */
	public function autoCompleteData()
	{
		return [];
	}

Qiang Xue committed
124 125
	/**
	 * Returns the message to be displayed when the newly generated code is saved successfully.
126
	 * Child classes may override this method to customize the message.
Qiang Xue committed
127 128 129 130 131 132 133
	 * @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.';
	}

134 135
	/**
	 * Returns the view file for the input form of the generator.
Qiang Xue committed
136 137
	 * The default implementation will return the "form.php" file under the directory
	 * that contains the generator class file.
138 139
	 * @return string the view file for the input form of the generator.
	 */
Qiang Xue committed
140
	public function formView()
Qiang Xue committed
141
	{
Qiang Xue committed
142
		$class = new ReflectionClass($this);
Qiang Xue committed
143
		return dirname($class->getFileName()) . '/form.php';
Qiang Xue committed
144 145
	}

146 147 148 149 150 151
	/**
	 * 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.
	 * @return string the root path to the default code template files.
	 */
Qiang Xue committed
152
	public function defaultTemplate()
Qiang Xue committed
153
	{
Qiang Xue committed
154 155
		$class = new ReflectionClass($this);
		return dirname($class->getFileName()) . '/templates';
Qiang Xue committed
156 157
	}

158 159 160
	/**
	 * @return string the detailed description of the generator.
	 */
Qiang Xue committed
161
	public function getDescription()
Qiang Xue committed
162
	{
Qiang Xue committed
163
		return '';
Qiang Xue committed
164 165 166
	}

	/**
Qiang Xue committed
167
	 * @inheritdoc
168 169 170 171 172
	 *
	 * Child classes should override this method like the following so that the parent
	 * rules are included:
	 *
	 * ~~~
Alexander Makarov committed
173
	 * return array_merge(parent::rules(), [
Qiang Xue committed
174
	 *     ...rules for the child class...
Alexander Makarov committed
175
	 * ]);
176
	 * ~~~
Qiang Xue committed
177 178 179
	 */
	public function rules()
	{
Alexander Makarov committed
180
		return [
181 182
			[['template'], 'required', 'message' => 'A code template must be selected.'],
			[['template'], 'validateTemplate'],
Alexander Makarov committed
183
		];
Qiang Xue committed
184 185 186
	}

	/**
187 188
	 * Loads sticky attributes from an internal file and populates them into the generator.
	 * @internal
Qiang Xue committed
189
	 */
Qiang Xue committed
190
	public function loadStickyAttributes()
Qiang Xue committed
191
	{
Qiang Xue committed
192 193 194 195
		$stickyAttributes = $this->stickyAttributes();
		$attributes[] = 'template';
		$path = $this->getStickyDataFile();
		if (is_file($path)) {
Qiang Xue committed
196
			$result = json_decode(file_get_contents($path), true);
Qiang Xue committed
197 198 199 200 201 202
			if (is_array($result)) {
				foreach ($stickyAttributes as $name) {
					if (isset($result[$name])) {
						$this->$name = $result[$name];
					}
				}
Qiang Xue committed
203 204 205 206 207
			}
		}
	}

	/**
208 209
	 * Saves sticky attributes into an internal file.
	 * @internal
Qiang Xue committed
210
	 */
Qiang Xue committed
211
	public function saveStickyAttributes()
Qiang Xue committed
212
	{
Qiang Xue committed
213 214
		$stickyAttributes = $this->stickyAttributes();
		$stickyAttributes[] = 'template';
Alexander Makarov committed
215
		$values = [];
Qiang Xue committed
216 217
		foreach ($stickyAttributes as $name) {
			$values[$name] = $this->$name;
Qiang Xue committed
218
		}
Qiang Xue committed
219 220
		$path = $this->getStickyDataFile();
		@mkdir(dirname($path), 0755, true);
Qiang Xue committed
221
		file_put_contents($path, json_encode($values));
Qiang Xue committed
222 223 224
	}

	/**
Qiang Xue committed
225
	 * @return string the file path that stores the sticky attribute values.
226
	 * @internal
Qiang Xue committed
227
	 */
Qiang Xue committed
228
	public function getStickyDataFile()
Qiang Xue committed
229
	{
Qiang Xue committed
230
		return Yii::$app->getRuntimePath() . '/gii-' . Yii::getVersion() . '/' . str_replace('\\', '-', get_class($this)) . '.json';
Qiang Xue committed
231 232 233
	}

	/**
Qiang Xue committed
234
	 * Saves the generated code into files.
235
	 * @param CodeFile[] $files the code files to be saved
Qiang Xue committed
236
	 * @param array $answers
237 238 239
	 * @param string $results this parameter receives a value from this method indicating the log messages
	 * generated while saving the code files.
	 * @return boolean whether there is any error while saving the code files.
Qiang Xue committed
240
	 */
241
	public function save($files, $answers, &$results)
Qiang Xue committed
242
	{
Alexander Makarov committed
243
		$lines = ['Generating code using template "' . $this->getTemplatePath() . '"...'];
244
		$hasError = false;
245
		foreach ($files as $file) {
Qiang Xue committed
246 247 248 249
			$relativePath = $file->getRelativePath();
			if (isset($answers[$file->id]) && $file->operation !== CodeFile::OP_SKIP) {
				$error = $file->save();
				if (is_string($error)) {
250
					$hasError = true;
Qiang Xue committed
251
					$lines[] = "generating $relativePath\n<span class=\"error\">$error</span>";
Qiang Xue committed
252
				} else {
253
					$lines[] = $file->operation === CodeFile::OP_CREATE ? " generated $relativePath" : " overwrote $relativePath";
Qiang Xue committed
254 255 256 257 258 259
				}
			} else {
				$lines[] = "   skipped $relativePath";
			}
		}
		$lines[] = "done!\n";
260 261 262
		$results = implode("\n", $lines);

		return $hasError;
Qiang Xue committed
263 264 265
	}

	/**
266 267
	 * @return string the root path of the template files that are currently being used.
	 * @throws InvalidConfigException if [[template]] is invalid
Qiang Xue committed
268
	 */
Qiang Xue committed
269
	public function getTemplatePath()
Qiang Xue committed
270
	{
Qiang Xue committed
271 272 273 274
		if (isset($this->templates[$this->template])) {
			return $this->templates[$this->template];
		} else {
			throw new InvalidConfigException("Unknown template: {$this->template}");
Qiang Xue committed
275
		}
Qiang Xue committed
276 277
	}

278 279 280
	/**
	 * Generates code using the specified code template and parameters.
	 * Note that the code template will be used as a PHP file.
Qiang Xue committed
281 282
	 * @param string $template the code template file. This must be specified as a file path
	 * relative to [[templatePath]].
283 284 285
	 * @param array $params list of parameters to be passed to the template file.
	 * @return string the generated code
	 */
Alexander Makarov committed
286
	public function render($template, $params = [])
Qiang Xue committed
287 288 289
	{
		$view = new View;
		$params['generator'] = $this;
Qiang Xue committed
290
		return $view->renderFile($this->getTemplatePath() . '/' . $template, $params, $this);
Qiang Xue committed
291 292 293
	}

	/**
Qiang Xue committed
294 295
	 * Validates the template selection.
	 * This method validates whether the user selects an existing template
296
	 * and the template contains all required template files as specified in [[requiredTemplates()]].
Qiang Xue committed
297
	 */
Qiang Xue committed
298
	public function validateTemplate()
Qiang Xue committed
299
	{
Qiang Xue committed
300 301 302 303 304 305 306 307
		$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($templatePath . '/' . $template)) {
					$this->addError('template', "Unable to find the required code template file '$template'.");
Qiang Xue committed
308 309 310 311 312
				}
			}
		}
	}

Qiang Xue committed
313 314 315 316 317 318 319 320 321
	/**
	 * 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.
	 * @param string $attribute the attribute being validated
	 * @param array $params the validation options
	 */
	public function validateClass($attribute, $params)
	{
Qiang Xue committed
322
		$class = $this->$attribute;
Qiang Xue committed
323
		try {
Qiang Xue committed
324 325 326 327 328
			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.");
					}
Qiang Xue committed
329 330
				}
			} else {
Qiang Xue committed
331
				$this->addError($attribute, "Class '$class' does not exist or has syntax error.");
Qiang Xue committed
332 333
			}
		} catch (\Exception $e) {
Qiang Xue committed
334
			$this->addError($attribute, "Class '$class' does not exist or has syntax error.");
Qiang Xue committed
335 336 337
		}
	}

Qiang Xue committed
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
	/**
	 * 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.
	 * @param string $attribute the attribute being validated
	 * @param array $params 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");
			}
		}
	}

Qiang Xue committed
360
	/**
Qiang Xue committed
361 362
	 * @param string $value the attribute to be validated
	 * @return boolean whether the value is a reserved PHP keyword.
Qiang Xue committed
363
	 */
Qiang Xue committed
364
	public function isReservedKeyword($value)
Qiang Xue committed
365
	{
Alexander Makarov committed
366
		static $keywords = [
Qiang Xue committed
367 368 369 370 371 372 373
			'__class__',
			'__dir__',
			'__file__',
			'__function__',
			'__line__',
			'__method__',
			'__namespace__',
Qiang Xue committed
374
			'__trait__',
Qiang Xue committed
375 376 377 378 379 380 381
			'abstract',
			'and',
			'array',
			'as',
			'break',
			'case',
			'catch',
382
			'callable',
Qiang Xue committed
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
			'cfunction',
			'class',
			'clone',
			'const',
			'continue',
			'declare',
			'default',
			'die',
			'do',
			'echo',
			'else',
			'elseif',
			'empty',
			'enddeclare',
			'endfor',
			'endforeach',
			'endif',
			'endswitch',
			'endwhile',
			'eval',
			'exception',
			'exit',
			'extends',
			'final',
Qiang Xue committed
407
			'finally',
Qiang Xue committed
408 409 410 411 412 413 414 415 416 417
			'for',
			'foreach',
			'function',
			'global',
			'goto',
			'if',
			'implements',
			'include',
			'include_once',
			'instanceof',
418
			'insteadof',
Qiang Xue committed
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
			'interface',
			'isset',
			'list',
			'namespace',
			'new',
			'old_function',
			'or',
			'parent',
			'php_user_filter',
			'print',
			'private',
			'protected',
			'public',
			'require',
			'require_once',
			'return',
			'static',
			'switch',
			'this',
			'throw',
Qiang Xue committed
439
			'trait',
Qiang Xue committed
440 441 442 443 444 445
			'try',
			'unset',
			'use',
			'var',
			'while',
			'xor',
Alexander Makarov committed
446
		];
Qiang Xue committed
447
		return in_array(strtolower($value), $keywords, true);
Qiang Xue committed
448 449
	}
}