Skip to content

Commit

Permalink
Fix #537: Generating rules for the fields with default values
Browse files Browse the repository at this point in the history
  • Loading branch information
manky authored Oct 24, 2023
1 parent 752717e commit be02a08
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ Yii Framework 2 gii extension Change Log
-----------------------

- Bug #532: Return `ExitCode::USAGE` on command input validation error (egmsystems)
- Enh #537: Generating rules for the fields with default values (manky)


2.2.6 May 22, 2023
Expand Down
18 changes: 18 additions & 0 deletions src/generators/model/Generator.php
Original file line number Diff line number Diff line change
Expand Up @@ -438,12 +438,21 @@ public function generateRules($table)
{
$types = [];
$lengths = [];
$nullable = [];
$defaultValues = [];
foreach ($table->columns as $column) {
if ($column->autoIncrement) {
continue;
}
if (!$column->allowNull && $column->defaultValue === null) {
$types['required'][] = $column->name;
} elseif ($column->allowNull && $column->defaultValue === null) {
$nullable[] = $column->name;
} elseif (is_scalar($column->defaultValue)) {
if (array_key_exists($column->defaultValue, $defaultValues)) {
$defaultValues[$column->defaultValue] = [];
}
$defaultValues[$column->defaultValue][] = $column->name;
}
switch ($column->type) {
case Schema::TYPE_SMALLINT:
Expand Down Expand Up @@ -477,6 +486,15 @@ public function generateRules($table)
}
}
$rules = [];
if (!empty($nullable)) {
$rules[] = "[['" . implode("', '", $nullable) . "'], 'default', 'value' => null]";
}
if (!empty($defaultValues)) {
foreach ($defaultValues as $defaultValue => $defaultValueColumns) {
$defaultValue = is_numeric($defaultValue) ? $defaultValue : "'$defaultValue'";
$rules[] = "[['" . implode("', '", $defaultValueColumns) . "'], 'default', 'value' => $defaultValue]";
}
}
$driverName = $this->getDbDriverName();
foreach ($types as $type => $columns) {
if ($driverName === 'pgsql' && $type === 'integer') {
Expand Down

0 comments on commit be02a08

Please sign in to comment.