Skip to content

Commit 04cd26a

Browse files
committed
refactor: migrate db:create command as modern command
1 parent 2ef1571 commit 04cd26a

3 files changed

Lines changed: 137 additions & 75 deletions

File tree

‎system/Commands/Database/CreateDatabase.php‎

Lines changed: 45 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -13,75 +13,60 @@
1313

1414
namespace CodeIgniter\Commands\Database;
1515

16-
use CodeIgniter\CLI\BaseCommand;
16+
use CodeIgniter\CLI\AbstractCommand;
17+
use CodeIgniter\CLI\Attributes\Command;
1718
use CodeIgniter\CLI\CLI;
19+
use CodeIgniter\CLI\Input\Argument;
20+
use CodeIgniter\CLI\Input\Option;
1821
use CodeIgniter\Config\Factories;
19-
use CodeIgniter\Database\SQLite3\Connection;
22+
use CodeIgniter\Database\SQLite3\Connection as SQLite3Connection;
2023
use Config\Database;
2124
use Throwable;
2225

2326
/**
2427
* Creates a new database.
2528
*/
26-
class CreateDatabase extends BaseCommand
29+
#[Command(name: 'db:create', description: 'Create a new database schema.', group: 'Database')]
30+
class CreateDatabase extends AbstractCommand
2731
{
2832
/**
29-
* The group the command is lumped under
30-
* when listing commands.
31-
*
32-
* @var string
33+
* @var list<string>
3334
*/
34-
protected $group = 'Database';
35+
private const VALID_EXTENSIONS = ['db', 'sqlite'];
3536

36-
/**
37-
* The Command's name
38-
*
39-
* @var string
40-
*/
41-
protected $name = 'db:create';
37+
protected function configure(): void
38+
{
39+
$this
40+
->addArgument(new Argument(
41+
name: 'db_name',
42+
description: 'The database name to use.',
43+
required: true,
44+
))
45+
->addOption(new Option(
46+
name: 'ext',
47+
description: 'File extension of the database file for SQLite3. Can be `db` or `sqlite`.',
48+
requiresValue: true,
49+
default: 'db',
50+
));
51+
}
4252

43-
/**
44-
* the Command's short description
45-
*
46-
* @var string
47-
*/
48-
protected $description = 'Create a new database schema.';
53+
protected function interact(array &$arguments, array &$options): void
54+
{
55+
if ($arguments === []) {
56+
$arguments[] = CLI::prompt('Database name', null, 'required');
57+
}
4958

50-
/**
51-
* the Command's usage
52-
*
53-
* @var string
54-
*/
55-
protected $usage = 'db:create <db_name> [options]';
59+
$ext = $this->getUnboundOption('ext', $options);
5660

57-
/**
58-
* The Command's arguments
59-
*
60-
* @var array<string, string>
61-
*/
62-
protected $arguments = [
63-
'db_name' => 'The database name to use',
64-
];
65-
66-
/**
67-
* The Command's options
68-
*
69-
* @var array<string, string>
70-
*/
71-
protected $options = [
72-
'--ext' => 'File extension of the database file for SQLite3. Can be `db` or `sqlite`. Defaults to `db`.',
73-
];
61+
if (is_string($ext) && ! in_array($ext, self::VALID_EXTENSIONS, true)) {
62+
$options['ext'] = CLI::prompt('Please choose a valid file extension', self::VALID_EXTENSIONS, 'required');
63+
}
64+
}
7465

75-
/**
76-
* Creates a new database.
77-
*/
78-
public function run(array $params)
66+
protected function execute(array $arguments, array $options): int
7967
{
80-
$name = array_shift($params);
81-
82-
if (empty($name)) {
83-
$name = CLI::prompt('Database name', null, 'required'); // @codeCoverageIgnore
84-
}
68+
$name = $arguments['db_name'];
69+
assert(is_string($name));
8570

8671
try {
8772
$config = config(Database::class);
@@ -93,12 +78,14 @@ public function run(array $params)
9378

9479
$db = Database::connect();
9580

96-
// Special SQLite3 handling
97-
if ($db instanceof Connection) {
98-
$ext = $params['ext'] ?? CLI::getOption('ext') ?? 'db';
81+
if ($db instanceof SQLite3Connection) {
82+
$ext = $options['ext'];
83+
assert(is_string($ext));
9984

100-
if (! in_array($ext, ['db', 'sqlite'], true)) {
101-
$ext = CLI::prompt('Please choose a valid file extension', ['db', 'sqlite']); // @codeCoverageIgnore
85+
if (! in_array($ext, self::VALID_EXTENSIONS, true)) {
86+
CLI::error(sprintf('Invalid file extension "%s". Use either `db` or `sqlite`.', $ext), 'light_gray', 'red');
87+
88+
return EXIT_ERROR;
10289
}
10390

10491
if ($name !== ':memory:') {
@@ -113,7 +100,6 @@ public function run(array $params)
113100

114101
if (is_file($dbName)) {
115102
CLI::error("Database \"{$dbName}\" already exists.", 'light_gray', 'red');
116-
CLI::newLine();
117103

118104
return EXIT_ERROR;
119105
}
@@ -128,26 +114,21 @@ public function run(array $params)
128114
if (! is_file($db->getDatabase()) && $name !== ':memory:') {
129115
// @codeCoverageIgnoreStart
130116
CLI::error('Database creation failed.', 'light_gray', 'red');
131-
CLI::newLine();
132117

133118
return EXIT_ERROR;
134119
// @codeCoverageIgnoreEnd
135120
}
136121
} elseif (! Database::forge()->createDatabase($name)) {
137-
// @codeCoverageIgnoreStart
138122
CLI::error('Database creation failed.', 'light_gray', 'red');
139-
CLI::newLine();
140123

141124
return EXIT_ERROR;
142-
// @codeCoverageIgnoreEnd
143125
}
144126

145127
CLI::write("Database \"{$name}\" successfully created.", 'green');
146-
CLI::newLine();
147128

148129
return EXIT_SUCCESS;
149130
} catch (Throwable $e) {
150-
$this->showError($e);
131+
$this->renderThrowable($e);
151132

152133
return EXIT_ERROR;
153134
} finally {

‎tests/system/Commands/CreateDatabaseTest.php‎

Lines changed: 91 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,12 @@
1313

1414
namespace CodeIgniter\Commands;
1515

16+
use CodeIgniter\CLI\CLI;
1617
use CodeIgniter\Database\BaseConnection;
1718
use CodeIgniter\Database\OCI8\Connection as OCI8Connection;
1819
use CodeIgniter\Database\SQLite3\Connection as SQLite3Connection;
1920
use CodeIgniter\Test\CIUnitTestCase;
21+
use CodeIgniter\Test\Mock\MockInputOutput;
2022
use CodeIgniter\Test\StreamFilterTrait;
2123
use Config\Database;
2224
use PHPUnit\Framework\Attributes\Group;
@@ -39,13 +41,15 @@ protected function setUp(): void
3941

4042
parent::setUp();
4143

44+
CLI::resetLastWrite();
4245
$this->dropDatabase();
4346
}
4447

4548
protected function tearDown(): void
4649
{
4750
parent::tearDown();
4851

52+
CLI::reset();
4953
$this->dropDatabase();
5054
}
5155

@@ -81,9 +85,9 @@ private function closeDatabaseConnections(): void
8185
$this->setPrivateProperty(Database::class, 'instances', []);
8286
}
8387

84-
protected function getBuffer(): string
88+
private function getUndecoratedBuffer(): string
8589
{
86-
return $this->getStreamFilterBuffer();
90+
return preg_replace('/\e\[[^m]+m/', '', $this->getStreamFilterBuffer()) ?? '';
8791
}
8892

8993
public function testCreateDatabase(): void
@@ -92,8 +96,17 @@ public function testCreateDatabase(): void
9296
$this->markTestSkipped('Needs to run on non-OCI8 drivers.');
9397
}
9498

99+
$name = $this->connection instanceof SQLite3Connection ? 'database.db' : 'database';
100+
95101
command('db:create database');
96-
$this->assertStringContainsString('successfully created.', $this->getBuffer());
102+
$this->assertSame(
103+
<<<EOT
104+
105+
Database "{$name}" successfully created.
106+
107+
EOT,
108+
$this->getUndecoratedBuffer(),
109+
);
97110
}
98111

99112
public function testSqliteDatabaseDuplicated(): void
@@ -104,9 +117,19 @@ public function testSqliteDatabaseDuplicated(): void
104117

105118
command('db:create database');
106119
$this->resetStreamFilterBuffer();
120+
CLI::resetLastWrite();
121+
122+
$database = WRITEPATH . 'database.db';
107123

108124
command('db:create database --ext db');
109-
$this->assertStringContainsString('already exists.', $this->getBuffer());
125+
$this->assertSame(
126+
<<<EOT
127+
128+
Database "{$database}" already exists.
129+
130+
EOT,
131+
$this->getUndecoratedBuffer(),
132+
);
110133
}
111134

112135
public function testOtherDriverDuplicatedDatabase(): void
@@ -119,6 +142,69 @@ public function testOtherDriverDuplicatedDatabase(): void
119142
$this->resetStreamFilterBuffer();
120143

121144
command('db:create database');
122-
$this->assertStringContainsString('Unable to create the specified database.', $this->getBuffer());
145+
$this->assertStringContainsString('Unable to create the specified database.', $this->getUndecoratedBuffer());
146+
}
147+
148+
public function testOtherDriverCreationFailsWithoutDebug(): void
149+
{
150+
if ($this->connection instanceof SQLite3Connection || $this->connection instanceof OCI8Connection) {
151+
$this->markTestSkipped('Needs to run on non-SQLite3 and non-OCI8 drivers.');
152+
}
153+
154+
command('db:create database');
155+
$this->resetStreamFilterBuffer();
156+
157+
$this->connection = Database::connect();
158+
$this->setPrivateProperty($this->connection, 'DBDebug', false);
159+
160+
CLI::resetLastWrite();
161+
command('db:create database');
162+
$this->assertSame(
163+
<<<'EOT'
164+
165+
Database creation failed.
166+
167+
EOT,
168+
$this->getUndecoratedBuffer(),
169+
);
170+
}
171+
172+
public function testSqlitePromptsForInvalidExtension(): void
173+
{
174+
if (! $this->connection instanceof SQLite3Connection) {
175+
$this->markTestSkipped('Needs to run on SQLite3.');
176+
}
177+
178+
$io = new MockInputOutput();
179+
$io->setInputs(['db']);
180+
CLI::setInputOutput($io);
181+
182+
command('db:create database --ext txt');
183+
184+
$this->assertSame(
185+
<<<'EOT'
186+
Please choose a valid file extension [db, sqlite]: db
187+
Database "database.db" successfully created.
188+
189+
EOT,
190+
preg_replace('/\e\[[^m]+m/', '', $io->getOutput()) ?? '',
191+
);
192+
}
193+
194+
public function testSqliteRejectsInvalidExtensionWhenNonInteractive(): void
195+
{
196+
if (! $this->connection instanceof SQLite3Connection) {
197+
$this->markTestSkipped('Needs to run on SQLite3.');
198+
}
199+
200+
command('db:create database --ext txt --no-interaction');
201+
$this->assertSame(
202+
<<<'EOT'
203+
204+
Invalid file extension "txt". Use either `db` or `sqlite`.
205+
206+
EOT,
207+
$this->getUndecoratedBuffer(),
208+
);
123209
}
124210
}

‎utils/phpstan-baseline/empty.notAllowed.neon‎

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,7 @@
1-
# total 210 errors
1+
# total 209 errors
22

33
parameters:
44
ignoreErrors:
5-
-
6-
message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#'
7-
count: 1
8-
path: ../../system/Commands/Database/CreateDatabase.php
9-
105
-
116
message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#'
127
count: 1

0 commit comments

Comments
 (0)