Skip to content

Commit b18f4b7

Browse files
authored
fix: ask the CodeIgniter namespace confirmation once in make:cell and make:model (#10621)
1 parent 3f4344e commit b18f4b7

7 files changed

Lines changed: 219 additions & 23 deletions

File tree

‎system/CLI/AbstractGeneratorCommand.php‎

Lines changed: 34 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,11 @@ abstract class AbstractGeneratorCommand extends AbstractCommand implements Promp
5252

5353
protected ?string $templatePath = null;
5454

55+
/**
56+
* The answer to the `CodeIgniter` namespace confirmation for the current `generateClass()`, or `null` if not yet asked.
57+
*/
58+
private ?bool $confirmedCodeIgniterNamespace = null;
59+
5560
/**
5661
* @throws LogicException
5762
*/
@@ -137,6 +142,8 @@ protected function execute(array $arguments, array $options): int
137142
*/
138143
protected function generateClass(): int
139144
{
145+
$this->confirmedCodeIgniterNamespace = null;
146+
140147
return $this->generate($this->qualifyClassName());
141148
}
142149

@@ -150,6 +157,14 @@ protected function generateView(string $view): int
150157
return $this->generate($view);
151158
}
152159

160+
/**
161+
* Whether the `CodeIgniter` namespace confirmation was declined since the last `generateClass()`.
162+
*/
163+
protected function isCodeIgniterNamespaceDeclined(): bool
164+
{
165+
return $this->confirmedCodeIgniterNamespace === false;
166+
}
167+
153168
/**
154169
* Additional template placeholder replacements, which take precedence over the core `{namespace}` / `{class}` pairs.
155170
*
@@ -327,17 +342,8 @@ private function generate(string $class): int
327342
*/
328343
private function generateFile(string $target, string $content): int
329344
{
330-
if (str_starts_with($target, SYSTEMPATH)) {
331-
CLI::write(lang('CLI.generator.usingCINamespace'), 'yellow');
332-
333-
if (
334-
$this->isInteractive()
335-
&& CLI::prompt(lang('CLI.generator.confirmContinue'), ['y', 'n'], 'required') === 'n'
336-
) {
337-
CLI::write(lang('CLI.generator.cancelOperation'), 'yellow');
338-
339-
return EXIT_SUCCESS;
340-
}
345+
if (str_starts_with($target, SYSTEMPATH) && ! $this->confirmCodeIgniterNamespaceOnce()) {
346+
return EXIT_SUCCESS;
341347
}
342348

343349
$isFile = is_file($target);
@@ -374,6 +380,23 @@ private function generateFile(string $target, string $content): int
374380
return EXIT_SUCCESS;
375381
}
376382

383+
private function confirmCodeIgniterNamespaceOnce(): bool
384+
{
385+
if ($this->confirmedCodeIgniterNamespace !== null) {
386+
return $this->confirmedCodeIgniterNamespace;
387+
}
388+
389+
CLI::write(lang('CLI.generator.usingCINamespace'), 'yellow');
390+
391+
if ($this->isInteractive() && CLI::prompt(lang('CLI.generator.confirmContinue'), ['y', 'n'], 'required') === 'n') {
392+
CLI::write(lang('CLI.generator.cancelOperation'), 'yellow');
393+
394+
return $this->confirmedCodeIgniterNamespace = false;
395+
}
396+
397+
return $this->confirmedCodeIgniterNamespace = true;
398+
}
399+
377400
/**
378401
* Performs the placeholder replacements on the rendered template.
379402
*

‎system/Commands/Generators/ModelGenerator.php‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ protected function execute(array $arguments, array $options): int
8282

8383
$exitCode = $this->generateClass();
8484

85-
if ($exitCode !== EXIT_SUCCESS || $return !== 'entity') {
85+
if ($exitCode !== EXIT_SUCCESS || $return !== 'entity' || $this->isCodeIgniterNamespaceDeclined()) {
8686
return $exitCode;
8787
}
8888

@@ -92,7 +92,12 @@ protected function execute(array $arguments, array $options): int
9292
$entityOptions['force'] = null;
9393
}
9494

95-
return $this->call('make:entity', [$this->getEntityClass($this->qualifyClassName())], $entityOptions);
95+
return $this->call(
96+
'make:entity',
97+
[$this->getEntityClass($this->qualifyClassName())],
98+
$entityOptions,
99+
noInteractionOverride: true,
100+
);
96101
}
97102

98103
protected function getReplacements(string $class): array

‎tests/system/CLI/AbstractGeneratorCommandTest.php‎

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@
1313

1414
namespace CodeIgniter\CLI;
1515

16+
use CodeIgniter\CLI\Attributes\Command;
17+
use CodeIgniter\CLI\Attributes\GeneratorCommand;
1618
use CodeIgniter\Exceptions\LogicException;
1719
use CodeIgniter\Test\CIUnitTestCase;
1820
use CodeIgniter\Test\Mock\MockInputOutput;
@@ -413,6 +415,89 @@ public function testAcceptingCodeIgniterNamespacePromptProceeds(): void
413415
$this->assertStringContainsString('File exists: ', $io->getOutput());
414416
}
415417

418+
public function testNonInteractiveCodeIgniterNamespaceWarnsOnceAndProceeds(): void
419+
{
420+
$io = new MockInputOutput();
421+
CLI::setInputOutput($io);
422+
423+
$command = $this->createClassAndViewGenerator();
424+
$command->setInteractive(false);
425+
426+
$this->assertSame(EXIT_ERROR, $command->run([CLI::class], ['namespace' => 'CodeIgniter']));
427+
$this->assertSame(
428+
<<<'EOT'
429+
430+
Warning: Using the "CodeIgniter" namespace will generate the file in the system directory.
431+
File exists: "SYSTEMPATH/CLI/CLI.php"
432+
File exists: "SYSTEMPATH/CLI/Commands.php"
433+
434+
EOT,
435+
preg_replace('/\e\[[^m]+m/', '', $io->getOutput()),
436+
);
437+
}
438+
439+
public function testAcceptedCodeIgniterNamespaceIsReusedForTheView(): void
440+
{
441+
$io = new MockInputOutput();
442+
$io->setInputs(['y']);
443+
CLI::setInputOutput($io);
444+
445+
$command = $this->createClassAndViewGenerator();
446+
$command->setInteractive(true);
447+
448+
$this->assertSame(EXIT_ERROR, $command->run([CLI::class], ['namespace' => 'CodeIgniter']));
449+
$this->assertSame(
450+
<<<'EOT'
451+
452+
Warning: Using the "CodeIgniter" namespace will generate the file in the system directory.
453+
Are you sure you want to continue? [y, n]: y
454+
File exists: "SYSTEMPATH/CLI/CLI.php"
455+
File exists: "SYSTEMPATH/CLI/Commands.php"
456+
457+
EOT,
458+
preg_replace('/\e\[[^m]+m/', '', $io->getOutput()),
459+
);
460+
}
461+
462+
public function testCodeIgniterNamespaceIsConfirmedAgainOnTheNextRun(): void
463+
{
464+
$io = new MockInputOutput();
465+
$io->setInputs(['y', 'n']);
466+
CLI::setInputOutput($io);
467+
468+
$command = $this->createClassAndViewGenerator();
469+
$command->setInteractive(true);
470+
471+
$this->assertSame(EXIT_ERROR, $command->run([CLI::class], ['namespace' => 'CodeIgniter']));
472+
$this->assertSame(EXIT_SUCCESS, $command->run([CLI::class], ['namespace' => 'CodeIgniter']));
473+
$this->assertSame(
474+
<<<'EOT'
475+
476+
Warning: Using the "CodeIgniter" namespace will generate the file in the system directory.
477+
Are you sure you want to continue? [y, n]: y
478+
File exists: "SYSTEMPATH/CLI/CLI.php"
479+
File exists: "SYSTEMPATH/CLI/Commands.php"
480+
Warning: Using the "CodeIgniter" namespace will generate the file in the system directory.
481+
Are you sure you want to continue? [y, n]: n
482+
Operation has been cancelled.
483+
484+
EOT,
485+
preg_replace('/\e\[[^m]+m/', '', $io->getOutput()),
486+
);
487+
}
488+
489+
private function createClassAndViewGenerator(): AbstractGeneratorCommand
490+
{
491+
return new #[Command(name: 'make:classandview', description: 'Generates a class and a view.', group: 'Fixtures')]
492+
#[GeneratorCommand(component: 'Widget', template: 'config.tpl.php')]
493+
class (new Commands()) extends AbstractGeneratorCommand {
494+
protected function execute(array $arguments, array $options): int
495+
{
496+
return $this->generateClass() | $this->generateView(Commands::class);
497+
}
498+
};
499+
}
500+
416501
public function testImportsAreSortedInGeneratedContent(): void
417502
{
418503
$command = new ImportSortingGeneratorCommand(new Commands());

‎tests/system/Commands/Generators/CellGeneratorTest.php‎

Lines changed: 32 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,9 @@
1414
namespace CodeIgniter\Commands\Generators;
1515

1616
use CodeIgniter\CLI\CLI;
17+
use CodeIgniter\CLI\Commands;
1718
use CodeIgniter\Test\CIUnitTestCase;
19+
use CodeIgniter\Test\Mock\MockInputOutput;
1820
use CodeIgniter\Test\StreamFilterTrait;
1921
use PHPUnit\Framework\Attributes\Group;
2022

@@ -39,12 +41,12 @@ protected function tearDown(): void
3941

4042
CLI::reset();
4143

42-
$dir = APPPATH . 'Cells';
43-
44-
if (is_dir($dir)) {
45-
helper('filesystem');
46-
delete_files($dir, true, false, true);
47-
rmdir($dir);
44+
foreach ([APPPATH . 'Cells', SYSTEMPATH . 'Cells'] as $dir) {
45+
if (is_dir($dir)) {
46+
helper('filesystem');
47+
delete_files($dir, true, false, true);
48+
rmdir($dir);
49+
}
4850
}
4951
}
5052

@@ -134,4 +136,28 @@ public function testForceOverwritesBothFiles(): void
134136
$this->getUndecoratedBuffer(),
135137
);
136138
}
139+
140+
public function testDecliningCodeIgniterNamespaceAsksOnceForBothFiles(): void
141+
{
142+
$io = new MockInputOutput();
143+
$io->setInputs(['n']);
144+
CLI::setInputOutput($io);
145+
146+
$command = new CellGenerator(new Commands());
147+
$command->setInteractive(true);
148+
149+
$this->assertSame(EXIT_SUCCESS, $command->run(['foo'], ['namespace' => 'CodeIgniter']));
150+
$this->assertSame(
151+
<<<'EOT'
152+
153+
Warning: Using the "CodeIgniter" namespace will generate the file in the system directory.
154+
Are you sure you want to continue? [y, n]: n
155+
Operation has been cancelled.
156+
157+
EOT,
158+
preg_replace('/\e\[[^m]+m/', '', $io->getOutput()),
159+
);
160+
$this->assertFileDoesNotExist(SYSTEMPATH . 'Cells' . DIRECTORY_SEPARATOR . 'FooCell.php');
161+
$this->assertFileDoesNotExist(SYSTEMPATH . 'Cells' . DIRECTORY_SEPARATOR . 'foo.php');
162+
}
137163
}

‎tests/system/Commands/Generators/ModelGeneratorTest.php‎

Lines changed: 49 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ protected function tearDown(): void
4949

5050
helper('filesystem');
5151

52-
foreach ([APPPATH . 'Models/Admin', APPPATH . 'Entities'] as $dir) {
52+
foreach ([APPPATH . 'Models/Admin', APPPATH . 'Entities', SYSTEMPATH . 'Models', SYSTEMPATH . 'Entities'] as $dir) {
5353
if (is_dir($dir)) {
5454
delete_files($dir, true, false, true);
5555
rmdir($dir);
@@ -216,4 +216,52 @@ public function testInvalidReturnTypePromptsWhenInteractive(): void
216216
$this->assertStringContainsString('Return type', $io->getOutput());
217217
$this->assertStringContainsString("protected \$returnType = 'object';", $this->getContents('Models/User.php'));
218218
}
219+
220+
public function testDecliningCodeIgniterNamespaceSkipsTheEntity(): void
221+
{
222+
$io = new MockInputOutput();
223+
$io->setInputs(['n']);
224+
CLI::setInputOutput($io);
225+
226+
$command = new ModelGenerator(new Commands());
227+
$command->setInteractive(true);
228+
229+
$this->assertSame(EXIT_SUCCESS, $command->run(['user'], ['namespace' => 'CodeIgniter', 'return' => 'entity']));
230+
$this->assertSame(
231+
<<<'EOT'
232+
233+
Warning: Using the "CodeIgniter" namespace will generate the file in the system directory.
234+
Are you sure you want to continue? [y, n]: n
235+
Operation has been cancelled.
236+
237+
EOT,
238+
preg_replace('/\e\[[^m]+m/', '', $io->getOutput()),
239+
);
240+
$this->assertFileDoesNotExist(SYSTEMPATH . 'Models' . DIRECTORY_SEPARATOR . 'User.php');
241+
$this->assertFileDoesNotExist(SYSTEMPATH . 'Entities' . DIRECTORY_SEPARATOR . 'User.php');
242+
}
243+
244+
public function testAcceptingCodeIgniterNamespaceDoesNotAskAgainForTheEntity(): void
245+
{
246+
$io = new MockInputOutput();
247+
$io->setInputs(['y']);
248+
CLI::setInputOutput($io);
249+
250+
$command = new ModelGenerator(new Commands());
251+
$command->setInteractive(true);
252+
253+
$this->assertSame(EXIT_SUCCESS, $command->run(['user'], ['namespace' => 'CodeIgniter', 'return' => 'entity']));
254+
$this->assertSame(
255+
<<<'EOT'
256+
257+
Warning: Using the "CodeIgniter" namespace will generate the file in the system directory.
258+
Are you sure you want to continue? [y, n]: y
259+
File created: SYSTEMPATH/Models/User.php
260+
Warning: Using the "CodeIgniter" namespace will generate the file in the system directory.
261+
File created: SYSTEMPATH/Entities/User.php
262+
263+
EOT,
264+
preg_replace('/\e\[[^m]+m/', '', $io->getOutput()),
265+
);
266+
}
219267
}

‎user_guide_src/source/changelogs/v4.8.0.rst‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ Behavior Changes
3535
behaviour may need to re-implement against the modern API (``configure()`` + ``execute()`` and the ``#[Command]`` attribute) once the class it extends is migrated, or, preferably, compose instead of extending. Invocations on the command line are unaffected.
3636
- **Commands:** Generator commands migrated to ``AbstractGeneratorCommand`` now return ``EXIT_ERROR`` (previously ``EXIT_SUCCESS``) when the target file exists
3737
without ``--force``, when the namespace is not defined, or when the name does not form a valid class name. The ``CodeIgniter`` namespace confirmation is no
38-
longer prompted on non-interactive runs.
38+
longer prompted on non-interactive runs, and ``make:cell`` and ``make:model --return entity`` now ask it only once.
3939
- **Commands:** The ``make:command`` command now generates modern commands: a ``basic`` command extends ``AbstractCommand`` with the ``#[Command]`` attribute,
4040
and a ``generator`` command extends ``AbstractGeneratorCommand`` with the ``#[GeneratorCommand]`` attribute.
4141
- **Commands:** The ``make:migration`` command now rejects ``--force`` as an unknown option. It was previously accepted but ignored, since the

‎user_guide_src/source/cli/cli_modern_generators.rst‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -262,8 +262,10 @@ Behavioural changes we need to be aware of when migrating:
262262
generator reported ``EXIT_SUCCESS`` even when the target file already existed. The base class
263263
returns ``EXIT_ERROR`` for an existing file without ``--force``, a write failure, and an undefined
264264
namespace. Declining the ``CodeIgniter`` namespace confirmation still exits with ``EXIT_SUCCESS``.
265-
- **The** ``CodeIgniter`` **namespace confirmation only prompts on interactive runs.** Non-interactive
266-
runs print the warning and proceed instead of blocking on input that will never arrive.
265+
- **The** ``CodeIgniter`` **namespace confirmation is asked once, and only on interactive runs.** The
266+
trait asked for every file. The base class asks once per ``generateClass()`` and reuses the answer for
267+
the views generated after it. Non-interactive runs print the warning and proceed instead of blocking
268+
on input that will never arrive.
267269
- **The** ``CodeIgniter`` **namespace confirmation keys off the target path.** The trait compared
268270
the raw ``--namespace`` option, so an attribute-pinned ``CodeIgniter`` namespace or a spelling like
269271
``--namespace CodeIgniter/`` did not warn. The base class warns exactly when the file would be written
@@ -294,6 +296,13 @@ AbstractGeneratorCommand
294296
Like :php:meth:`generateClass`, but for non-class artifacts. The name is
295297
used as-is, without qualification or suffix handling.
296298

299+
.. php:method:: isCodeIgniterNamespaceDeclined(): bool
300+
301+
Whether the ``CodeIgniter`` namespace confirmation was declined since the
302+
last :php:meth:`generateClass` call. A declined run still returns
303+
``EXIT_SUCCESS``, so check this before generating anything that depends
304+
on the declined file.
305+
297306
.. php:method:: getReplacements(string $class): array
298307
299308
:param string $class: The namespaced class (or view) being generated.

0 commit comments

Comments
 (0)