Generator.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\gii\generators\model;
  8. use Yii;
  9. use yii\db\ActiveRecord;
  10. use yii\db\Connection;
  11. use yii\db\Schema;
  12. use yii\gii\CodeFile;
  13. use yii\helpers\Inflector;
  14. use yii\base\NotSupportedException;
  15. /**
  16. * This generator will generate one or multiple ActiveRecord classes for the specified database table.
  17. *
  18. * @author Qiang Xue <qiang.xue@gmail.com>
  19. * @since 2.0
  20. */
  21. class Generator extends \yii\gii\Generator
  22. {
  23. public $db = 'db';
  24. public $ns = 'app\models';
  25. public $tableName;
  26. public $modelClass;
  27. public $baseClass = 'yii\db\ActiveRecord';
  28. public $generateRelations = true;
  29. public $generateLabelsFromComments = false;
  30. /**
  31. * @inheritdoc
  32. */
  33. public function getName()
  34. {
  35. return 'Model Generator';
  36. }
  37. /**
  38. * @inheritdoc
  39. */
  40. public function getDescription()
  41. {
  42. return 'This generator generates an ActiveRecord class for the specified database table.';
  43. }
  44. /**
  45. * @inheritdoc
  46. */
  47. public function rules()
  48. {
  49. return array_merge(parent::rules(), [
  50. [['db', 'ns', 'tableName', 'modelClass', 'baseClass'], 'filter', 'filter' => 'trim'],
  51. [['db', 'ns', 'tableName', 'baseClass'], 'required'],
  52. [['db', 'modelClass'], 'match', 'pattern' => '/^\w+$/', 'message' => 'Only word characters are allowed.'],
  53. [['ns', 'baseClass'], 'match', 'pattern' => '/^[\w\\\\]+$/', 'message' => 'Only word characters and backslashes are allowed.'],
  54. [['tableName'], 'match', 'pattern' => '/^(\w+\.)?([\w\*]+)$/', 'message' => 'Only word characters, and optionally an asterisk and/or a dot are allowed.'],
  55. [['db'], 'validateDb'],
  56. [['ns'], 'validateNamespace'],
  57. [['tableName'], 'validateTableName'],
  58. [['modelClass'], 'validateModelClass', 'skipOnEmpty' => false],
  59. [['baseClass'], 'validateClass', 'params' => ['extends' => ActiveRecord::className()]],
  60. [['generateRelations', 'generateLabelsFromComments'], 'boolean'],
  61. [['enableI18N'], 'boolean'],
  62. [['messageCategory'], 'validateMessageCategory', 'skipOnEmpty' => false],
  63. ]);
  64. }
  65. /**
  66. * @inheritdoc
  67. */
  68. public function attributeLabels()
  69. {
  70. return array_merge(parent::attributeLabels(), [
  71. 'ns' => 'Namespace',
  72. 'db' => 'Database Connection ID',
  73. 'tableName' => 'Table Name',
  74. 'modelClass' => 'Model Class',
  75. 'baseClass' => 'Base Class',
  76. 'generateRelations' => 'Generate Relations',
  77. 'generateLabelsFromComments' => 'Generate Labels from DB Comments',
  78. ]);
  79. }
  80. /**
  81. * @inheritdoc
  82. */
  83. public function hints()
  84. {
  85. return array_merge(parent::hints(), [
  86. 'ns' => 'This is the namespace of the ActiveRecord class to be generated, e.g., <code>app\models</code>',
  87. 'db' => 'This is the ID of the DB application component.',
  88. 'tableName' => 'This is the name of the DB table that the new ActiveRecord class is associated with, e.g. <code>post</code>.
  89. The table name may consist of the DB schema part if needed, e.g. <code>public.post</code>.
  90. The table name may end with asterisk to match multiple table names, e.g. <code>tbl_*</code>
  91. will match tables who name starts with <code>tbl_</code>. In this case, multiple ActiveRecord classes
  92. will be generated, one for each matching table name; and the class names will be generated from
  93. the matching characters. For example, table <code>tbl_post</code> will generate <code>Post</code>
  94. class.',
  95. 'modelClass' => 'This is the name of the ActiveRecord class to be generated. The class name should not contain
  96. the namespace part as it is specified in "Namespace". You do not need to specify the class name
  97. if "Table Name" ends with asterisk, in which case multiple ActiveRecord classes will be generated.',
  98. 'baseClass' => 'This is the base class of the new ActiveRecord class. It should be a fully qualified namespaced class name.',
  99. 'generateRelations' => 'This indicates whether the generator should generate relations based on
  100. foreign key constraints it detects in the database. Note that if your database contains too many tables,
  101. you may want to uncheck this option to accelerate the code generation process.',
  102. 'generateLabelsFromComments' => 'This indicates whether the generator should generate attribute labels
  103. by using the comments of the corresponding DB columns.',
  104. ]);
  105. }
  106. /**
  107. * @inheritdoc
  108. */
  109. public function autoCompleteData()
  110. {
  111. $db = $this->getDbConnection();
  112. if ($db !== null) {
  113. return [
  114. 'tableName' => function () use ($db) {
  115. return $db->getSchema()->getTableNames();
  116. },
  117. ];
  118. } else {
  119. return [];
  120. }
  121. }
  122. /**
  123. * @inheritdoc
  124. */
  125. public function requiredTemplates()
  126. {
  127. return ['model.php'];
  128. }
  129. /**
  130. * @inheritdoc
  131. */
  132. public function stickyAttributes()
  133. {
  134. return array_merge(parent::stickyAttributes(), ['ns', 'db', 'baseClass', 'generateRelations', 'generateLabelsFromComments']);
  135. }
  136. /**
  137. * @inheritdoc
  138. */
  139. public function generate()
  140. {
  141. $files = [];
  142. $relations = $this->generateRelations();
  143. $db = $this->getDbConnection();
  144. foreach ($this->getTableNames() as $tableName) {
  145. $className = $this->generateClassName($tableName);
  146. $tableSchema = $db->getTableSchema($tableName);
  147. $params = [
  148. 'tableName' => $tableName,
  149. 'className' => $className,
  150. 'tableSchema' => $tableSchema,
  151. 'labels' => $this->generateLabels($tableSchema),
  152. 'rules' => $this->generateRules($tableSchema),
  153. 'relations' => isset($relations[$className]) ? $relations[$className] : [],
  154. ];
  155. $files[] = new CodeFile(
  156. Yii::getAlias('@' . str_replace('\\', '/', $this->ns)) . '/' . $className . '.php',
  157. $this->render('model.php', $params)
  158. );
  159. }
  160. return $files;
  161. }
  162. /**
  163. * Generates the attribute labels for the specified table.
  164. * @param \yii\db\TableSchema $table the table schema
  165. * @return array the generated attribute labels (name => label)
  166. */
  167. public function generateLabels($table)
  168. {
  169. $labels = [];
  170. foreach ($table->columns as $column) {
  171. if ($this->generateLabelsFromComments && !empty($column->comment)) {
  172. $labels[$column->name] = $column->comment;
  173. } elseif (!strcasecmp($column->name, 'id')) {
  174. $labels[$column->name] = 'ID';
  175. } else {
  176. $label = Inflector::camel2words($column->name);
  177. if (strcasecmp(substr($label, -3), ' id') === 0) {
  178. $label = substr($label, 0, -3) . ' ID';
  179. }
  180. $labels[$column->name] = $label;
  181. }
  182. }
  183. return $labels;
  184. }
  185. /**
  186. * Generates validation rules for the specified table.
  187. * @param \yii\db\TableSchema $table the table schema
  188. * @return array the generated validation rules
  189. */
  190. public function generateRules($table)
  191. {
  192. $types = [];
  193. $lengths = [];
  194. foreach ($table->columns as $column) {
  195. if ($column->autoIncrement) {
  196. continue;
  197. }
  198. if (!$column->allowNull && $column->defaultValue === null) {
  199. $types['required'][] = $column->name;
  200. }
  201. switch ($column->type) {
  202. case Schema::TYPE_SMALLINT:
  203. case Schema::TYPE_INTEGER:
  204. case Schema::TYPE_BIGINT:
  205. $types['integer'][] = $column->name;
  206. break;
  207. case Schema::TYPE_BOOLEAN:
  208. $types['boolean'][] = $column->name;
  209. break;
  210. case Schema::TYPE_FLOAT:
  211. case Schema::TYPE_DECIMAL:
  212. case Schema::TYPE_MONEY:
  213. $types['number'][] = $column->name;
  214. break;
  215. case Schema::TYPE_DATE:
  216. case Schema::TYPE_TIME:
  217. case Schema::TYPE_DATETIME:
  218. case Schema::TYPE_TIMESTAMP:
  219. $types['safe'][] = $column->name;
  220. break;
  221. default: // strings
  222. if ($column->size > 0) {
  223. $lengths[$column->size][] = $column->name;
  224. } else {
  225. $types['string'][] = $column->name;
  226. }
  227. }
  228. }
  229. $rules = [];
  230. foreach ($types as $type => $columns) {
  231. $rules[] = "[['" . implode("', '", $columns) . "'], '$type']";
  232. }
  233. foreach ($lengths as $length => $columns) {
  234. $rules[] = "[['" . implode("', '", $columns) . "'], 'string', 'max' => $length]";
  235. }
  236. // Unique indexes rules
  237. try {
  238. $db = $this->getDbConnection();
  239. $uniqueIndexes = $db->getSchema()->findUniqueIndexes($table);
  240. foreach ($uniqueIndexes as $uniqueColumns) {
  241. // Avoid validating auto incremental columns
  242. if (!$this->isColumnAutoIncremental($table, $uniqueColumns)) {
  243. $attributesCount = count($uniqueColumns);
  244. if ($attributesCount == 1) {
  245. $rules[] = "[['" . $uniqueColumns[0] . "'], 'unique']";
  246. } elseif ($attributesCount > 1) {
  247. $labels = array_intersect_key($this->generateLabels($table), array_flip($uniqueColumns));
  248. $lastLabel = array_pop($labels);
  249. $columnsList = implode("', '", $uniqueColumns);
  250. $rules[] = "[['" . $columnsList . "'], 'unique', 'targetAttribute' => ['" . $columnsList . "'], 'message' => 'The combination of " . implode(', ', $labels) . " and " . $lastLabel . " has already been taken.']";
  251. }
  252. }
  253. }
  254. } catch (NotSupportedException $e) {
  255. // doesn't support unique indexes information...do nothing
  256. }
  257. return $rules;
  258. }
  259. /**
  260. * @return array the generated relation declarations
  261. */
  262. protected function generateRelations()
  263. {
  264. if (!$this->generateRelations) {
  265. return [];
  266. }
  267. $db = $this->getDbConnection();
  268. if (($pos = strpos($this->tableName, '.')) !== false) {
  269. $schemaName = substr($this->tableName, 0, $pos);
  270. } else {
  271. $schemaName = '';
  272. }
  273. $relations = [];
  274. foreach ($db->getSchema()->getTableSchemas($schemaName) as $table) {
  275. $tableName = $table->name;
  276. $className = $this->generateClassName($tableName);
  277. foreach ($table->foreignKeys as $refs) {
  278. $refTable = $refs[0];
  279. unset($refs[0]);
  280. $fks = array_keys($refs);
  281. $refClassName = $this->generateClassName($refTable);
  282. // Add relation for this table
  283. $link = $this->generateRelationLink(array_flip($refs));
  284. $relationName = $this->generateRelationName($relations, $className, $table, $fks[0], false);
  285. $relations[$className][$relationName] = [
  286. "return \$this->hasOne($refClassName::className(), $link);",
  287. $refClassName,
  288. false,
  289. ];
  290. // Add relation for the referenced table
  291. $hasMany = false;
  292. foreach ($fks as $key) {
  293. if (!in_array($key, $table->primaryKey, true)) {
  294. $hasMany = true;
  295. break;
  296. }
  297. }
  298. $link = $this->generateRelationLink($refs);
  299. $relationName = $this->generateRelationName($relations, $refClassName, $refTable, $className, $hasMany);
  300. $relations[$refClassName][$relationName] = [
  301. "return \$this->" . ($hasMany ? 'hasMany' : 'hasOne') . "($className::className(), $link);",
  302. $className,
  303. $hasMany,
  304. ];
  305. }
  306. if (($fks = $this->checkPivotTable($table)) === false) {
  307. continue;
  308. }
  309. $table0 = $fks[$table->primaryKey[0]][0];
  310. $table1 = $fks[$table->primaryKey[1]][0];
  311. $className0 = $this->generateClassName($table0);
  312. $className1 = $this->generateClassName($table1);
  313. $link = $this->generateRelationLink([$fks[$table->primaryKey[1]][1] => $table->primaryKey[1]]);
  314. $viaLink = $this->generateRelationLink([$table->primaryKey[0] => $fks[$table->primaryKey[0]][1]]);
  315. $relationName = $this->generateRelationName($relations, $className0, $db->getTableSchema($table0), $table->primaryKey[1], true);
  316. $relations[$className0][$relationName] = [
  317. "return \$this->hasMany($className1::className(), $link)->viaTable('{$table->name}', $viaLink);",
  318. $className1,
  319. true,
  320. ];
  321. $link = $this->generateRelationLink([$fks[$table->primaryKey[0]][1] => $table->primaryKey[0]]);
  322. $viaLink = $this->generateRelationLink([$table->primaryKey[1] => $fks[$table->primaryKey[1]][1]]);
  323. $relationName = $this->generateRelationName($relations, $className1, $db->getTableSchema($table1), $table->primaryKey[0], true);
  324. $relations[$className1][$relationName] = [
  325. "return \$this->hasMany($className0::className(), $link)->viaTable('{$table->name}', $viaLink);",
  326. $className0,
  327. true,
  328. ];
  329. }
  330. return $relations;
  331. }
  332. /**
  333. * Generates the link parameter to be used in generating the relation declaration.
  334. * @param array $refs reference constraint
  335. * @return string the generated link parameter.
  336. */
  337. protected function generateRelationLink($refs)
  338. {
  339. $pairs = [];
  340. foreach ($refs as $a => $b) {
  341. $pairs[] = "'$a' => '$b'";
  342. }
  343. return '[' . implode(', ', $pairs) . ']';
  344. }
  345. /**
  346. * Checks if the given table is a pivot table.
  347. * For simplicity, this method only deals with the case where the pivot contains two PK columns,
  348. * each referencing a column in a different table.
  349. * @param \yii\db\TableSchema the table being checked
  350. * @return array|boolean the relevant foreign key constraint information if the table is a pivot table,
  351. * or false if the table is not a pivot table.
  352. */
  353. protected function checkPivotTable($table)
  354. {
  355. $pk = $table->primaryKey;
  356. if (count($pk) !== 2) {
  357. return false;
  358. }
  359. $fks = [];
  360. foreach ($table->foreignKeys as $refs) {
  361. if (count($refs) === 2) {
  362. if (isset($refs[$pk[0]])) {
  363. $fks[$pk[0]] = [$refs[0], $refs[$pk[0]]];
  364. } elseif (isset($refs[$pk[1]])) {
  365. $fks[$pk[1]] = [$refs[0], $refs[$pk[1]]];
  366. }
  367. }
  368. }
  369. if (count($fks) === 2 && $fks[$pk[0]][0] !== $fks[$pk[1]][0]) {
  370. return $fks;
  371. } else {
  372. return false;
  373. }
  374. }
  375. /**
  376. * Generate a relation name for the specified table and a base name.
  377. * @param array $relations the relations being generated currently.
  378. * @param string $className the class name that will contain the relation declarations
  379. * @param \yii\db\TableSchema $table the table schema
  380. * @param string $key a base name that the relation name may be generated from
  381. * @param boolean $multiple whether this is a has-many relation
  382. * @return string the relation name
  383. */
  384. protected function generateRelationName($relations, $className, $table, $key, $multiple)
  385. {
  386. if (strcasecmp(substr($key, -2), 'id') === 0 && strcasecmp($key, 'id')) {
  387. $key = rtrim(substr($key, 0, -2), '_');
  388. }
  389. if ($multiple) {
  390. $key = Inflector::pluralize($key);
  391. }
  392. $name = $rawName = Inflector::id2camel($key, '_');
  393. $i = 0;
  394. while (isset($table->columns[lcfirst($name)])) {
  395. $name = $rawName . ($i++);
  396. }
  397. while (isset($relations[$className][lcfirst($name)])) {
  398. $name = $rawName . ($i++);
  399. }
  400. return $name;
  401. }
  402. /**
  403. * Validates the [[db]] attribute.
  404. */
  405. public function validateDb()
  406. {
  407. if (!Yii::$app->has($this->db)) {
  408. $this->addError('db', 'There is no application component named "db".');
  409. } elseif (!Yii::$app->get($this->db) instanceof Connection) {
  410. $this->addError('db', 'The "db" application component must be a DB connection instance.');
  411. }
  412. }
  413. /**
  414. * Validates the [[ns]] attribute.
  415. */
  416. public function validateNamespace()
  417. {
  418. $this->ns = ltrim($this->ns, '\\');
  419. $path = Yii::getAlias('@' . str_replace('\\', '/', $this->ns), false);
  420. if ($path === false) {
  421. $this->addError('ns', 'Namespace must be associated with an existing directory.');
  422. }
  423. }
  424. /**
  425. * Validates the [[modelClass]] attribute.
  426. */
  427. public function validateModelClass()
  428. {
  429. if ($this->isReservedKeyword($this->modelClass)) {
  430. $this->addError('modelClass', 'Class name cannot be a reserved PHP keyword.');
  431. }
  432. if (substr($this->tableName, -1) !== '*' && $this->modelClass == '') {
  433. $this->addError('modelClass', 'Model Class cannot be blank if table name does not end with asterisk.');
  434. }
  435. }
  436. /**
  437. * Validates the [[tableName]] attribute.
  438. */
  439. public function validateTableName()
  440. {
  441. if (strpos($this->tableName, '*') !== false && substr($this->tableName, -1) !== '*') {
  442. $this->addError('tableName', 'Asterisk is only allowed as the last character.');
  443. return;
  444. }
  445. $tables = $this->getTableNames();
  446. if (empty($tables)) {
  447. $this->addError('tableName', "Table '{$this->tableName}' does not exist.");
  448. } else {
  449. foreach ($tables as $table) {
  450. $class = $this->generateClassName($table);
  451. if ($this->isReservedKeyword($class)) {
  452. $this->addError('tableName', "Table '$table' will generate a class which is a reserved PHP keyword.");
  453. break;
  454. }
  455. }
  456. }
  457. }
  458. private $_tableNames;
  459. private $_classNames;
  460. /**
  461. * @return array the table names that match the pattern specified by [[tableName]].
  462. */
  463. protected function getTableNames()
  464. {
  465. if ($this->_tableNames !== null) {
  466. return $this->_tableNames;
  467. }
  468. $db = $this->getDbConnection();
  469. if ($db === null) {
  470. return [];
  471. }
  472. $tableNames = [];
  473. if (strpos($this->tableName, '*') !== false) {
  474. if (($pos = strrpos($this->tableName, '.')) !== false) {
  475. $schema = substr($this->tableName, 0, $pos);
  476. $pattern = '/^' . str_replace('*', '\w+', substr($this->tableName, $pos + 1)) . '$/';
  477. } else {
  478. $schema = '';
  479. $pattern = '/^' . str_replace('*', '\w+', $this->tableName) . '$/';
  480. }
  481. foreach ($db->schema->getTableNames($schema) as $table) {
  482. if (preg_match($pattern, $table)) {
  483. $tableNames[] = $schema === '' ? $table : ($schema . '.' . $table);
  484. }
  485. }
  486. } elseif (($table = $db->getTableSchema($this->tableName, true)) !== null) {
  487. $tableNames[] = $this->tableName;
  488. $this->_classNames[$this->tableName] = $this->modelClass;
  489. }
  490. return $this->_tableNames = $tableNames;
  491. }
  492. /**
  493. * Generates a class name from the specified table name.
  494. * @param string $tableName the table name (which may contain schema prefix)
  495. * @return string the generated class name
  496. */
  497. protected function generateClassName($tableName)
  498. {
  499. if (isset($this->_classNames[$tableName])) {
  500. return $this->_classNames[$tableName];
  501. }
  502. if (($pos = strrpos($tableName, '.')) !== false) {
  503. $tableName = substr($tableName, $pos + 1);
  504. }
  505. $db = $this->getDbConnection();
  506. $patterns = [];
  507. $patterns[] = "/^{$db->tablePrefix}(.*?)$/";
  508. $patterns[] = "/^(.*?){$db->tablePrefix}$/";
  509. if (strpos($this->tableName, '*') !== false) {
  510. $pattern = $this->tableName;
  511. if (($pos = strrpos($pattern, '.')) !== false) {
  512. $pattern = substr($pattern, $pos + 1);
  513. }
  514. $patterns[] = '/^' . str_replace('*', '(\w+)', $pattern) . '$/';
  515. }
  516. $className = $tableName;
  517. foreach ($patterns as $pattern) {
  518. if (preg_match($pattern, $tableName, $matches)) {
  519. $className = $matches[1];
  520. break;
  521. }
  522. }
  523. return $this->_classNames[$tableName] = Inflector::id2camel($className, '_');
  524. }
  525. /**
  526. * @return Connection the DB connection as specified by [[db]].
  527. */
  528. protected function getDbConnection()
  529. {
  530. return Yii::$app->{$this->db};
  531. }
  532. /**
  533. * Checks if any of the specified columns is auto incremental.
  534. * @param \yii\db\TableSchema $table the table schema
  535. * @param array $columns columns to check for autoIncrement property
  536. * @return boolean whether any of the specified columns is auto incremental.
  537. */
  538. protected function isColumnAutoIncremental($table, $columns)
  539. {
  540. foreach ($columns as $column) {
  541. if (isset($table->columns[$column]) && $table->columns[$column]->autoIncrement) {
  542. return true;
  543. }
  544. }
  545. return false;
  546. }
  547. }