Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implemented enum #434

Merged
merged 23 commits into from
Feb 1, 2024
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 69 additions & 0 deletions src/generators/model/Generator.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
use yii\base\NotSupportedException;
use yii\db\ActiveQuery;
use yii\db\ActiveRecord;
use yii\db\ColumnSchema;
use yii\db\Connection;
use yii\db\Exception;
use yii\db\Schema;
Expand Down Expand Up @@ -245,6 +246,7 @@ public function generate()
'rules' => $this->generateRules($tableSchema),
'relations' => $tableRelations,
'relationsClassHints' => $this->generateRelationsClassHints($tableRelations, $this->generateQuery),
'enum' => $this->getEnum($tableSchema->columns),
];
$files[] = new CodeFile(
Yii::getAlias('@' . str_replace('\\', '/', $this->ns)) . '/' . $modelClassName . '.php',
Expand Down Expand Up @@ -429,6 +431,17 @@ public function generateRules($table)
$rules[] = "[['" . implode("', '", $columns) . "'], 'string', 'max' => $length]";
}

foreach ($this->getEnum($table->columns) as $field_name => $field_details) {
samdark marked this conversation as resolved.
Show resolved Hide resolved
$fieldEnumValues = [];
foreach ($field_details['values'] as $field_enum_values) {
$fieldEnumValues[] = 'self::'.$field_enum_values['const_name'];
samdark marked this conversation as resolved.
Show resolved Hide resolved
}
$rules['enum-' . $field_name] = "['".$field_name."', 'in', 'range' => [\n ".implode(
samdark marked this conversation as resolved.
Show resolved Hide resolved
",\n ",
$fieldEnumValues
).",\n ]\n ]";
samdark marked this conversation as resolved.
Show resolved Hide resolved
}

$db = $this->getDbConnection();

// Unique indexes rules
Expand Down Expand Up @@ -1094,4 +1107,60 @@ protected function isColumnAutoIncremental($table, $columns)

return false;
}

/**
* prepare ENUM field values.
samdark marked this conversation as resolved.
Show resolved Hide resolved
*
* @param ColumnSchema[] $columns
*
* @return array
*/
public function getEnum($columns)
{
$enum = [];
foreach ($columns as $column) {
if (!$this->isEnum($column)) {
continue;
}

$column_camel_name = str_replace(' ', '', ucwords(implode(' ', explode('_', $column->name))));
samdark marked this conversation as resolved.
Show resolved Hide resolved
$enum[$column->name]['func_opts_name'] = 'opts'.$column_camel_name;
samdark marked this conversation as resolved.
Show resolved Hide resolved
$enum[$column->name]['func_get_label_name'] = 'get'.$column_camel_name.'ValueLabel';
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
$enum[$column->name]['func_get_label_name'] = 'get'.$column_camel_name.'ValueLabel';
$enum[$column->name]['func_get_label_name'] = 'get' . $column_camel_name . 'ValueLabel';

$enum[$column->name]['isFunctionPrefix'] = 'is'.$column_camel_name;
samdark marked this conversation as resolved.
Show resolved Hide resolved
$enum[$column->name]['displayFunctionPrefix'] = 'display'.$column_camel_name;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
$enum[$column->name]['displayFunctionPrefix'] = 'display'.$column_camel_name;
$enum[$column->name]['displayFunctionPrefix'] = 'display' . $column_camel_name;

$enum[$column->name]['columnName'] = $column->name;
$enum[$column->name]['values'] = [];

foreach ($column->enumValues as $value) {
$value = trim($value, "()'");
samdark marked this conversation as resolved.
Show resolved Hide resolved

$const_name = strtoupper($column->name.'_'.$value);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
$const_name = strtoupper($column->name.'_'.$value);
$const_name = strtoupper($column->name . '_' . $value);

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It should be non-ASCII characters aware.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These 4 lines probably could be replaced with one Inflector method.

$const_name = preg_replace('/\s+/', '_', $const_name);
$const_name = str_replace(['-', '_', ' '], '_', $const_name);
$const_name = preg_replace('/[^A-Z0-9_]/', '', $const_name);

$label = Inflector::camel2words($value);

$enum[$column->name]['values'][] = [
'value' => $value,
'const_name' => $const_name,
'label' => $label,
'isFunctionSuffix' => str_replace(' ', '', ucwords(implode(' ', explode('_', $value))))
];
}
}

return $enum;
}

/**
* validate is ENUM column.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
* validate is ENUM column.
* Checks if column is of ENUM type.

*
* @param ColumnSchema $column
* @return string
samdark marked this conversation as resolved.
Show resolved Hide resolved
*/
protected function isEnum($column)
{
return stripos(strtoupper($column->dbType), 'ENUM') === 0;
samdark marked this conversation as resolved.
Show resolved Hide resolved
}
}
72 changes: 72 additions & 0 deletions src/generators/model/default/model.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
/* @var $labels string[] list of attribute labels (name => label) */
/* @var $rules string[] list of validation rules */
/* @var $relations array list of relations (name => relation declaration) */
/* @var array $enum list of ENUM fields */
samdark marked this conversation as resolved.
Show resolved Hide resolved

echo "<?php\n";
?>
Expand All @@ -36,6 +37,22 @@
*/
class <?= $className ?> extends <?= '\\' . ltrim($generator->baseClass, '\\') . "\n" ?>
{

<?php
if(!empty($enum)){
samdark marked this conversation as resolved.
Show resolved Hide resolved
?>
/**
* ENUM field values
samdark marked this conversation as resolved.
Show resolved Hide resolved
*/
samdark marked this conversation as resolved.
Show resolved Hide resolved
<?php
foreach($enum as $column_name => $column_data){
samdark marked this conversation as resolved.
Show resolved Hide resolved
foreach ($column_data['values'] as $enum_value){
echo ' const ' . $enum_value['const_name'] . ' = \'' . $enum_value['value'] . '\';' . PHP_EOL;
}
}
}
?>

/**
* {@inheritdoc}
*/
Expand Down Expand Up @@ -99,4 +116,59 @@ public static function find()
return new <?= $queryClassFullName ?>(get_called_class());
}
<?php endif; ?>

<?php if ($enum): ?>
<?php
foreach($enum as $column_name => $column_data){
samdark marked this conversation as resolved.
Show resolved Hide resolved
?>

/**
* column <?php echo $column_name?> ENUM value labels
samdark marked this conversation as resolved.
Show resolved Hide resolved
* @return array
samdark marked this conversation as resolved.
Show resolved Hide resolved
*/
public static function <?php echo $column_data['func_opts_name']?>()
samdark marked this conversation as resolved.
Show resolved Hide resolved
{
return [
<?php
foreach($column_data['values'] as $k => $value){
samdark marked this conversation as resolved.
Show resolved Hide resolved
if ($generator->enableI18N) {
echo ' '.'self::' . $value['const_name'] . ' => Yii::t(\'' . $generator->messageCategory . '\', \'' . $value['value'] . "'),\n";
samdark marked this conversation as resolved.
Show resolved Hide resolved
} else {
echo ' '.'self::' . $value['const_name'] . ' => \'' . $value['value'] . "',\n";
samdark marked this conversation as resolved.
Show resolved Hide resolved
}
}
?>
];
}
<?php
}

samdark marked this conversation as resolved.
Show resolved Hide resolved

foreach($enum as $column_name => $column_data){
samdark marked this conversation as resolved.
Show resolved Hide resolved
?>

/**
* @return string
samdark marked this conversation as resolved.
Show resolved Hide resolved
*/
samdark marked this conversation as resolved.
Show resolved Hide resolved
public function <?=$column_data['displayFunctionPrefix']?>()
samdark marked this conversation as resolved.
Show resolved Hide resolved
{
return self::<?=$column_data['func_opts_name']?>()[$this-><?=$column_name?>];
}
<?php
foreach ($column_data['values'] as $enum_value){
samdark marked this conversation as resolved.
Show resolved Hide resolved
?>

/**
* @return bool
*/
samdark marked this conversation as resolved.
Show resolved Hide resolved
public function <?=$column_data['isFunctionPrefix'].$enum_value['isFunctionSuffix']?>()
samdark marked this conversation as resolved.
Show resolved Hide resolved
{
return $this-><?=$column_name?> === self::<?=$enum_value['const_name']?>;
samdark marked this conversation as resolved.
Show resolved Hide resolved
}
<?php
}
}
endif;
?>

samdark marked this conversation as resolved.
Show resolved Hide resolved
}
112 changes: 112 additions & 0 deletions tests/generators/ModelGeneratorTest.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
<?php
namespace yiiunit\gii\generators;

use yii\db\mysql\ColumnSchema;
use yii\db\TableSchema;
use yii\gii\generators\model\Generator as ModelGenerator;
use yiiunit\gii\GiiTestCase;

Expand Down Expand Up @@ -413,4 +415,114 @@ public function testGenerateProperties($tableName, $columns)
}

}

public function testEnum()
{
$generator = new ModelGenerator();
$generator->template = 'default';
$generator->tableName = 'category_photo';


samdark marked this conversation as resolved.
Show resolved Hide resolved
$tableSchema = $this->createEnumTableSchema();
$params = [
'tableName' => $tableSchema->name,
'className' => 'TestEnumModel',
'queryClassName' => false,
'tableSchema' => $tableSchema,
'properties' => [],
'labels' => $generator->generateLabels($tableSchema),
'rules' => $generator->generateRules($tableSchema),
'relations' => [],
'relationsClassHints' => [],
'enum' => $generator->getEnum($tableSchema->columns),
];
$codeFile = $generator->render('model.php', $params);

/**
* Fix class code for eval - remove ?php, namespace and use Yii
*/
$classCode = str_replace('<?php','',$codeFile);
samdark marked this conversation as resolved.
Show resolved Hide resolved
$classCode = str_replace('namespace app\models;','',$classCode);
samdark marked this conversation as resolved.
Show resolved Hide resolved
$classCode = str_replace('use Yii;','',$classCode);
samdark marked this conversation as resolved.
Show resolved Hide resolved

/**
* add method getTableSchema for seting test schema
samdark marked this conversation as resolved.
Show resolved Hide resolved
*/
$classCode = substr($classCode, 0, strrpos($classCode, "\n"));
$classCode = substr($classCode, 0, strrpos($classCode, "\n"));
$classCode .= '
public static $testTableSchema;
public static function getTableSchema(){
return self::$testTableSchema;
}
}
';
if(!class_exists('TestEnumModel')) {
samdark marked this conversation as resolved.
Show resolved Hide resolved
//echo $classCode;
eval($classCode);
uldisn marked this conversation as resolved.
Show resolved Hide resolved
}

$testEnumModel = new \TestEnumModel();
$testEnumModel::$testTableSchema = $this->createEnumTableSchema();

/** test assigning and method is... */
$testEnumModel->type = \TestEnumModel::TYPE_CLIENT;
$this->assertTrue($testEnumModel->isTypeClient());
$this->assertFalse($testEnumModel->isTypeConsignees());

$testEnumModel->type = \TestEnumModel::TYPE_CONSIGNEES;
$this->assertFalse($testEnumModel->isTypeClient());
$this->assertTrue($testEnumModel->isTypeConsignees());
$this->assertEquals(\TestEnumModel::TYPE_CONSIGNEES,$testEnumModel->displayType());

/** test validate */
$this->assertTrue($testEnumModel->validate());
$testEnumModel->type = '11111';
$this->assertFalse($testEnumModel->validate());

uldisn marked this conversation as resolved.
Show resolved Hide resolved

}

public function createEnumTableSchema()
{
$schema = new TableSchema();
$schema->name = 'company_type';
$schema->fullName = 'company_type';
$schema->primaryKey = ['id'];
$schema->columns = [
'id' => new ColumnSchema([
'name' => 'id',
'allowNull' => false,
'type' => 'smallint',
'phpType' => 'integer',
'dbType' => 'smallint(5) unsigned',
'size' => 5,
'precision' => 5,
'isPrimaryKey' => true,
'autoIncrement' => true,
'unsigned' => true,
'comment' => ''
]),
'type' => new ColumnSchema([
'name' => 'type',
'allowNull' => true,
'type' => 'string',
'phpType' => 'string',
'dbType' => 'enum(\'Client\',\'Consignees\',\'Car cleaner\')',
'enumValues' => [
0 => 'Client',
1 => 'Consignees',
2 => 'Car cleaner',
],
'size' => null,
'precision' => null,
'isPrimaryKey' => false,
'autoIncrement' => false,
'unsigned' => false,
'comment' => ''
]),
];

return $schema;
}
}