Skip to content

Commit 8c55b82

Browse files
committed
refactor: migrate make:model to AbstractGeneratorCommand
1 parent 4f9d165 commit 8c55b82

6 files changed

Lines changed: 232 additions & 205 deletions

File tree

‎system/Commands/Generators/ModelGenerator.php‎

Lines changed: 93 additions & 104 deletions
Original file line numberDiff line numberDiff line change
@@ -13,132 +13,121 @@
1313

1414
namespace CodeIgniter\Commands\Generators;
1515

16-
use CodeIgniter\CLI\BaseCommand;
16+
use CodeIgniter\CLI\AbstractGeneratorCommand;
17+
use CodeIgniter\CLI\Attributes\Command;
18+
use CodeIgniter\CLI\Attributes\GeneratorCommand;
1719
use CodeIgniter\CLI\CLI;
18-
use CodeIgniter\CLI\GeneratorTrait;
19-
20-
/**
21-
* Generates a skeleton Model file.
22-
*/
23-
class ModelGenerator extends BaseCommand
20+
use CodeIgniter\CLI\Input\Option;
21+
22+
#[Command(name: 'make:model', description: 'Generates a new model file.', group: 'Generators')]
23+
#[GeneratorCommand(
24+
component: 'Model',
25+
template: 'model.tpl.php',
26+
directory: 'Models',
27+
classNameLang: 'CLI.generator.className.model',
28+
)]
29+
class ModelGenerator extends AbstractGeneratorCommand
2430
{
25-
use GeneratorTrait;
26-
27-
/**
28-
* The Command's Group
29-
*
30-
* @var string
31-
*/
32-
protected $group = 'Generators';
33-
34-
/**
35-
* The Command's Name
36-
*
37-
* @var string
38-
*/
39-
protected $name = 'make:model';
40-
41-
/**
42-
* The Command's Description
43-
*
44-
* @var string
45-
*/
46-
protected $description = 'Generates a new model file.';
47-
48-
/**
49-
* The Command's Usage
50-
*
51-
* @var string
52-
*/
53-
protected $usage = 'make:model <name> [options]';
31+
private const RETURN_TYPES = ['array', 'object', 'entity'];
5432

55-
/**
56-
* The Command's Arguments
57-
*
58-
* @var array<string, string>
59-
*/
60-
protected $arguments = [
61-
'name' => 'The model class name.',
62-
];
63-
64-
/**
65-
* The Command's Options
66-
*
67-
* @var array<string, string>
68-
*/
69-
protected $options = [
70-
'--table' => 'Supply a table name. Default: "the lowercased plural of the class name".',
71-
'--dbgroup' => 'Database group to use. Default: "default".',
72-
'--return' => 'Return type, Options: [array, object, entity]. Default: "array".',
73-
'--namespace' => 'Set root namespace. Default: "APP_NAMESPACE".',
74-
'--suffix' => 'Append the component title to the class name (e.g. User => UserModel).',
75-
'--force' => 'Force overwrite existing file.',
76-
];
33+
protected function configure(): void
34+
{
35+
parent::configure();
36+
37+
$this
38+
->addOption(new Option(
39+
name: 'table',
40+
shortcut: 't',
41+
description: 'Table name. Defaults to the lowercased plural of the class name.',
42+
acceptsValue: true,
43+
valueLabel: 'name',
44+
))
45+
->addOption(new Option(
46+
name: 'dbgroup',
47+
shortcut: 'g',
48+
description: 'Database group to use.',
49+
acceptsValue: true,
50+
valueLabel: 'group',
51+
))
52+
->addOption(new Option(
53+
name: 'return',
54+
shortcut: 'r',
55+
description: 'Return type: "array", "object", or "entity".',
56+
requiresValue: true,
57+
valueLabel: 'type',
58+
default: 'array',
59+
));
60+
}
7761

78-
/**
79-
* Actually execute a command.
80-
*/
81-
public function run(array $params)
62+
protected function interact(array &$arguments, array &$options): void
8263
{
83-
$this->component = 'Model';
84-
$this->directory = 'Models';
85-
$this->template = 'model.tpl.php';
64+
$return = $this->getUnboundOption('return', $options);
8665

87-
$this->classNameLang = 'CLI.generator.className.model';
88-
$this->generateClass($params);
66+
if (! is_string($return) || in_array($return, self::RETURN_TYPES, true)) {
67+
return;
68+
}
8969

90-
return EXIT_SUCCESS;
70+
$options['return'] = CLI::prompt(lang('CLI.generator.returnType'), self::RETURN_TYPES, 'required');
9171
}
9272

93-
/**
94-
* Prepare options and do the necessary replacements.
95-
*/
96-
protected function prepare(string $class): string
73+
protected function execute(array $arguments, array $options): int
9774
{
98-
$table = $this->getOption('table');
99-
$dbGroup = $this->getOption('dbgroup');
100-
$return = $this->getOption('return');
75+
$return = $this->getValidatedOption('return');
10176

102-
$baseClass = class_basename($class);
77+
if (! in_array($return, self::RETURN_TYPES, true)) {
78+
CLI::error(lang('CLI.generator.invalidReturnType', [$return]));
10379

104-
if (preg_match('/^(\S+)Model$/i', $baseClass, $match) === 1) {
105-
$baseClass = $match[1];
80+
return EXIT_ERROR;
10681
}
10782

108-
$table = is_string($table) ? $table : plural(strtolower($baseClass));
109-
$return = is_string($return) ? $return : 'array';
83+
$exitCode = $this->generateClass();
11084

111-
if (! in_array($return, ['array', 'object', 'entity'], true)) {
112-
// @codeCoverageIgnoreStart
113-
$return = CLI::prompt(lang('CLI.generator.returnType'), ['array', 'object', 'entity'], 'required');
114-
CLI::newLine();
115-
// @codeCoverageIgnoreEnd
85+
if ($exitCode !== EXIT_SUCCESS || $return !== 'entity') {
86+
return $exitCode;
11687
}
11788

118-
if ($return === 'entity') {
119-
// Build the fully-qualified entity class from the model class so
120-
// that the generated Entity keeps any sub-namespaces (eg. Admin).
121-
$entityClass = str_replace('Models', 'Entities', $class);
89+
$entityOptions = ['namespace' => $this->getValidatedOption('namespace')];
12290

123-
if (preg_match('/^(\S+)Model$/i', $entityClass, $match) === 1) {
124-
$entityClass = $match[1];
91+
if ($this->getValidatedOption('force') === true) {
92+
$entityOptions['force'] = null;
93+
}
94+
95+
return $this->call('make:entity', [$this->getEntityClass($this->qualifyClassName())], $entityOptions);
96+
}
12597

126-
if ($this->getOption('suffix')) {
127-
$entityClass .= 'Entity';
128-
}
129-
}
98+
protected function getReplacements(string $class): array
99+
{
100+
$table = $this->getValidatedOption('table');
101+
$dbGroup = $this->getValidatedOption('dbgroup');
102+
103+
$return = $this->getValidatedOption('return') === 'entity'
104+
? '\\' . $this->getEntityClass($class) . '::class'
105+
: sprintf("'%s'", $this->getValidatedOption('return'));
106+
107+
return [
108+
'{dbGroup}' => is_string($dbGroup) ? $dbGroup : '',
109+
'{table}' => is_string($table) ? $table : plural(strtolower($this->stripModelSuffix(class_basename($class)))),
110+
'{return}' => $return,
111+
];
112+
}
130113

131-
// Call the entity generator with the fully-qualified class name so
132-
// it ends up under the correct sub-namespace/folder (eg. Admin).
133-
$entityOptions = array_intersect_key($this->params, array_flip(['namespace', 'suffix', 'force']));
114+
protected function getTemplateData(string $class): array
115+
{
116+
return ['dbGroup' => $this->getValidatedOption('dbgroup')];
117+
}
134118

135-
$this->call('make:entity', array_merge([trim($entityClass, '\\')], $entityOptions));
119+
/**
120+
* Derives the entity class from the qualified model class, keeping any sub-namespace.
121+
*/
122+
private function getEntityClass(string $class): string
123+
{
124+
$entity = $this->stripModelSuffix(str_replace('\\Models\\', '\\Entities\\', $class));
136125

137-
$return = '\\' . trim($entityClass, '\\') . '::class';
138-
} else {
139-
$return = "'{$return}'";
140-
}
126+
return $this->shouldAppendSuffix() ? $entity . 'Entity' : $entity;
127+
}
141128

142-
return $this->parseTemplate($class, ['{dbGroup}', '{table}', '{return}'], [$dbGroup, $table, $return], compact('dbGroup'));
129+
private function stripModelSuffix(string $class): string
130+
{
131+
return preg_replace('/^(.+)Model$/i', '$1', $class) ?? $class;
143132
}
144133
}

‎system/Commands/Generators/ScaffoldGenerator.php‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -108,11 +108,11 @@ public function run(array $params)
108108
$controllerOpts['restful'] = is_string($restful) ? $restful : null;
109109
}
110110

111-
$modelOpts = [
111+
$modelOpts = array_filter([
112112
'table' => $this->getOption('table'),
113113
'dbgroup' => $this->getOption('dbgroup'),
114114
'return' => $this->getOption('return'),
115-
];
115+
], is_string(...));
116116

117117
$class = $params[0] ?? CLI::getSegment(2);
118118

‎system/Language/en/CLI.php‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@
4545
'fileOverwrite' => 'File overwritten: "{0}"',
4646
'invalidClassName' => 'Class name "{0}" is not valid.',
4747
'invalidParentClass' => 'Parent class "{0}" is not valid.',
48+
'invalidReturnType' => 'Return type "{0}" is not valid.',
4849
'parentClass' => 'Parent class',
4950
'returnType' => 'Return type',
5051
'tableName' => 'Table name',

0 commit comments

Comments
 (0)