From 304e8c8a59779a4824fc4dffb908c6d7650872df Mon Sep 17 00:00:00 2001 From: Jasper Smet Date: Wed, 7 Oct 2026 08:58:34 +0200 Subject: [PATCH 1/2] Prepare Migrations for CakePHP 6 APIs and dependencies --- .github/workflows/ci.yml | 25 ++-- README.md | 7 +- composer.json | 22 ++-- phpunit.xml.dist | 2 +- rector.php | 3 +- src/BaseMigration.php | 16 +-- src/BaseSeed.php | 18 +-- src/Command/BakeMigrationCommand.php | 12 +- src/Command/BakeMigrationDiffCommand.php | 55 +++----- src/Command/BakeMigrationSnapshotCommand.php | 18 ++- src/Command/BakeSeedCommand.php | 37 +++--- src/Command/BakeSimpleMigrationCommand.php | 74 +++++------ src/Command/DumpCommand.php | 26 ++-- src/Command/EntryCommand.php | 35 +++--- src/Command/MarkMigratedCommand.php | 36 +++--- src/Command/MigrateCommand.php | 69 ++++------ src/Command/ResetCommand.php | 118 +++++++----------- src/Command/RollbackCommand.php | 70 +++++------ src/Command/SeedCommand.php | 81 ++++++------ src/Command/SeedResetCommand.php | 60 ++++----- src/Command/SeedStatusCommand.php | 46 +++---- src/Command/SeedsEntryCommand.php | 35 +++--- src/Command/SnapshotTrait.php | 50 ++++---- src/Command/StatusCommand.php | 103 +++++++-------- src/Command/UpgradeCommand.php | 85 ++++++------- src/Db/Adapter/AbstractAdapter.php | 22 ++-- src/Db/Adapter/AdapterInterface.php | 10 +- src/Db/Adapter/AdapterWrapper.php | 6 +- src/Db/Adapter/MysqlAdapter.php | 10 +- src/Db/Adapter/SqlserverAdapter.php | 2 +- src/Db/Adapter/TimedOutputAdapter.php | 4 +- src/Db/Table/Column.php | 50 ++++---- src/Db/Table/ForeignKey.php | 8 +- src/Db/Table/Index.php | 16 +-- .../PendingMigrationsMiddleware.php | 18 +-- src/Migration/Environment.php | 24 ++-- src/Migration/Manager.php | 26 ++-- src/Migration/ManagerFactory.php | 6 +- src/MigrationInterface.php | 10 +- src/SeedInterface.php | 10 +- .../Command/BakeMigrationCommandTest.php | 2 +- .../Command/BakeMigrationDiffCommandTest.php | 4 +- .../BakeMigrationSnapshotCommandTest.php | 10 +- .../TestCase/Command/BakeSeedCommandTest.php | 2 +- tests/TestCase/Command/CompletionTest.php | 18 +-- tests/TestCase/Command/DumpCommandTest.php | 2 +- tests/TestCase/Command/ResetCommandTest.php | 8 +- .../TestCase/Command/RollbackCommandTest.php | 8 +- tests/TestCase/Command/SeedCommandTest.php | 2 +- tests/TestCase/Command/StatusCommandTest.php | 8 +- tests/TestCase/Command/UpgradeCommandTest.php | 3 +- .../Db/Adapter/RecordingAdapterTest.php | 2 +- .../Db/Adapter/SqlserverAdapterSchemaTest.php | 68 ++++++++++ .../TestCase/Migration/ManagerFactoryTest.php | 17 +++ tests/TestCase/Migration/ManagerTest.php | 2 +- .../schema-dump-test_comparisons_mysql.lock | Bin 1810 -> 1938 bytes .../schema-dump-test_comparisons_pgsql.lock | Bin 1686 -> 1814 bytes .../schema-dump-test_comparisons_mysql.lock | Bin 1290 -> 1373 bytes .../schema-dump-test_comparisons_mysql.lock | Bin 8627 -> 9487 bytes .../schema-dump-test_comparisons_pgsql.lock | Bin 8082 -> 8696 bytes .../comparisons/Diff/refresh_schema_dumps.php | 16 +-- .../schema-dump-test_comparisons_mysql.lock | Bin 3620 -> 3933 bytes .../schema-dump-test_comparisons_pgsql.lock | Bin 3437 -> 3750 bytes .../schema-dump-test_comparisons_mysql.lock | Bin 896 -> 934 bytes .../schema-dump-test_comparisons_mysql.lock | Bin 896 -> 934 bytes .../schema-dump-test_comparisons_mysql.lock | Bin 896 -> 934 bytes .../CustomBakeMigrationDiffCommand.php | 19 ++- 67 files changed, 709 insertions(+), 807 deletions(-) create mode 100644 tests/TestCase/Db/Adapter/SqlserverAdapterSchemaTest.php diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b1ca9ed4b..5c2257473 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -7,6 +7,7 @@ on: - 4.next - 5.x - 5.next + - 6.x paths-ignore: - docs/** pull_request: @@ -25,20 +26,20 @@ jobs: strategy: fail-fast: false matrix: - php-version: ['8.2', '8.5'] + php-version: ['8.4', '8.5'] db-type: [mariadb, mysql, pgsql, sqlite] prefer-lowest: [''] legacy-tables: [''] include: - - php-version: '8.2' + - php-version: '8.4' db-type: 'sqlite' prefer-lowest: 'prefer-lowest' - - php-version: '8.3' + - php-version: '8.4' db-type: 'mysql' - - php-version: '8.3' + - php-version: '8.4' db-type: 'pgsql' # Test unified cake_migrations table (non-legacy mode) - - php-version: '8.3' + - php-version: '8.4' db-type: 'mysql' legacy-tables: 'false' services: @@ -125,9 +126,7 @@ jobs: - name: Composer install run: | - if [[ ${{ matrix.php-version }} == '8.2' || ${{ matrix.php-version }} == '8.3' || ${{ matrix.php-version }} == '8.4' ]]; then - composer install - elif ${{ matrix.prefer-lowest == 'prefer-lowest' }}; then + if ${{ matrix.prefer-lowest == 'prefer-lowest' }}; then composer update --prefer-lowest --prefer-stable else composer update @@ -158,23 +157,23 @@ jobs: if [[ -n '${{ matrix.legacy-tables }}' ]]; then export LEGACY_TABLES='${{ matrix.legacy-tables }}' fi - if [[ ${{ matrix.php-version }} == '8.1' && ${{ matrix.db-type }} == 'mysql' ]]; then + if [[ ${{ matrix.php-version }} == '8.4' && ${{ matrix.db-type }} == 'mysql' ]]; then vendor/bin/phpunit --coverage-clover=coverage.xml else vendor/bin/phpunit fi - name: Code Coverage Report - if: success() && matrix.php-version == '8.1' && matrix.db-type == 'mysql' + if: success() && matrix.php-version == '8.4' && matrix.db-type == 'mysql' uses: codecov/codecov-action@v7 testsuite-windows: runs-on: windows-2022 - name: Windows - PHP 8.2 & SQL Server + name: Windows - PHP 8.4 & SQL Server env: EXTENSIONS: mbstring, intl, pdo_sqlsrv - PHP_VERSION: '8.2' + PHP_VERSION: '8.4' steps: - uses: actions/checkout@v7 @@ -243,5 +242,5 @@ jobs: uses: codecov/codecov-action@v7 cs-stan: - uses: cakephp/.github/.github/workflows/cs-stan.yml@5.x + uses: cakephp/.github/.github/workflows/cs-stan.yml@6.x secrets: inherit diff --git a/README.md b/README.md index 7d4bacbf2..83b2725e8 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,10 @@ This is a Database Migrations system for CakePHP. The plugin provides a complete database migration solution with support for creating, running, and managing migrations. -This branch is for use with CakePHP **5.x**. See [version map](https://github.com/cakephp/migrations/wiki#version-map) for details. +This branch is for use with CakePHP **6.x**, requiring PHP 8.4 or higher. See [version map](https://github.com/cakephp/migrations/wiki#version-map) for details. + +When upgrading from CakePHP 5, regenerate schema dump files with `bin/cake migrations dump` +before baking a diff. Serialized schema metadata uses CakePHP 6's property names. ## Installation @@ -17,7 +20,7 @@ You can install this plugin into your CakePHP application using [Composer](https Run the following command ```sh -composer require cakephp/migrations +composer require cakephp/migrations:"6.x-dev" ``` ## Configuration diff --git a/composer.json b/composer.json index 8cdefb5e9..67461455b 100644 --- a/composer.json +++ b/composer.json @@ -22,22 +22,22 @@ "source": "https://github.com/cakephp/migrations" }, "require": { - "php": ">=8.2", - "cakephp/cache": "^5.3.0", - "cakephp/database": "^5.3.2", - "cakephp/orm": "^5.3.0" + "php": ">=8.4", + "cakephp/cache": "^6.0", + "cakephp/database": "^6.0", + "cakephp/orm": "^6.0" }, "require-dev": { - "cakephp/bake": "^3.3", - "cakephp/cakephp": "^5.3.2", - "cakephp/cakephp-codesniffer": "^5.0", - "phpunit/phpunit": "^11.5.3 || ^12.1.3 || ^13.0" + "cakephp/bake": "^4.0", + "cakephp/cakephp": "^6.0", + "cakephp/cakephp-codesniffer": "^6.0", + "phpunit/phpunit": "^12.1.3 || ^13.0" }, "suggest": { "cakephp/bake": "If you want to generate migrations.", "dereuromark/cakephp-ide-helper": "If you want to have IDE suggest/autocomplete when creating migrations." }, - "minimum-stability": "stable", + "minimum-stability": "dev", "prefer-stable": true, "autoload": { "psr-4": { @@ -46,15 +46,13 @@ }, "autoload-dev": { "psr-4": { - "Blog\\": "tests/test_app/Plugin/Blog/src/", "Cake\\Test\\": "./vendor/cakephp/cakephp/tests/", "Migrations\\Test\\": "tests/", "Migrator\\": "tests/test_app/Plugin/Migrator/src/", "SimpleSnapshot\\": "tests/test_app/Plugin/SimpleSnapshot/src/", "TestApp\\": "tests/test_app/App/", "TestBlog\\": "tests/test_app/Plugin/TestBlog/src/", - "Blog\\": "tests/test_app/Plugin/Blog/src/", - "Migrator\\": "tests/test_app/Plugin/Migrator/src/" + "Blog\\": "tests/test_app/Plugin/Blog/src/" } }, "config": { diff --git a/phpunit.xml.dist b/phpunit.xml.dist index 673769206..2a1f57dca 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -3,7 +3,7 @@ colors="true" cacheDirectory=".phpunit.cache" bootstrap="tests/bootstrap.php" - xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/10.5/phpunit.xsd" + xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/12.1/phpunit.xsd" > diff --git a/rector.php b/rector.php index a93e7edcf..7c39d4397 100644 --- a/rector.php +++ b/rector.php @@ -28,7 +28,8 @@ cacheDirectory: $cacheDir, ) - ->withPhpSets() + // Keep language modernization separate from the CakePHP 6 API upgrade. + ->withPhpSets(php82: true) ->withAttributesSets() ->withSets([ diff --git a/src/BaseMigration.php b/src/BaseMigration.php index 6d61260b1..4a7683256 100644 --- a/src/BaseMigration.php +++ b/src/BaseMigration.php @@ -8,7 +8,7 @@ namespace Migrations; -use Cake\Console\ConsoleIo; +use Cake\Console\ConsoleIoInterface; use Cake\Database\Query; use Cake\Database\Query\DeleteQuery; use Cake\Database\Query\InsertQuery; @@ -34,9 +34,9 @@ class BaseMigration implements MigrationInterface protected ?AdapterInterface $adapter = null; /** - * The ConsoleIo instance + * The ConsoleIoInterface instance */ - protected ?ConsoleIo $io = null; + protected ?ConsoleIoInterface $io = null; /** * The config instance. @@ -108,7 +108,7 @@ public function getAdapter(): AdapterInterface /** * {@inheritDoc} */ - public function setIo(ConsoleIo $io) + public function setIo(ConsoleIoInterface $io) { $this->io = $io; @@ -118,7 +118,7 @@ public function setIo(ConsoleIo $io) /** * {@inheritDoc} */ - public function getIo(): ?ConsoleIo + public function getIo(): ?ConsoleIoInterface { return $this->io; } @@ -155,7 +155,7 @@ public function getName(): string * @param int $version Version * @return $this */ - public function setVersion(int $version) + public function setVersion(int $version): static { $this->validateVersion($version); $this->version = $version; @@ -179,7 +179,7 @@ public function getVersion(): int * @param bool $isMigratingUp True if the migration is being applied * @return $this */ - public function setMigratingUp(bool $isMigratingUp) + public function setMigratingUp(bool $isMigratingUp): static { $this->isMigratingUp = $isMigratingUp; @@ -448,7 +448,7 @@ public function preFlightCheck(): void { if (method_exists($this, MigrationInterface::CHANGE) && (method_exists($this, MigrationInterface::UP) || method_exists($this, MigrationInterface::DOWN))) { $io = $this->getIo(); - if ($io instanceof ConsoleIo) { + if ($io instanceof ConsoleIoInterface) { $io->out( 'warning Migration contains both change() and up()/down() methods.' . ' Ignoring up() and down().', diff --git a/src/BaseSeed.php b/src/BaseSeed.php index 8cde6fb73..7ee4b98db 100644 --- a/src/BaseSeed.php +++ b/src/BaseSeed.php @@ -8,7 +8,7 @@ namespace Migrations; -use Cake\Console\ConsoleIo; +use Cake\Console\ConsoleIoInterface; use Migrations\Config\ConfigInterface; use Migrations\Db\Adapter\AdapterInterface; use Migrations\Db\Table; @@ -29,9 +29,9 @@ class BaseSeed implements SeedInterface protected ?AdapterInterface $adapter = null; /** - * The ConsoleIo instance + * The ConsoleIoInterface instance */ - protected ?ConsoleIo $io = null; + protected ?ConsoleIoInterface $io = null; /** * The config instance. @@ -78,7 +78,7 @@ public function getAdapter(): AdapterInterface /** * {@inheritDoc} */ - public function setIo(ConsoleIo $io) + public function setIo(ConsoleIoInterface $io) { $this->io = $io; @@ -88,7 +88,7 @@ public function setIo(ConsoleIo $io) /** * {@inheritDoc} */ - public function getIo(): ?ConsoleIo + public function getIo(): ?ConsoleIoInterface { return $this->io; } @@ -223,8 +223,8 @@ public function isIdempotent(): bool public function call(string $seeder, array $options = []): void { $io = $this->getIo(); - if (!$io instanceof ConsoleIo) { - throw new RuntimeException('ConsoleIo is required for calling other seeders.'); + if (!$io instanceof ConsoleIoInterface) { + throw new RuntimeException('ConsoleIoInterface is required for calling other seeders.'); } $io->out(''); $io->out( @@ -272,8 +272,8 @@ protected function runCall(string $seeder, array $options = []): void 'source' => $options['source'], ]); $io = $this->getIo(); - if (!$io instanceof ConsoleIo) { - throw new RuntimeException('ConsoleIo is required for calling other seeders.'); + if (!$io instanceof ConsoleIoInterface) { + throw new RuntimeException('ConsoleIoInterface is required for calling other seeders.'); } $manager = $factory->createManager($io); $manager->seed($seeder); diff --git a/src/Command/BakeMigrationCommand.php b/src/Command/BakeMigrationCommand.php index ce9af3cb2..55bdf7076 100644 --- a/src/Command/BakeMigrationCommand.php +++ b/src/Command/BakeMigrationCommand.php @@ -15,8 +15,6 @@ */ namespace Migrations\Command; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIo; use Cake\Console\ConsoleOptionParser; use Cake\Core\Configure; use Cake\Event\Event; @@ -42,7 +40,7 @@ public static function defaultName(): string /** * @inheritDoc */ - protected function bake(string $name, Arguments $args, ConsoleIo $io): void + protected function bake(string $name): void { EventManager::instance()->on('Bake.initialize', function (Event $event): void { /** @var \Bake\View\BakeView $view */ @@ -51,7 +49,7 @@ protected function bake(string $name, Arguments $args, ConsoleIo $io): void }); $this->_name = $name; - parent::bake($name, $args, $io); + parent::bake($name); } /** @@ -70,18 +68,18 @@ public function template(): string /** * @inheritDoc */ - public function templateData(Arguments $arguments): array + public function templateData(): array { $className = $this->_name; $namespace = Configure::read('App.namespace'); $pluginPath = ''; if ($this->plugin) { - $namespace = $this->_pluginNamespace($this->plugin); + $namespace = $this->pluginNamespace($this->plugin); $pluginPath = $this->plugin . '.'; } /** @var array $args */ - $args = $arguments->getArguments(); + $args = $this->args->getArguments(); unset($args[0]); $columnParser = new ColumnParser(); $fields = $columnParser->parseFields($args); diff --git a/src/Command/BakeMigrationDiffCommand.php b/src/Command/BakeMigrationDiffCommand.php index e03c8b1eb..b57e9faa0 100644 --- a/src/Command/BakeMigrationDiffCommand.php +++ b/src/Command/BakeMigrationDiffCommand.php @@ -15,8 +15,6 @@ */ namespace Migrations\Command; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIo; use Cake\Console\ConsoleOptionParser; use Cake\Database\Connection; use Cake\Database\Schema\CachedCollection; @@ -121,17 +119,17 @@ public static function defaultName(): string /** * @inheritDoc */ - protected function bake(string $name, Arguments $args, ConsoleIo $io): void + protected function bake(string $name): void { - $this->setup($args); + $this->setup(); if (!$this->checkSync()) { - $io->abort('Your migrations history is not in sync with your migrations files. ' . + $this->io->abort('Your migrations history is not in sync with your migrations files. ' . 'Make sure all your migrations have been migrated before baking a diff.'); } if (!$this->migrationsFiles && !$this->migratedItems) { - $this->bakeSnapshot($name, $args, $io); + $this->bakeSnapshot($name); } $collection = $this->getCollection($this->connection); @@ -148,26 +146,23 @@ protected function bake(string $name, Arguments $args, ConsoleIo $io): void ]); }); - parent::bake($name, $args, $io); + parent::bake($name); } /** * Sets up everything the baking process needs * - * @param \Cake\Console\Arguments $args The command arguments. * @return void */ - protected function setup(Arguments $args): void + protected function setup(): void { - $this->migrationsPath = $this->getPath($args); + $this->migrationsPath = $this->getPath(); $this->migrationsFiles = glob($this->migrationsPath . '*.php') ?: []; $this->phinxTable = $this->getPhinxTable($this->plugin); - $connection = ConnectionManager::get($this->connection); assert($connection instanceof Connection); $this->tables = $connection->getSchemaCollection()->listTables(); $tableExists = in_array($this->phinxTable, $this->tables, true); - $migratedItems = []; if ($tableExists) { $query = $connection->selectQuery() @@ -180,10 +175,8 @@ protected function setup(Arguments $args): void $query->where(['plugin IS' => $this->plugin]); } - /** @var array $migratedItems */ $migratedItems = $query->execute()->fetchAll('assoc'); } - $this->migratedItems = $migratedItems; } @@ -204,9 +197,9 @@ public function getCollection(string $connection): CollectionInterface /** * @inheritDoc */ - public function templateData(Arguments $arguments): array + public function templateData(): array { - $this->dumpSchema = $this->getDumpSchema($arguments); + $this->dumpSchema = $this->getDumpSchema(); $this->currentSchema = $this->getCurrentSchema(); $this->commonTables = array_intersect_key($this->currentSchema, $this->dumpSchema); @@ -560,23 +553,21 @@ protected function checkSync(): bool * there are no migration files. * * @param string $name Name. - * @param \Cake\Console\Arguments $args The command arguments. - * @param \Cake\Console\ConsoleIo $io The console io * @return int|null Value of the snapshot baking dispatch process */ - protected function bakeSnapshot(string $name, Arguments $args, ConsoleIo $io): ?int + protected function bakeSnapshot(string $name): ?int { - $io->out('Your migrations history is empty and you do not have any migrations files.'); - $io->out('Falling back to baking a snapshot...'); + $this->io->out('Your migrations history is empty and you do not have any migrations files.'); + $this->io->out('Falling back to baking a snapshot...'); $newArgs = []; $newArgs[] = $name; - $newArgs = array_merge($newArgs, $this->parseOptions($args)); - $exitCode = $this->executeCommand(BakeMigrationSnapshotCommand::class, $newArgs, $io); + $newArgs = array_merge($newArgs, $this->parseOptions()); + $exitCode = $this->executeCommand(BakeMigrationSnapshotCommand::class, $newArgs); if ($exitCode === 1) { - $io->abort('Something went wrong during the snapshot baking. Please try again.'); + $this->io->abort('Something went wrong during the snapshot baking. Please try again.'); } return $exitCode; @@ -586,33 +577,27 @@ protected function bakeSnapshot(string $name, Arguments $args, ConsoleIo $io): ? * Fetch the correct schema dump based on the arguments and options passed to the shell call * and returns it as an array * - * @param \Cake\Console\Arguments $args The command arguments. * @return array Full database schema. */ - protected function getDumpSchema(Arguments $args): array + protected function getDumpSchema(): array { $options = []; - $connectionName = 'default'; - if ($args->getOption('connection')) { - $connectionName = $inputArgs['--connection'] = $args->getOption('connection'); + if ($this->args->getOption('connection')) { + $connectionName = $inputArgs['--connection'] = $this->args->getOption('connection'); } $options['connection'] = $connectionName; - $options['source'] = $args->getOption('source'); - $options['plugin'] = $args->getOption('plugin'); - + $options['source'] = $this->args->getOption('source'); + $options['plugin'] = $this->args->getOption('plugin'); $factory = new ManagerFactory($options); $config = $factory->createConfig(); - $path = $config->getMigrationPath() . DS . 'schema-dump-' . $connectionName . '.lock'; if (!file_exists($path)) { $msg = 'Unable to retrieve the schema dump file. You can create a dump file using ' . 'the `cake migrations dump` command'; $this->io->abort($msg); } - $contents = (string)file_get_contents($path); - // Use allowed_classes to restrict deserialization to safe CakePHP schema classes return unserialize($contents, [ 'allowed_classes' => [ diff --git a/src/Command/BakeMigrationSnapshotCommand.php b/src/Command/BakeMigrationSnapshotCommand.php index 375235255..be34b1d68 100644 --- a/src/Command/BakeMigrationSnapshotCommand.php +++ b/src/Command/BakeMigrationSnapshotCommand.php @@ -15,8 +15,6 @@ */ namespace Migrations\Command; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIo; use Cake\Console\ConsoleOptionParser; use Cake\Core\Configure; use Cake\Database\Connection; @@ -56,7 +54,7 @@ public static function defaultName(): string /** * @inheritDoc */ - protected function bake(string $name, Arguments $args, ConsoleIo $io): void + protected function bake(string $name): void { $collection = $this->getCollection($this->connection); @@ -73,7 +71,7 @@ protected function bake(string $name, Arguments $args, ConsoleIo $io): void }); $this->_name = $name; - parent::bake($name, $args, $io); + parent::bake($name); } /** @@ -87,18 +85,18 @@ public function template(): string /** * @inheritDoc */ - public function templateData(Arguments $arguments): array + public function templateData(): array { $namespace = Configure::read('App.namespace'); $pluginPath = ''; if ($this->plugin) { - $namespace = $this->_pluginNamespace($this->plugin); + $namespace = $this->pluginNamespace($this->plugin); $pluginPath = $this->plugin . '.'; } $collection = $this->getCollection($this->connection); $options = [ - 'require-table' => $arguments->getOption('require-table'), + 'require-table' => $this->args->getOption('require-table'), 'plugin' => $this->plugin, ]; $finder = new TableFinder($this->connection); @@ -109,11 +107,11 @@ public function templateData(Arguments $arguments): array $tables = array_combine($tables, $tables); $autoId = true; - if ($arguments->hasOption('disable-autoid')) { - $autoId = !$arguments->getOption('disable-autoid'); + if ($this->args->hasOption('disable-autoid')) { + $autoId = !$this->args->getOption('disable-autoid'); } - $useChange = (bool)$arguments->getOption('change'); + $useChange = (bool)$this->args->getOption('change'); return [ 'plugin' => $this->plugin, diff --git a/src/Command/BakeSeedCommand.php b/src/Command/BakeSeedCommand.php index 3eed89180..e9bd86acb 100644 --- a/src/Command/BakeSeedCommand.php +++ b/src/Command/BakeSeedCommand.php @@ -17,7 +17,6 @@ use Bake\Command\SimpleBakeCommand; use Cake\Console\Arguments; -use Cake\Console\ConsoleIo; use Cake\Console\ConsoleOptionParser; use Cake\Core\Configure; use Cake\Datasource\ConnectionManager; @@ -37,11 +36,6 @@ class BakeSeedCommand extends SimpleBakeCommand protected string $_name; - /** - * Arguments - */ - protected Arguments $args; - /** * @inheritDoc */ @@ -77,11 +71,11 @@ public function fileName($name): string /** * @inheritDoc */ - public function getPath(Arguments $args): string + public function getPath(): string { $path = ROOT . DS . $this->pathFragment; if ($this->plugin) { - $path = $this->_pluginPath($this->plugin) . $this->pathFragment; + $path = $this->pluginPath($this->plugin) . $this->pathFragment; } return str_replace('/', DS, $path); @@ -103,28 +97,27 @@ public function template(): string /** * Get template data. * - * @param \Cake\Console\Arguments $arguments The arguments for the command * @return array * @phpstan-return array */ - public function templateData(Arguments $arguments): array + public function templateData(): array { $namespace = Configure::read('App.namespace'); if ($this->plugin) { - $namespace = $this->_pluginNamespace($this->plugin); + $namespace = $this->pluginNamespace($this->plugin); } - $table = Inflector::underscore((string)$arguments->getArgumentAt(0)); - if ($arguments->hasOption('table')) { + $table = Inflector::underscore((string)$this->args->getArgumentAt(0)); + if ($this->args->hasOption('table')) { /** @var string $table */ - $table = $arguments->getOption('table'); + $table = $this->args->getOption('table'); } $records = false; - if ($arguments->getOption('data')) { - $limit = (int)$arguments->getOption('limit'); + if ($this->args->getOption('data')) { + $limit = (int)$this->args->getOption('limit'); - $fields = (string)$arguments->getOption('fields') ?: '*'; + $fields = (string)$this->args->getOption('fields') ?: '*'; if ($fields !== '*') { $fields = explode(',', $fields); } @@ -160,18 +153,18 @@ public function templateData(Arguments $arguments): array /** * @inheritDoc */ - protected function bake(string $name, Arguments $args, ConsoleIo $io): void + protected function bake(string $name): void { - $this->args = $args; /** @var array $options */ - $options = array_merge($args->getOptions(), ['no-test' => true]); + $options = array_merge($this->args->getOptions(), ['no-test' => true]); $newArgs = new Arguments( - $args->getArguments(), + $this->args->getArguments(), $options, ['name'], ); $this->_name = $name; - parent::bake($name, $newArgs, $io); + $this->args = $newArgs; + parent::bake($name); } /** diff --git a/src/Command/BakeSimpleMigrationCommand.php b/src/Command/BakeSimpleMigrationCommand.php index b85f0f7e3..faf154a95 100644 --- a/src/Command/BakeSimpleMigrationCommand.php +++ b/src/Command/BakeSimpleMigrationCommand.php @@ -17,8 +17,6 @@ use Bake\Command\SimpleBakeCommand; use Bake\Utility\TemplateRenderer; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIo; use Cake\Console\ConsoleOptionParser; use Cake\Core\Configure; use Cake\Core\Plugin; @@ -47,16 +45,6 @@ abstract class BakeSimpleMigrationCommand extends SimpleBakeCommand */ public string $pathFragment = 'config'; - /** - * Console IO - */ - protected ConsoleIo $io; - - /** - * Arguments - */ - protected Arguments $args; - /** * @inheritDoc */ @@ -84,7 +72,7 @@ public function fileName($name): string $time = substr($timestamp, 8); $camelName = Inflector::camelize($name); - $path = $this->getPath($this->args); + $path = $this->getPath(); $offset = 0; while (glob($path . $readableDate . '_' . $time . '_*.php')) { $timestamp = Util::getCurrentTimestamp(++$offset); @@ -100,7 +88,7 @@ public function fileName($name): string $timestamp = Util::getCurrentTimestamp(); $suffix = '_' . Inflector::camelize($name) . '.php'; - $path = $this->getPath($this->args); + $path = $this->getPath(); $offset = 0; while (glob($path . $timestamp . '_*.php')) { $timestamp = Util::getCurrentTimestamp(++$offset); @@ -112,12 +100,12 @@ public function fileName($name): string /** * @inheritDoc */ - public function getPath(Arguments $args): string + public function getPath(): string { - $migrationFolder = $this->pathFragment . DS . $args->getOption('source') . DS; + $migrationFolder = $this->pathFragment . DS . $this->args->getOption('source') . DS; $path = ROOT . DS . $migrationFolder; if ($this->plugin) { - $path = $this->_pluginPath($this->plugin) . $migrationFolder; + $path = $this->pluginPath($this->plugin) . $migrationFolder; } return str_replace('/', DS, $path); @@ -126,21 +114,21 @@ public function getPath(Arguments $args): string /** * @inheritDoc */ - public function execute(Arguments $args, ConsoleIo $io): ?int + public function execute(): ?int { if (!Plugin::isLoaded('Bake')) { - $io->err('Bake plugin is not loaded. Please load it first to generate a migration.'); + $this->io->err('Bake plugin is not loaded. Please load it first to generate a migration.'); $this->abort(); } - $this->extractCommonProperties($args); - $name = $args->getArgumentAt(0); + $this->extractCommonProperties($this->args); + $name = $this->args->getArgumentAt(0); if (!$name) { - $io->err('You must provide a name to bake a ' . $this->name()); + $this->io->err('You must provide a name to bake a ' . $this->name()); $this->abort(); } - $name = $this->_getName($name); + $name = $this->getNameWithoutPrefix($name); $name = Inflector::camelize($name); - $this->bake($name, $args, $io); + $this->bake($name); return static::CODE_SUCCESS; } @@ -148,20 +136,18 @@ public function execute(Arguments $args, ConsoleIo $io): ?int /** * @inheritDoc */ - protected function bake(string $name, Arguments $args, ConsoleIo $io): void + protected function bake(string $name): void { - $this->io = $io; - $this->args = $args; if ($this->isReservedKeyword($name)) { - $prefix = $io->ask('Reserved keywords cannot be used for class names. What prefix would you like to use? Defaults to `Migration`.', 'Migration'); + $prefix = $this->io->ask('Reserved keywords cannot be used for class names. What prefix would you like to use? Defaults to `Migration`.', 'Migration'); $name = $prefix . ucfirst($name); } - $migrationWithSameName = glob($this->getPath($args) . '*_' . $name . '.php'); + $migrationWithSameName = glob($this->getPath() . '*_' . $name . '.php'); if ($migrationWithSameName) { - $force = $args->getOption('force'); + $force = $this->args->getOption('force'); if (!$force) { - $io->abort( + $this->io->abort( sprintf( 'A migration with the name `%s` already exists. Please use a different name.', $name, @@ -169,41 +155,39 @@ protected function bake(string $name, Arguments $args, ConsoleIo $io): void ); } - $io->info(sprintf('A migration with the name `%s` already exists, it will be deleted.', $name)); + $this->io->info(sprintf('A migration with the name `%s` already exists, it will be deleted.', $name)); foreach ($migrationWithSameName as $migration) { - $io->info(sprintf('Deleting migration file `%s`...', $migration)); + $this->io->info(sprintf('Deleting migration file `%s`...', $migration)); if (unlink($migration)) { - $io->success(sprintf('Deleted `%s`', $migration)); + $this->io->success(sprintf('Deleted `%s`', $migration)); } else { - $io->err(sprintf('An error occurred while deleting `%s`', $migration)); + $this->io->err(sprintf('An error occurred while deleting `%s`', $migration)); } } } $renderer = new TemplateRenderer($this->theme); $renderer->set('name', $name); - $renderer->set($this->templateData($args)); + $renderer->set($this->templateData()); $contents = $renderer->generate($this->template()); - $path = $this->getPath($args); + $path = $this->getPath(); $filename = $path . $this->fileName($name); - $this->createFile($filename, $contents, $args, $io); + $this->createFile($filename, $contents); $emptyFile = $path . '.gitkeep'; - $this->deleteEmptyFile($emptyFile, $io); + $this->deleteEmptyFile($emptyFile); } /** * @param string $path Where to put the file. * @param string $contents Content to put in the file. - * @param \Cake\Console\Arguments $args The command arguments. - * @param \Cake\Console\ConsoleIo $io The console io * @return bool Success */ - protected function createFile(string $path, string $contents, Arguments $args, ConsoleIo $io): bool + protected function createFile(string $path, string $contents): bool { - return $io->createFile($path, $contents); + return $this->io->createFile($path, $contents); } /** @@ -220,7 +204,7 @@ protected function getMigrationName(?string $name = null): string $this->io->abort('Choose a migration name to bake in CamelCase format'); } - $name = $this->_getName($name); + $name = $this->getNameWithoutPrefix($name); $name = Inflector::camelize($name); if (!preg_match('/^[A-Z]{1}[a-zA-Z0-9]+$/', $name)) { @@ -238,7 +222,7 @@ protected function getMigrationName(?string $name = null): string */ protected function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionParser { - $parser = $this->_setCommonOptions($parser); + $parser = $this->setCommonOptions($parser); $parser->setDescription( 'Bake migration class.', diff --git a/src/Command/DumpCommand.php b/src/Command/DumpCommand.php index 10bf3982d..e81e54ea2 100644 --- a/src/Command/DumpCommand.php +++ b/src/Command/DumpCommand.php @@ -15,7 +15,6 @@ use Cake\Command\Command; use Cake\Console\Arguments; -use Cake\Console\ConsoleIo; use Cake\Console\ConsoleOptionParser; use Cake\Database\Connection; use Cake\Datasource\ConnectionManager; @@ -53,6 +52,7 @@ public static function defaultName(): string /** * Extract options for the dump command from another migrations option parser. * + * @param \Cake\Console\Arguments $args The command arguments. * @return array */ public static function extractArgs(Arguments $args): array @@ -106,53 +106,47 @@ protected function buildOptionParser(ConsoleOptionParser $parser): ConsoleOption /** * Execute the command. * - * @param \Cake\Console\Arguments $args The command arguments. - * @param \Cake\Console\ConsoleIo $io The console io * @return int|null The exit code or null for success */ - public function execute(Arguments $args, ConsoleIo $io): ?int + public function execute(): ?int { $factory = new ManagerFactory([ - 'plugin' => $args->getOption('plugin'), - 'source' => $args->getOption('source'), - 'connection' => $args->getOption('connection'), + 'plugin' => $this->args->getOption('plugin'), + 'source' => $this->args->getOption('source'), + 'connection' => $this->args->getOption('connection'), ]); $config = $factory->createConfig(); $path = $config->getMigrationPath(); - if (!is_dir($path)) { - $io->verbose('No migrations directory found, skipping dump.'); + $this->io->verbose('No migrations directory found, skipping dump.'); return self::CODE_SUCCESS; } $connectionName = (string)$config->getConnection(); $connection = ConnectionManager::get($connectionName); assert($connection instanceof Connection); - $collection = $connection->getSchemaCollection(); $options = [ 'require-table' => false, - 'plugin' => $args->getOption('plugin'), + 'plugin' => $this->args->getOption('plugin'), ]; // The connection property is used by the trait methods. $this->connection = $connectionName; $finder = new TableFinder($connectionName); $tables = $finder->getTablesToBake($collection, $options); - $dump = []; foreach ($tables as $table) { $schema = $collection->describe($table); $dump[$table] = $schema; } - $filePath = $path . DS . 'schema-dump-' . $connectionName . '.lock'; - $io->verbose(sprintf('Writing dump file `%s`...', $filePath)); + $this->io->verbose(sprintf('Writing dump file `%s`...', $filePath)); if (file_put_contents($filePath, serialize($dump))) { - $io->verbose(sprintf('Dump file `%s` was successfully written', $filePath)); + $this->io->verbose(sprintf('Dump file `%s` was successfully written', $filePath)); return self::CODE_SUCCESS; } - $io->err(sprintf('An error occurred while writing dump file `%s`', $filePath)); + $this->io->err(sprintf('An error occurred while writing dump file `%s`', $filePath)); return self::CODE_ERROR; } diff --git a/src/Command/EntryCommand.php b/src/Command/EntryCommand.php index 0577b2dbc..eda88486d 100644 --- a/src/Command/EntryCommand.php +++ b/src/Command/EntryCommand.php @@ -21,7 +21,7 @@ use Cake\Console\Command\HelpCommand; use Cake\Console\CommandCollection; use Cake\Console\CommandCollectionAwareInterface; -use Cake\Console\ConsoleIo; +use Cake\Console\ConsoleIoInterface; use Cake\Console\Exception\ConsoleException; /** @@ -56,64 +56,65 @@ public function setCommandCollection(CommandCollection $commands): void * Override the run() method for special handling of the `--help` option. * * @param array $argv Arguments from the CLI environment. - * @param \Cake\Console\ConsoleIo $io The console io + * @param \Cake\Console\ConsoleIoInterface|null $io The console IO. * @return int|null Exit code or null for success. */ - public function run(array $argv, ConsoleIo $io): ?int + public function run(array $argv, ?ConsoleIoInterface $io = null): ?int { + if ($io instanceof ConsoleIoInterface) { + $this->io = $io; + } $this->initialize(); $parser = $this->getOptionParser(); try { [$options, $arguments] = $parser->parse($argv); - $args = new Arguments( + $this->args = new Arguments( $arguments, $options, $parser->argumentNames(), ); } catch (ConsoleException $e) { - $io->err('Error: ' . $e->getMessage()); + $this->io->err('Error: ' . $e->getMessage()); return static::CODE_ERROR; } - $this->setOutputLevel($args, $io); + $this->setOutputLevel(); // This is the variance from Command::run() - if (!$args->getArgumentAt(0) && $args->getOption('help')) { - $io->out([ + if (!$this->args->getArgumentAt(0) && $this->args->getOption('help')) { + $this->io->out([ 'Migrations', '', "Migrations provides commands for managing your application's database schema and initial data.", '', ]); $help = $this->getHelp(); - $this->executeCommand($help, [], $io); + $this->executeCommand($help, []); return static::CODE_SUCCESS; } - return $this->execute($args, $io); + return $this->execute(); } /** * Execute the command. * - * @param \Cake\Console\Arguments $args The command arguments. - * @param \Cake\Console\ConsoleIo $io The console io * @return int|null The exit code or null for success */ - public function execute(Arguments $args, ConsoleIo $io): ?int + public function execute(): ?int { - if ($args->hasArgumentAt(0)) { - $name = $args->getArgumentAt(0); - $io->err( + if ($this->args->hasArgumentAt(0)) { + $name = $this->args->getArgumentAt(0); + $this->io->err( sprintf('Could not find migrations command named `%s`.', $name) . ' Run `migrations --help` to get a list of commands.', ); return static::CODE_ERROR; } - $io->err('No command provided. Run `migrations --help` to get a list of commands.'); + $this->io->err('No command provided. Run `migrations --help` to get a list of commands.'); return static::CODE_ERROR; } diff --git a/src/Command/MarkMigratedCommand.php b/src/Command/MarkMigratedCommand.php index cbfe55014..3dbbe5c81 100644 --- a/src/Command/MarkMigratedCommand.php +++ b/src/Command/MarkMigratedCommand.php @@ -14,8 +14,6 @@ namespace Migrations\Command; use Cake\Command\Command; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIo; use Cake\Console\ConsoleOptionParser; use InvalidArgumentException; use Migrations\Config\ConfigInterface; @@ -98,55 +96,49 @@ protected function buildOptionParser(ConsoleOptionParser $parser): ConsoleOption /** * Checks for an invalid use of `--exclude` or `--only` * - * @param \Cake\Console\Arguments $args The console arguments * @return bool Returns true when it is an invalid use of `--exclude` or `--only` otherwise false */ - protected function invalidOnlyOrExclude(Arguments $args): bool + protected function invalidOnlyOrExclude(): bool { - if ($args->getOption('exclude') && $args->getOption('only')) { + if ($this->args->getOption('exclude') && $this->args->getOption('only')) { return true; } - return ($args->getOption('exclude') || $args->getOption('only')) && - $args->getOption('target') === null; + return ($this->args->getOption('exclude') || $this->args->getOption('only')) && + $this->args->getOption('target') === null; } /** * Execute the command. * - * @param \Cake\Console\Arguments $args The command arguments. - * @param \Cake\Console\ConsoleIo $io The console io * @return int|null The exit code or null for success */ - public function execute(Arguments $args, ConsoleIo $io): ?int + public function execute(): ?int { $factory = new ManagerFactory([ - 'plugin' => $args->getOption('plugin'), - 'source' => $args->getOption('source'), - 'connection' => $args->getOption('connection'), + 'plugin' => $this->args->getOption('plugin'), + 'source' => $this->args->getOption('source'), + 'connection' => $this->args->getOption('connection'), ]); - $manager = $factory->createManager($io); + $manager = $factory->createManager($this->io); $config = $manager->getConfig(); $path = $config->getMigrationPath(); - - if ($this->invalidOnlyOrExclude($args)) { - $io->err( + if ($this->invalidOnlyOrExclude()) { + $this->io->err( 'You should use `--exclude` OR `--only` (not both) along with a `--target` !', ); return self::CODE_ERROR; } - try { - $versions = $manager->getVersionsToMark($args); + $versions = $manager->getVersionsToMark($this->args); } catch (InvalidArgumentException $e) { - $io->err(sprintf('%s', $e->getMessage())); + $this->io->err(sprintf('%s', $e->getMessage())); return self::CODE_ERROR; } - $output = $manager->markVersionsAsMigrated($path, $versions); - array_map(fn(string $line): ?int => $io->out($line), $output); + array_map(fn(string $line): ?int => $this->io->out($line), $output); return self::CODE_SUCCESS; } diff --git a/src/Command/MigrateCommand.php b/src/Command/MigrateCommand.php index 702943337..259e6b15b 100644 --- a/src/Command/MigrateCommand.php +++ b/src/Command/MigrateCommand.php @@ -14,8 +14,6 @@ namespace Migrations\Command; use Cake\Command\Command; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIo; use Cake\Console\ConsoleOptionParser; use Cake\Event\EventDispatcherTrait; use DateTime; @@ -102,17 +100,15 @@ protected function buildOptionParser(ConsoleOptionParser $parser): ConsoleOption /** * Execute the command. * - * @param \Cake\Console\Arguments $args The command arguments. - * @param \Cake\Console\ConsoleIo $io The console io * @return int|null The exit code or null for success */ - public function execute(Arguments $args, ConsoleIo $io): ?int + public function execute(): ?int { $event = $this->dispatchEvent('Migration.beforeMigrate'); if ($event->isStopped()) { return $event->getResult() ? self::CODE_SUCCESS : self::CODE_ERROR; } - $result = $this->executeMigrations($args, $io); + $result = $this->executeMigrations(); $this->dispatchEvent('Migration.afterMigrate'); return $result; @@ -121,17 +117,14 @@ public function execute(Arguments $args, ConsoleIo $io): ?int /** * Execute migrations based on console inputs. * - * @param \Cake\Console\Arguments $args The command arguments. - * @param \Cake\Console\ConsoleIo $io The console io * @return int|null The exit code or null for success */ - protected function executeMigrations(Arguments $args, ConsoleIo $io): ?int + protected function executeMigrations(): ?int { - $version = $args->getOption('target') !== null ? (int)$args->getOption('target') : null; - $date = $args->getOption('date'); - $fake = (bool)$args->getOption('fake'); - - $count = $args->getOption('count') !== null ? (int)$args->getOption('count') : null; + $version = $this->args->getOption('target') !== null ? (int)$this->args->getOption('target') : null; + $date = $this->args->getOption('date'); + $fake = (bool)$this->args->getOption('fake'); + $count = $this->args->getOption('count') !== null ? (int)$this->args->getOption('count') : null; if ($count !== null && $count < 1) { throw new LogicException('Count must be > 0.'); } @@ -141,30 +134,24 @@ protected function executeMigrations(Arguments $args, ConsoleIo $io): ?int if ($version && $date) { throw new LogicException('Can only use one of `--version` or `--date` options at a time.'); } - $factory = new ManagerFactory([ - 'plugin' => $args->getOption('plugin'), - 'source' => $args->getOption('source'), - 'connection' => $args->getOption('connection'), - 'dry-run' => (bool)$args->getOption('dry-run'), + 'plugin' => $this->args->getOption('plugin'), + 'source' => $this->args->getOption('source'), + 'connection' => $this->args->getOption('connection'), + 'dry-run' => (bool)$this->args->getOption('dry-run'), ]); - - $manager = $factory->createManager($io); + $manager = $factory->createManager($this->io); $config = $manager->getConfig(); - $versionOrder = $config->getVersionOrder(); - if ($config->isDryRun()) { - $io->info('DRY-RUN mode enabled'); + $this->io->info('DRY-RUN mode enabled'); } - $io->verbose('using connection ' . $args->getOption('connection')); - $io->verbose('using paths ' . $config->getMigrationPath()); - $io->verbose('ordering by ' . $versionOrder . ' time'); - + $this->io->verbose('using connection ' . $this->args->getOption('connection')); + $this->io->verbose('using paths ' . $config->getMigrationPath()); + $this->io->verbose('ordering by ' . $versionOrder . ' time'); if ($fake) { - $io->out('warning performing fake migrations'); + $this->io->out('warning performing fake migrations'); } - try { // run the migrations $start = microtime(true); @@ -175,25 +162,23 @@ protected function executeMigrations(Arguments $args, ConsoleIo $io): ?int } $end = microtime(true); } catch (Throwable $e) { - $io->err('' . $e->getMessage() . ''); - $io->verbose($e->getTraceAsString()); + $this->io->err('' . $e->getMessage() . ''); + $this->io->verbose($e->getTraceAsString()); return self::CODE_ERROR; } - - $io->comment('All Done. Took ' . sprintf('%.4fs', $end - $start)); - $io->out(''); + $this->io->comment('All Done. Took ' . sprintf('%.4fs', $end - $start)); + $this->io->out(''); $exitCode = self::CODE_SUCCESS; - // Run dump command to generate lock file - if (!$args->getOption('no-lock') && !$args->getOption('dry-run')) { - $io->verbose(''); - $io->verbose('Dumping the current schema of the database to be used while baking a diff'); - $io->verbose(''); + if (!$this->args->getOption('no-lock') && !$this->args->getOption('dry-run')) { + $this->io->verbose(''); + $this->io->verbose('Dumping the current schema of the database to be used while baking a diff'); + $this->io->verbose(''); - $newArgs = DumpCommand::extractArgs($args); - $exitCode = $this->executeCommand(DumpCommand::class, $newArgs, $io); + $newArgs = DumpCommand::extractArgs($this->args); + $exitCode = $this->executeCommand(DumpCommand::class, $newArgs); } return $exitCode; diff --git a/src/Command/ResetCommand.php b/src/Command/ResetCommand.php index f5a8d021c..95c65ad37 100644 --- a/src/Command/ResetCommand.php +++ b/src/Command/ResetCommand.php @@ -14,8 +14,6 @@ namespace Migrations\Command; use Cake\Command\Command; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIo; use Cake\Console\ConsoleOptionParser; use Cake\Database\Connection; use Cake\Datasource\ConnectionManager; @@ -97,83 +95,71 @@ protected function buildOptionParser(ConsoleOptionParser $parser): ConsoleOption /** * Execute the command. * - * @param \Cake\Console\Arguments $args The command arguments. - * @param \Cake\Console\ConsoleIo $io The console io * @return int|null The exit code or null for success */ - public function execute(Arguments $args, ConsoleIo $io): ?int + public function execute(): ?int { $event = $this->dispatchEvent('Migration.beforeReset'); if ($event->isStopped()) { return $event->getResult() ? self::CODE_SUCCESS : self::CODE_ERROR; } - - $connectionName = (string)$args->getOption('connection'); + $connectionName = (string)$this->args->getOption('connection'); /** @var \Cake\Database\Connection $connection */ $connection = ConnectionManager::get($connectionName); - $dryRun = (bool)$args->getOption('dry-run'); - + $dryRun = (bool)$this->args->getOption('dry-run'); if ($dryRun) { - $io->out('DRY-RUN mode enabled - no changes will be made'); - $io->out(''); + $this->io->out('DRY-RUN mode enabled - no changes will be made'); + $this->io->out(''); } - // Get tables to drop $tablesToDrop = $this->getTablesToDrop($connection); - if ($tablesToDrop === []) { - $io->out('No tables to drop.'); - $io->out(''); - $io->out('Running migrations...'); + $this->io->out('No tables to drop.'); + $this->io->out(''); + $this->io->out('Running migrations...'); - return $this->runMigrationsAndDispatch($args, $io); + return $this->runMigrationsAndDispatch(); } - // Show what will be dropped - $io->out('The following tables will be dropped:'); + $this->io->out('The following tables will be dropped:'); foreach ($tablesToDrop as $table) { - $io->out(' - ' . $table); + $this->io->out(' - ' . $table); } - $io->out(''); - + $this->io->out(''); // Ask for confirmation (unless dry-run) if (!$dryRun) { - $continue = $io->askChoice( + $continue = $this->io->askChoice( 'This will permanently delete all data. Do you want to continue?', ['y', 'n'], 'n', ); if ($continue !== 'y') { - $io->warning('Reset operation aborted.'); + $this->io->warning('Reset operation aborted.'); return self::CODE_SUCCESS; } } - // Drop tables - $io->out(''); + $this->io->out(''); if (!$dryRun) { $factory = new ManagerFactory([ - 'plugin' => $args->getOption('plugin'), - 'source' => $args->getOption('source'), - 'connection' => $args->getOption('connection'), + 'plugin' => $this->args->getOption('plugin'), + 'source' => $this->args->getOption('source'), + 'connection' => $this->args->getOption('connection'), ]); - $manager = $factory->createManager($io); + $manager = $factory->createManager($this->io); $adapter = $manager->getEnvironment()->getAdapter(); - $this->dropTables($adapter, $tablesToDrop, $io); + $this->dropTables($adapter, $tablesToDrop); } else { - $io->info('DRY-RUN: Would drop ' . count($tablesToDrop) . ' table(s).'); + $this->io->info('DRY-RUN: Would drop ' . count($tablesToDrop) . ' table(s).'); } - - $io->out(''); - + $this->io->out(''); // Re-run migrations if (!$dryRun) { - return $this->runMigrationsAndDispatch($args, $io); + return $this->runMigrationsAndDispatch(); } - - $io->info('DRY-RUN: Would re-run all migrations.'); + $this->io->info('DRY-RUN: Would re-run all migrations.'); return self::CODE_SUCCESS; } @@ -196,10 +182,9 @@ protected function getTablesToDrop(Connection $connection): array * * @param \Migrations\Db\Adapter\AdapterInterface $adapter The adapter * @param array $tables Tables to drop - * @param \Cake\Console\ConsoleIo $io Console IO * @return void */ - protected function dropTables(AdapterInterface $adapter, array $tables, ConsoleIo $io): void + protected function dropTables(AdapterInterface $adapter, array $tables): void { if (!$adapter instanceof DirectActionInterface) { throw new RuntimeException('The adapter must implement DirectActionInterface'); @@ -209,26 +194,24 @@ protected function dropTables(AdapterInterface $adapter, array $tables, ConsoleI try { foreach ($tables as $table) { - $io->verbose('Dropping table: ' . $table); + $this->io->verbose('Dropping table: ' . $table); $adapter->dropTable($table); } } finally { $adapter->enableForeignKeyConstraints(); } - $io->success('Dropped ' . count($tables) . ' table(s).'); + $this->io->success('Dropped ' . count($tables) . ' table(s).'); } /** * Run migrations and dispatch afterReset event. * - * @param \Cake\Console\Arguments $args The command arguments. - * @param \Cake\Console\ConsoleIo $io The console io * @return int|null The exit code */ - protected function runMigrationsAndDispatch(Arguments $args, ConsoleIo $io): ?int + protected function runMigrationsAndDispatch(): ?int { - $result = $this->runMigrations($args, $io); + $result = $this->runMigrations(); $this->dispatchEvent('Migration.afterReset'); return $result; @@ -237,49 +220,42 @@ protected function runMigrationsAndDispatch(Arguments $args, ConsoleIo $io): ?in /** * Run migrations. * - * @param \Cake\Console\Arguments $args The command arguments. - * @param \Cake\Console\ConsoleIo $io The console io * @return int|null The exit code */ - protected function runMigrations(Arguments $args, ConsoleIo $io): ?int + protected function runMigrations(): ?int { $factory = new ManagerFactory([ - 'plugin' => $args->getOption('plugin'), - 'source' => $args->getOption('source'), - 'connection' => $args->getOption('connection'), - 'dry-run' => (bool)$args->getOption('dry-run'), + 'plugin' => $this->args->getOption('plugin'), + 'source' => $this->args->getOption('source'), + 'connection' => $this->args->getOption('connection'), + 'dry-run' => (bool)$this->args->getOption('dry-run'), ]); - - $manager = $factory->createManager($io); + $manager = $factory->createManager($this->io); $config = $manager->getConfig(); - - $io->verbose('using connection ' . $args->getOption('connection')); - $io->verbose('using paths ' . $config->getMigrationPath()); - + $this->io->verbose('using connection ' . $this->args->getOption('connection')); + $this->io->verbose('using paths ' . $config->getMigrationPath()); try { $start = microtime(true); $manager->migrate(null, false); $end = microtime(true); } catch (Throwable $e) { - $io->err('' . $e->getMessage() . ''); - $io->verbose($e->getTraceAsString()); + $this->io->err('' . $e->getMessage() . ''); + $this->io->verbose($e->getTraceAsString()); return self::CODE_ERROR; } - - $io->comment('All Done. Took ' . sprintf('%.4fs', $end - $start)); - $io->out(''); + $this->io->comment('All Done. Took ' . sprintf('%.4fs', $end - $start)); + $this->io->out(''); $exitCode = self::CODE_SUCCESS; - // Run dump command to generate lock file - if (!$args->getOption('no-lock') && !$args->getOption('dry-run')) { - $io->verbose(''); - $io->verbose('Dumping the current schema of the database to be used while baking a diff'); - $io->verbose(''); + if (!$this->args->getOption('no-lock') && !$this->args->getOption('dry-run')) { + $this->io->verbose(''); + $this->io->verbose('Dumping the current schema of the database to be used while baking a diff'); + $this->io->verbose(''); - $newArgs = DumpCommand::extractArgs($args); - $exitCode = $this->executeCommand(DumpCommand::class, $newArgs, $io); + $newArgs = DumpCommand::extractArgs($this->args); + $exitCode = $this->executeCommand(DumpCommand::class, $newArgs); } return $exitCode; diff --git a/src/Command/RollbackCommand.php b/src/Command/RollbackCommand.php index bf45b0a7b..fac81bfe9 100644 --- a/src/Command/RollbackCommand.php +++ b/src/Command/RollbackCommand.php @@ -14,8 +14,6 @@ namespace Migrations\Command; use Cake\Command\Command; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIo; use Cake\Console\ConsoleOptionParser; use Cake\Event\EventDispatcherTrait; use DateTime; @@ -107,17 +105,15 @@ protected function buildOptionParser(ConsoleOptionParser $parser): ConsoleOption /** * Execute the command. * - * @param \Cake\Console\Arguments $args The command arguments. - * @param \Cake\Console\ConsoleIo $io The console io * @return int|null The exit code or null for success */ - public function execute(Arguments $args, ConsoleIo $io): ?int + public function execute(): ?int { $event = $this->dispatchEvent('Migration.beforeRollback'); if ($event->isStopped()) { return $event->getResult() ? self::CODE_SUCCESS : self::CODE_ERROR; } - $result = $this->executeMigrations($args, $io); + $result = $this->executeMigrations(); $this->dispatchEvent('Migration.afterRollback'); return $result; @@ -126,19 +122,16 @@ public function execute(Arguments $args, ConsoleIo $io): ?int /** * Execute migrations based on console inputs. * - * @param \Cake\Console\Arguments $args The command arguments. - * @param \Cake\Console\ConsoleIo $io The console io * @return int|null The exit code or null for success */ - protected function executeMigrations(Arguments $args, ConsoleIo $io): ?int + protected function executeMigrations(): ?int { - $version = $args->getOption('target') !== null ? (int)$args->getOption('target') : null; - $date = $args->getOption('date'); - $fake = (bool)$args->getOption('fake'); - $force = (bool)$args->getOption('force'); - $dryRun = (bool)$args->getOption('dry-run'); - - $count = $args->getOption('count') !== null ? (int)$args->getOption('count') : null; + $version = $this->args->getOption('target') !== null ? (int)$this->args->getOption('target') : null; + $date = $this->args->getOption('date'); + $fake = (bool)$this->args->getOption('fake'); + $force = (bool)$this->args->getOption('force'); + $dryRun = (bool)$this->args->getOption('dry-run'); + $count = $this->args->getOption('count') !== null ? (int)$this->args->getOption('count') : null; if ($count !== null && $count < 1) { throw new LogicException('Count must be > 0.'); } @@ -148,28 +141,24 @@ protected function executeMigrations(Arguments $args, ConsoleIo $io): ?int if ($version && $date) { throw new LogicException('Can only use one of `--version` or `--date` options at a time.'); } - $factory = new ManagerFactory([ - 'plugin' => $args->getOption('plugin'), - 'source' => $args->getOption('source'), - 'connection' => $args->getOption('connection'), + 'plugin' => $this->args->getOption('plugin'), + 'source' => $this->args->getOption('source'), + 'connection' => $this->args->getOption('connection'), 'dry-run' => $dryRun, ]); - $manager = $factory->createManager($io); + $manager = $factory->createManager($this->io); $config = $manager->getConfig(); - $versionOrder = $config->getVersionOrder(); - $io->verbose('using connection ' . $args->getOption('connection')); - $io->verbose('using paths ' . $config->getMigrationPath()); - $io->verbose('ordering by ' . $versionOrder . ' time'); - + $this->io->verbose('using connection ' . $this->args->getOption('connection')); + $this->io->verbose('using paths ' . $config->getMigrationPath()); + $this->io->verbose('ordering by ' . $versionOrder . ' time'); if ($dryRun) { - $io->info('DRY-RUN mode enabled'); + $this->io->info('DRY-RUN mode enabled'); } if ($fake) { - $io->out('warning performing fake rollbacks'); + $this->io->out('warning performing fake rollbacks'); } - if ($date === null) { $targetMustMatch = true; $target = $version; @@ -177,7 +166,6 @@ protected function executeMigrations(Arguments $args, ConsoleIo $io): ?int $targetMustMatch = false; $target = $this->getTargetFromDate($date); } - try { // run the migrations $start = microtime(true); @@ -188,25 +176,23 @@ protected function executeMigrations(Arguments $args, ConsoleIo $io): ?int } $end = microtime(true); } catch (Throwable $e) { - $io->err('' . $e->getMessage() . ''); - $io->verbose($e->getTraceAsString()); + $this->io->err('' . $e->getMessage() . ''); + $this->io->verbose($e->getTraceAsString()); return self::CODE_ERROR; } - - $io->comment('All Done. Took ' . sprintf('%.4fs', $end - $start)); - $io->out(''); + $this->io->comment('All Done. Took ' . sprintf('%.4fs', $end - $start)); + $this->io->out(''); $exitCode = self::CODE_SUCCESS; - // Run dump command to generate lock file - if (!$args->getOption('no-lock')) { - $io->verbose(''); - $io->verbose('Dumping the current schema of the database to be used while baking a diff'); - $io->verbose(''); + if (!$this->args->getOption('no-lock')) { + $this->io->verbose(''); + $this->io->verbose('Dumping the current schema of the database to be used while baking a diff'); + $this->io->verbose(''); - $newArgs = DumpCommand::extractArgs($args); - $exitCode = $this->executeCommand(DumpCommand::class, $newArgs, $io); + $newArgs = DumpCommand::extractArgs($this->args); + $exitCode = $this->executeCommand(DumpCommand::class, $newArgs); } return $exitCode; diff --git a/src/Command/SeedCommand.php b/src/Command/SeedCommand.php index a764d0643..b907c6485 100644 --- a/src/Command/SeedCommand.php +++ b/src/Command/SeedCommand.php @@ -14,7 +14,6 @@ namespace Migrations\Command; use Cake\Command\Command; -use Cake\Console\Arguments; use Cake\Console\ConsoleIo; use Cake\Console\ConsoleOptionParser; use Cake\Event\EventDispatcherTrait; @@ -110,17 +109,15 @@ protected function buildOptionParser(ConsoleOptionParser $parser): ConsoleOption /** * Execute the command. * - * @param \Cake\Console\Arguments $args The command arguments. - * @param \Cake\Console\ConsoleIo $io The console io * @return int|null The exit code or null for success */ - public function execute(Arguments $args, ConsoleIo $io): ?int + public function execute(): ?int { $event = $this->dispatchEvent('Migration.beforeSeed'); if ($event->isStopped()) { return $event->getResult() ? self::CODE_SUCCESS : self::CODE_ERROR; } - $result = $this->executeSeeds($args, $io); + $result = $this->executeSeeds(); $this->dispatchEvent('Migration.afterSeed'); return $result; @@ -129,26 +126,22 @@ public function execute(Arguments $args, ConsoleIo $io): ?int /** * Execute seeds based on console inputs. * - * @param \Cake\Console\Arguments $args The command arguments. - * @param \Cake\Console\ConsoleIo $io The console io * @return int|null The exit code or null for success */ - protected function executeSeeds(Arguments $args, ConsoleIo $io): ?int + protected function executeSeeds(): ?int { $factory = new ManagerFactory([ - 'plugin' => $args->getOption('plugin'), - 'source' => $args->getOption('source'), - 'connection' => $args->getOption('connection'), - 'dry-run' => (bool)$args->getOption('dry-run'), + 'plugin' => $this->args->getOption('plugin'), + 'source' => $this->args->getOption('source'), + 'connection' => $this->args->getOption('connection'), + 'dry-run' => (bool)$this->args->getOption('dry-run'), ]); - - $manager = $factory->createManager($io); + $manager = $factory->createManager($this->io); $config = $manager->getConfig(); - // Get seed names from arguments $seeds = []; - if ($args->hasArgument('seed')) { - $seedArg = $args->getArgument('seed'); + if ($this->args->hasArgument('seed')) { + $seedArg = $this->args->getArgument('seed'); if ($seedArg !== null) { // Split by comma to support comma-separated list $seedList = explode(',', $seedArg); @@ -160,20 +153,17 @@ protected function executeSeeds(Arguments $args, ConsoleIo $io): ?int } } } - $versionOrder = $config->getVersionOrder(); - - $fake = (bool)$args->getOption('fake'); - + $fake = (bool)$this->args->getOption('fake'); if ($config->isDryRun()) { - $io->info('DRY-RUN mode enabled'); + $this->io->info('DRY-RUN mode enabled'); } if ($fake) { - $io->warning('performing fake seeding'); + $this->io->warning('performing fake seeding'); } - $io->verbose('using connection ' . $args->getOption('connection')); - $io->verbose('using paths ' . $config->getMigrationPath()); - $io->verbose('ordering by ' . $versionOrder . ' time'); + $this->io->verbose('using connection ' . $this->args->getOption('connection')); + $this->io->verbose('using paths ' . $config->getMigrationPath()); + $this->io->verbose('ordering by ' . $versionOrder . ' time'); $start = microtime(true); if (!$seeds) { @@ -181,21 +171,21 @@ protected function executeSeeds(Arguments $args, ConsoleIo $io): ?int try { $availableSeeds = $manager->getSeeds(); } catch (Throwable $e) { - $io->err('Failed to load seeds: ' . $e->getMessage() . ''); - $io->verbose($e->getTraceAsString()); + $this->io->err('Failed to load seeds: ' . $e->getMessage() . ''); + $this->io->verbose($e->getTraceAsString()); return static::CODE_ERROR; } if (!$availableSeeds) { - $io->warning('No seeds found.'); + $this->io->warning('No seeds found.'); return self::CODE_SUCCESS; } // Skip confirmation in quiet mode - if ($io->level() > ConsoleIo::QUIET) { - $force = (bool)$args->getOption('force'); + if ($this->io->level() > ConsoleIo::QUIET) { + $force = (bool)$this->args->getOption('force'); // Determine which seeds will actually run $willRun = []; @@ -208,45 +198,44 @@ protected function executeSeeds(Arguments $args, ConsoleIo $io): ?int } } - $io->out(''); + $this->io->out(''); if (!$willRun) { - $io->out('All seeds have already been executed. Use --force to re-run.'); - $io->out(''); + $this->io->out('All seeds have already been executed. Use --force to re-run.'); + $this->io->out(''); return self::CODE_SUCCESS; } - $io->out('The following seeds will be executed:'); + $this->io->out('The following seeds will be executed:'); foreach ($willRun as $name) { - $io->out(' - ' . $name); + $this->io->out(' - ' . $name); } - $io->out(''); + $this->io->out(''); if ($force) { - $io->out('Warning: Running with --force will re-execute all seeds,'); - $io->out('potentially creating duplicate data. Ensure your seeds are idempotent.'); + $this->io->out('Warning: Running with --force will re-execute all seeds,'); + $this->io->out('potentially creating duplicate data. Ensure your seeds are idempotent.'); } - $io->out(''); + $this->io->out(''); // Ask for confirmation - $continue = $io->askChoice('Do you want to continue?', ['y', 'n'], 'n'); + $continue = $this->io->askChoice('Do you want to continue?', ['y', 'n'], 'n'); if ($continue !== 'y') { - $io->warning('Seed operation aborted.'); + $this->io->warning('Seed operation aborted.'); return self::CODE_SUCCESS; } } // run all the seed(ers) - $manager->seed(null, (bool)$args->getOption('force'), $fake); + $manager->seed(null, (bool)$this->args->getOption('force'), $fake); } else { // run seed(ers) specified as arguments foreach ($seeds as $seed) { - $manager->seed(trim($seed), (bool)$args->getOption('force'), $fake); + $manager->seed(trim($seed), (bool)$this->args->getOption('force'), $fake); } } $end = microtime(true); - - $io->comment('All Done. Took ' . sprintf('%.4fs', $end - $start)); + $this->io->comment('All Done. Took ' . sprintf('%.4fs', $end - $start)); return self::CODE_SUCCESS; } diff --git a/src/Command/SeedResetCommand.php b/src/Command/SeedResetCommand.php index 34d5ae3fe..d85f78627 100644 --- a/src/Command/SeedResetCommand.php +++ b/src/Command/SeedResetCommand.php @@ -14,8 +14,6 @@ namespace Migrations\Command; use Cake\Command\Command; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIo; use Cake\Console\ConsoleOptionParser; use Migrations\Config\ConfigInterface; use Migrations\Migration\ManagerFactory; @@ -86,36 +84,29 @@ protected function buildOptionParser(ConsoleOptionParser $parser): ConsoleOption /** * Execute the command. * - * @param \Cake\Console\Arguments $args The command arguments. - * @param \Cake\Console\ConsoleIo $io The console io * @return int|null The exit code or null for success */ - public function execute(Arguments $args, ConsoleIo $io): ?int + public function execute(): ?int { $factory = new ManagerFactory([ - 'plugin' => $args->getOption('plugin'), - 'source' => $args->getOption('source'), - 'connection' => $args->getOption('connection'), - 'dry-run' => (bool)$args->getOption('dry-run'), + 'plugin' => $this->args->getOption('plugin'), + 'source' => $this->args->getOption('source'), + 'connection' => $this->args->getOption('connection'), + 'dry-run' => (bool)$this->args->getOption('dry-run'), ]); - - $manager = $factory->createManager($io); + $manager = $factory->createManager($this->io); $config = $manager->getConfig(); - if ($config->isDryRun()) { - $io->info('DRY-RUN mode enabled'); + $this->io->info('DRY-RUN mode enabled'); } - - $io->verbose('using connection ' . $args->getOption('connection')); - $io->verbose('using paths ' . $config->getSeedPath()); + $this->io->verbose('using connection ' . $this->args->getOption('connection')); + $this->io->verbose('using paths ' . $config->getSeedPath()); $seeds = $manager->getSeeds(); $adapter = $manager->getEnvironment()->getAdapter(); - // Filter seeds if --seed option is specified - $seedOption = $args->getOption('seed'); + $seedOption = $this->args->getOption('seed'); $seedsToReset = $seeds; - if ($seedOption) { $requestedSeeds = array_map(trim(...), explode(',', (string)$seedOption)); $seedsToReset = []; @@ -123,38 +114,34 @@ public function execute(Arguments $args, ConsoleIo $io): ?int foreach ($requestedSeeds as $requestedSeed) { $normalizedName = $manager->normalizeSeedName($requestedSeed, $seeds); if ($normalizedName === null) { - $io->error(sprintf('Seed `%s` does not exist.', $requestedSeed)); + $this->io->error(sprintf('Seed `%s` does not exist.', $requestedSeed)); return self::CODE_ERROR; } $seedsToReset[$normalizedName] = $seeds[$normalizedName]; } } - if ($seedsToReset === []) { - $io->warning('No seeds to reset.'); + $this->io->warning('No seeds to reset.'); return self::CODE_SUCCESS; } - // Show what will be reset and ask for confirmation - $io->out(''); + $this->io->out(''); $resetAllMessage = $seedOption ? 'The following seeds will be reset:' : 'All seeds will be reset:'; - $io->out($resetAllMessage); + $this->io->out($resetAllMessage); foreach ($seedsToReset as $seed) { - $io->out(' - ' . Util::getSeedDisplayName($seed->getName())); + $this->io->out(' - ' . Util::getSeedDisplayName($seed->getName())); } - $io->out(''); - + $this->io->out(''); if (!$config->isDryRun()) { - $continue = $io->askChoice('Do you want to continue?', ['y', 'n'], 'n'); + $continue = $this->io->askChoice('Do you want to continue?', ['y', 'n'], 'n'); if ($continue !== 'y') { - $io->warning('Reset operation aborted.'); + $this->io->warning('Reset operation aborted.'); return self::CODE_SUCCESS; } } - // Reset the seeds $count = 0; foreach ($seedsToReset as $seed) { @@ -163,18 +150,17 @@ public function execute(Arguments $args, ConsoleIo $io): ?int if (!$config->isDryRun()) { $adapter->removeSeedFromLog($seed); } - $io->info(sprintf('Reset: %s seed', $seedName)); + $this->io->info(sprintf('Reset: %s seed', $seedName)); $count++; } else { - $io->verbose(sprintf('Skipped (not executed): %s seed', $seedName)); + $this->io->verbose(sprintf('Skipped (not executed): %s seed', $seedName)); } } - - $io->out(''); + $this->io->out(''); if ($config->isDryRun()) { - $io->success(sprintf('DRY-RUN: Would reset %d seed(s).', $count)); + $this->io->success(sprintf('DRY-RUN: Would reset %d seed(s).', $count)); } else { - $io->success(sprintf('Reset %d seed(s).', $count)); + $this->io->success(sprintf('Reset %d seed(s).', $count)); } return self::CODE_SUCCESS; diff --git a/src/Command/SeedStatusCommand.php b/src/Command/SeedStatusCommand.php index 3a73bbd85..98c0cb856 100644 --- a/src/Command/SeedStatusCommand.php +++ b/src/Command/SeedStatusCommand.php @@ -14,8 +14,6 @@ namespace Migrations\Command; use Cake\Command\Command; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIo; use Cake\Console\ConsoleOptionParser; use Migrations\Config\ConfigInterface; use Migrations\Migration\ManagerFactory; @@ -75,34 +73,27 @@ protected function buildOptionParser(ConsoleOptionParser $parser): ConsoleOption /** * Execute the command. * - * @param \Cake\Console\Arguments $args The command arguments. - * @param \Cake\Console\ConsoleIo $io The console io * @return int|null The exit code or null for success */ - public function execute(Arguments $args, ConsoleIo $io): ?int + public function execute(): ?int { $factory = new ManagerFactory([ - 'plugin' => $args->getOption('plugin'), - 'source' => $args->getOption('source'), - 'connection' => $args->getOption('connection'), + 'plugin' => $this->args->getOption('plugin'), + 'source' => $this->args->getOption('source'), + 'connection' => $this->args->getOption('connection'), ]); - - $manager = $factory->createManager($io); + $manager = $factory->createManager($this->io); $config = $manager->getConfig(); - - $io->verbose('using connection ' . $args->getOption('connection')); - $io->verbose('using paths ' . $config->getSeedPath()); + $this->io->verbose('using connection ' . $this->args->getOption('connection')); + $this->io->verbose('using paths ' . $config->getSeedPath()); $seeds = $manager->getSeeds(); $adapter = $manager->getEnvironment()->getAdapter(); - // Ensure seed schema table exists if (!$adapter->hasTable($adapter->getSeedSchemaTableName())) { $adapter->createSeedSchemaTable(); } - $seedLog = $adapter->getSeedLog(); - // Build status list $statuses = []; foreach ($seeds as $seed) { @@ -130,31 +121,27 @@ public function execute(Arguments $args, ConsoleIo $io): ?int 'idempotent' => $seed->isIdempotent(), ]; } - - $format = (string)$args->getOption('format'); + $format = (string)$this->args->getOption('format'); if ($format === 'json') { $json = json_encode($statuses, JSON_PRETTY_PRINT); if ($json !== false) { - $io->out($json); + $this->io->out($json); } return self::CODE_SUCCESS; } - // Text format if (!$statuses) { - $io->warning('No seeds found.'); + $this->io->warning('No seeds found.'); return self::CODE_SUCCESS; } - - $io->out(''); - $io->out('Current seed execution status:'); - $io->out(''); + $this->io->out(''); + $this->io->out('Current seed execution status:'); + $this->io->out(''); $maxNameLength = max(array_map(fn(array $s): int => strlen($s['seedName']), $statuses)); $maxPluginLength = max(array_map(fn(array $s): int => strlen($s['plugin'] ?? ''), $statuses)); - foreach ($statuses as $status) { $seedName = str_pad($status['seedName'], $maxNameLength); $plugin = $status['plugin'] ? str_pad($status['plugin'], $maxPluginLength) : str_repeat(' ', $maxPluginLength); @@ -163,14 +150,13 @@ public function execute(Arguments $args, ConsoleIo $io): ?int if ($status['status'] === 'executed') { $statusText = 'executed'; $date = $status['executedAt'] ? ' (' . $status['executedAt'] . ')' : ''; - $io->out(sprintf(' %s %s %s%s%s', $statusText, $plugin, $seedName, $date, $idempotent)); + $this->io->out(sprintf(' %s %s %s%s%s', $statusText, $plugin, $seedName, $date, $idempotent)); } else { $statusText = 'pending '; - $io->out(sprintf(' %s %s %s%s', $statusText, $plugin, $seedName, $idempotent)); + $this->io->out(sprintf(' %s %s %s%s', $statusText, $plugin, $seedName, $idempotent)); } } - - $io->out(''); + $this->io->out(''); return self::CODE_SUCCESS; } diff --git a/src/Command/SeedsEntryCommand.php b/src/Command/SeedsEntryCommand.php index cc0ea6f57..5059d4014 100644 --- a/src/Command/SeedsEntryCommand.php +++ b/src/Command/SeedsEntryCommand.php @@ -21,7 +21,7 @@ use Cake\Console\Command\HelpCommand; use Cake\Console\CommandCollection; use Cake\Console\CommandCollectionAwareInterface; -use Cake\Console\ConsoleIo; +use Cake\Console\ConsoleIoInterface; use Cake\Console\Exception\ConsoleException; /** @@ -56,64 +56,65 @@ public function setCommandCollection(CommandCollection $commands): void * Override the run() method for special handling of the `--help` option. * * @param array $argv Arguments from the CLI environment. - * @param \Cake\Console\ConsoleIo $io The console io + * @param \Cake\Console\ConsoleIoInterface|null $io The console IO. * @return int|null Exit code or null for success. */ - public function run(array $argv, ConsoleIo $io): ?int + public function run(array $argv, ?ConsoleIoInterface $io = null): ?int { + if ($io instanceof ConsoleIoInterface) { + $this->io = $io; + } $this->initialize(); $parser = $this->getOptionParser(); try { [$options, $arguments] = $parser->parse($argv); - $args = new Arguments( + $this->args = new Arguments( $arguments, $options, $parser->argumentNames(), ); } catch (ConsoleException $e) { - $io->err('Error: ' . $e->getMessage()); + $this->io->err('Error: ' . $e->getMessage()); return static::CODE_ERROR; } - $this->setOutputLevel($args, $io); + $this->setOutputLevel(); // This is the variance from Command::run() - if (!$args->getArgumentAt(0) && $args->getOption('help')) { - $io->out([ + if (!$this->args->getArgumentAt(0) && $this->args->getOption('help')) { + $this->io->out([ 'Seeds', '', 'Seeds provides commands for managing your application database seed data.', '', ]); $help = $this->getHelp(); - $this->executeCommand($help, [], $io); + $this->executeCommand($help, []); return static::CODE_SUCCESS; } - return $this->execute($args, $io); + return $this->execute(); } /** * Execute the command. * - * @param \Cake\Console\Arguments $args The command arguments. - * @param \Cake\Console\ConsoleIo $io The console io * @return int|null The exit code or null for success */ - public function execute(Arguments $args, ConsoleIo $io): ?int + public function execute(): ?int { - if ($args->hasArgumentAt(0)) { - $name = $args->getArgumentAt(0); - $io->err( + if ($this->args->hasArgumentAt(0)) { + $name = $this->args->getArgumentAt(0); + $this->io->err( sprintf('Could not find seeds command named `%s`.', $name) . ' Run `seeds --help` to get a list of commands.', ); return static::CODE_ERROR; } - $io->err('No command provided. Run `seeds --help` to get a list of commands.'); + $this->io->err('No command provided. Run `seeds --help` to get a list of commands.'); return static::CODE_ERROR; } diff --git a/src/Command/SnapshotTrait.php b/src/Command/SnapshotTrait.php index 1c4fad8d3..5a681f312 100644 --- a/src/Command/SnapshotTrait.php +++ b/src/Command/SnapshotTrait.php @@ -13,9 +13,6 @@ */ namespace Migrations\Command; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIo; - /** * Trait needed for all "snapshot" type of bake operations. * Snapshot type operations are : baking a snapshot and baking a diff. @@ -25,15 +22,15 @@ trait SnapshotTrait /** * @inheritDoc */ - protected function createFile(string $path, string $contents, Arguments $args, ConsoleIo $io): bool + protected function createFile(string $path, string $contents): bool { - $createFile = parent::createFile($path, $contents, $args, $io); + $createFile = parent::createFile($path, $contents); - if ($createFile && !$args->getOption('generate-only')) { - $this->markSnapshotApplied($path, $args, $io); + if ($createFile && !$this->args->getOption('generate-only')) { + $this->markSnapshotApplied($path); - if (!$args->getOption('no-lock')) { - $this->refreshDump($args, $io); + if (!$this->args->getOption('no-lock')) { + $this->refreshDump(); } } @@ -45,11 +42,9 @@ protected function createFile(string $path, string $contents, Arguments $args, C * full file path. * * @param string $path Path to the newly created snapshot - * @param \Cake\Console\Arguments $args The command arguments. - * @param \Cake\Console\ConsoleIo $io The console io * @return void */ - protected function markSnapshotApplied(string $path, Arguments $args, ConsoleIo $io): void + protected function markSnapshotApplied(string $path): void { $fileName = pathinfo($path, PATHINFO_FILENAME); [$version, ] = explode('_', $fileName, 2); @@ -59,50 +54,47 @@ protected function markSnapshotApplied(string $path, Arguments $args, ConsoleIo $newArgs[] = $version; $newArgs[] = '-o'; - $newArgs = array_merge($newArgs, $this->parseOptions($args)); + $newArgs = array_merge($newArgs, $this->parseOptions()); - $io->out('Marking the migration ' . $fileName . ' as migrated...'); - $this->executeCommand(MarkMigratedCommand::class, $newArgs, $io); + $this->io->out('Marking the migration ' . $fileName . ' as migrated...'); + $this->executeCommand(MarkMigratedCommand::class, $newArgs); } /** * After a file has been successfully created, we refresh the dump of the database * to be able to generate a new diff afterward. * - * @param \Cake\Console\Arguments $args The command arguments. - * @param \Cake\Console\ConsoleIo $io The console io * @return void */ - protected function refreshDump(Arguments $args, ConsoleIo $io): void + protected function refreshDump(): void { - $newArgs = $this->parseOptions($args); + $newArgs = $this->parseOptions(); - $io->out('Creating a dump of the new database state...'); - $this->executeCommand(DumpCommand::class, $newArgs, $io); + $this->io->out('Creating a dump of the new database state...'); + $this->executeCommand(DumpCommand::class, $newArgs); } /** * Will parse 'connection', 'plugin' and 'source' options into a new Array * - * @param \Cake\Console\Arguments $args The command arguments. * @return array Array containing the short for the option followed by its value */ - protected function parseOptions(Arguments $args): array + protected function parseOptions(): array { $newArgs = []; - if ($args->getOption('connection')) { + if ($this->args->getOption('connection')) { $newArgs[] = '-c'; - $newArgs[] = $args->getOption('connection'); + $newArgs[] = $this->args->getOption('connection'); } - if ($args->getOption('plugin')) { + if ($this->args->getOption('plugin')) { $newArgs[] = '-p'; - $newArgs[] = $args->getOption('plugin'); + $newArgs[] = $this->args->getOption('plugin'); } - if ($args->getOption('source')) { + if ($this->args->getOption('source')) { $newArgs[] = '-s'; - $newArgs[] = $args->getOption('source'); + $newArgs[] = $this->args->getOption('source'); } return $newArgs; diff --git a/src/Command/StatusCommand.php b/src/Command/StatusCommand.php index 4161d64f4..cdff4141c 100644 --- a/src/Command/StatusCommand.php +++ b/src/Command/StatusCommand.php @@ -14,8 +14,6 @@ namespace Migrations\Command; use Cake\Command\Command; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIo; use Cake\Console\ConsoleOptionParser; use Cake\Core\Plugin; use Migrations\Config\ConfigInterface; @@ -112,65 +110,58 @@ protected function buildOptionParser(ConsoleOptionParser $parser): ConsoleOption /** * Execute the command. * - * @param \Cake\Console\Arguments $args The command arguments. - * @param \Cake\Console\ConsoleIo $io The console io * @return int|null The exit code or null for success */ - public function execute(Arguments $args, ConsoleIo $io): ?int + public function execute(): ?int { /** @var string|null $format */ - $format = $args->getOption('format'); - $clean = $args->getOption('cleanup'); - $all = (bool)$args->getOption('all'); - + $format = $this->args->getOption('format'); + $clean = $this->args->getOption('cleanup'); + $all = (bool)$this->args->getOption('all'); if ($all) { - if ($args->getOption('plugin')) { - $io->err('The --all option cannot be combined with --plugin.'); + if ($this->args->getOption('plugin')) { + $this->io->err('The --all option cannot be combined with --plugin.'); return Command::CODE_ERROR; } if ($clean) { - $io->err('The --all option cannot be combined with --cleanup.'); + $this->io->err('The --all option cannot be combined with --cleanup.'); return Command::CODE_ERROR; } - return $this->executeAll($args, $io, $format); + return $this->executeAll($format); } - $factory = new ManagerFactory([ - 'plugin' => $args->getOption('plugin'), - 'source' => $args->getOption('source'), - 'connection' => $args->getOption('connection'), - 'dry-run' => $args->getOption('dry-run'), + 'plugin' => $this->args->getOption('plugin'), + 'source' => $this->args->getOption('source'), + 'connection' => $this->args->getOption('connection'), + 'dry-run' => $this->args->getOption('dry-run'), ]); - $manager = $factory->createManager($io); - + $manager = $factory->createManager($this->io); if ($clean) { $removed = $manager->cleanupMissingMigrations(); if ($removed === 0) { - $io->out('No missing migrations to clean up.'); + $this->io->out('No missing migrations to clean up.'); } else { - $io->out(sprintf('Removed %d missing migration(s) from migration log.', $removed)); + $this->io->out(sprintf('Removed %d missing migration(s) from migration log.', $removed)); } return Command::CODE_SUCCESS; } - $migrations = $manager->printStatus($format); $tableName = $manager->getSchemaTableName(); - switch ($format) { case 'json': $flags = 0; - if ($args->getOption('verbose')) { + if ($this->args->getOption('verbose')) { $flags = JSON_PRETTY_PRINT; } $migrationString = (string)json_encode($migrations, $flags); - $io->out($migrationString); + $this->io->out($migrationString); break; default: - $this->display($migrations, $io, $tableName); + $this->display($migrations, $tableName); break; } @@ -181,25 +172,23 @@ public function execute(Arguments $args, ConsoleIo $io): ?int * Execute the status command for the app and every loaded plugin * that ships migrations. * - * @param \Cake\Console\Arguments $args The command arguments. - * @param \Cake\Console\ConsoleIo $io The console io. * @param string|null $format Output format. * @return int The exit code: CODE_STATUS_MISSING (2) when there are missing entries, * CODE_STATUS_DOWN (3) when there are pending down migrations, CODE_SUCCESS otherwise. */ - protected function executeAll(Arguments $args, ConsoleIo $io, ?string $format): int + protected function executeAll(?string $format): int { $sections = ['app' => null]; foreach (Plugin::loaded() as $pluginName) { $migrationsPath = Plugin::path($pluginName) . 'config' . DS - . $args->getOption('source') . DS; + . $this->args->getOption('source') . DS; if (!is_dir($migrationsPath)) { continue; } $sections[$pluginName] = $pluginName; } - $verbose = (bool)$args->getOption('verbose'); + $verbose = (bool)$this->args->getOption('verbose'); $jsonResults = []; $summary = []; $exitCode = Command::CODE_SUCCESS; @@ -207,11 +196,11 @@ protected function executeAll(Arguments $args, ConsoleIo $io, ?string $format): foreach ($sections as $label => $plugin) { $factory = new ManagerFactory([ 'plugin' => $plugin, - 'source' => $args->getOption('source'), - 'connection' => $args->getOption('connection'), - 'dry-run' => $args->getOption('dry-run'), + 'source' => $this->args->getOption('source'), + 'connection' => $this->args->getOption('connection'), + 'dry-run' => $this->args->getOption('dry-run'), ]); - $manager = $factory->createManager($io); + $manager = $factory->createManager($this->io); $migrations = $manager->printStatus($format); $sectionExit = $this->statusExitCode($migrations); @@ -234,11 +223,11 @@ protected function executeAll(Arguments $args, ConsoleIo $io, ?string $format): } $heading = $label === 'app' ? 'APP' : $label; - $io->out(''); - $io->out('=================================================='); - $io->out(sprintf('%s', $heading)); - $io->out('=================================================='); - $this->display($migrations, $io, $manager->getSchemaTableName()); + $this->io->out(''); + $this->io->out('=================================================='); + $this->io->out(sprintf('%s', $heading)); + $this->io->out('=================================================='); + $this->display($migrations, $manager->getSchemaTableName()); } if ($format === 'json') { @@ -246,12 +235,12 @@ protected function executeAll(Arguments $args, ConsoleIo $io, ?string $format): if ($verbose) { $flags = JSON_PRETTY_PRINT; } - $io->out((string)json_encode($jsonResults, $flags)); + $this->io->out((string)json_encode($jsonResults, $flags)); return $exitCode; } - $this->displaySummary($io, $summary); + $this->displaySummary($summary); return $exitCode; } @@ -282,20 +271,19 @@ protected function countActions(array $migrations): array /** * Render the trailing summary block listing sections that need action. * - * @param \Cake\Console\ConsoleIo $io The console io. * @param array $summary * @return void */ - protected function displaySummary(ConsoleIo $io, array $summary): void + protected function displaySummary(array $summary): void { $needsAction = array_filter( $summary, fn(array $counts): bool => $counts['down'] > 0 || $counts['missing'] > 0, ); - $io->out(''); + $this->io->out(''); if (!$needsAction) { - $io->out(sprintf( + $this->io->out(sprintf( 'Summary: all %d sections are up to date.', count($summary), )); @@ -303,7 +291,7 @@ protected function displaySummary(ConsoleIo $io, array $summary): void return; } - $io->out(sprintf( + $this->io->out(sprintf( 'Summary: %d of %d sections require action:', count($needsAction), count($summary), @@ -317,7 +305,7 @@ protected function displaySummary(ConsoleIo $io, array $summary): void if ($counts['missing'] > 0) { $parts[] = sprintf('%d missing', $counts['missing']); } - $io->out(sprintf(' - %s: %s', $heading, implode(', ', $parts))); + $this->io->out(sprintf(' - %s: %s', $heading, implode(', ', $parts))); } } @@ -346,17 +334,16 @@ protected function statusExitCode(array $migrations): int /** * Print migration status to stdout. * - * @param \Cake\Console\ConsoleIo $io The console io * @param string $tableName The migration tracking table name * @return void */ - protected function display(array $migrations, ConsoleIo $io, string $tableName): void + protected function display(array $migrations, string $tableName): void { - $io->out(sprintf('using migration table %s', $tableName)); + $this->io->out(sprintf('using migration table %s', $tableName)); if ($tableName !== UnifiedMigrationsTableStorage::TABLE_NAME) { - $io->warning('You are using legacy phinxlog tables. Run `migrations upgrade` to switch to the unified `cake_migrations` table.'); + $this->io->warning('You are using legacy phinxlog tables. Run `migrations upgrade` to switch to the unified `cake_migrations` table.'); } - $io->out(''); + $this->io->out(''); if ($migrations) { $rows = []; @@ -374,12 +361,12 @@ protected function display(array $migrations, ConsoleIo $io, string $tableName): } $rows[] = [$status, sprintf('%14.0f ', $migration['id']), $name . $missingComment]; } - $io->helper('table')->output($rows); + $this->io->helper('table')->output($rows); } else { $msg = 'There are no available migrations. Try creating one using the create command.'; - $io->err(''); - $io->err($msg); - $io->err(''); + $this->io->err(''); + $this->io->err($msg); + $this->io->err(''); } } } diff --git a/src/Command/UpgradeCommand.php b/src/Command/UpgradeCommand.php index 76c947429..e7bfe5703 100644 --- a/src/Command/UpgradeCommand.php +++ b/src/Command/UpgradeCommand.php @@ -14,8 +14,6 @@ namespace Migrations\Command; use Cake\Command\Command; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIo; use Cake\Console\ConsoleOptionParser; use Cake\Core\Plugin; use Cake\Database\Connection; @@ -95,87 +93,77 @@ protected function buildOptionParser(ConsoleOptionParser $parser): ConsoleOption /** * Execute the command. * - * @param \Cake\Console\Arguments $args The command arguments. - * @param \Cake\Console\ConsoleIo $io The console io * @return int|null The exit code or null for success */ - public function execute(Arguments $args, ConsoleIo $io): ?int + public function execute(): ?int { /** @var \Cake\Database\Connection $connection */ - $connection = ConnectionManager::get((string)$args->getOption('connection')); - $dryRun = (bool)$args->getOption('dry-run'); - $dropTables = (bool)$args->getOption('drop-tables'); - + $connection = ConnectionManager::get((string)$this->args->getOption('connection')); + $dryRun = (bool)$this->args->getOption('dry-run'); + $dropTables = (bool)$this->args->getOption('drop-tables'); if ($dryRun) { - $io->out('DRY RUN - No changes will be made'); - $io->out(''); + $this->io->out('DRY RUN - No changes will be made'); + $this->io->out(''); } - // Find all legacy phinxlog tables $legacyTables = $this->findLegacyTables($connection); - if ($legacyTables === []) { - $io->out('No phinxlog tables found. Nothing to upgrade.'); + $this->io->out('No phinxlog tables found. Nothing to upgrade.'); return self::CODE_SUCCESS; } - - $io->out(sprintf('Found %d phinxlog table(s):', count($legacyTables))); + $this->io->out(sprintf('Found %d phinxlog table(s):', count($legacyTables))); foreach ($legacyTables as $table => $plugin) { $pluginLabel = $plugin === null ? '(app)' : sprintf('(%s)', $plugin); - $io->out(sprintf(' - %s %s', $table, $pluginLabel)); + $this->io->out(sprintf(' - %s %s', $table, $pluginLabel)); } - $io->out(''); - + $this->io->out(''); // Create unified table if needed $unifiedTableName = UnifiedMigrationsTableStorage::TABLE_NAME; if (!$this->tableExists($connection, $unifiedTableName)) { - $io->out(sprintf('Creating unified table %s...', $unifiedTableName)); + $this->io->out(sprintf('Creating unified table %s...', $unifiedTableName)); if (!$dryRun) { - $this->createUnifiedTable($connection, $io); + $this->createUnifiedTable($connection); } } else { - $io->out(sprintf('Unified table %s already exists.', $unifiedTableName)); + $this->io->out(sprintf('Unified table %s already exists.', $unifiedTableName)); } - $io->out(''); - + $this->io->out(''); // Migrate data from each legacy table $totalMigrated = 0; foreach ($legacyTables as $tableName => $plugin) { - $count = $this->migrateTable($connection, $tableName, $plugin, $dryRun, $io); + $count = $this->migrateTable($connection, $tableName, $plugin, $dryRun); $totalMigrated += $count; } - - $io->out(''); - $io->out(sprintf('Total records migrated: %d', $totalMigrated)); - + $this->io->out(''); + $this->io->out(sprintf('Total records migrated: %d', $totalMigrated)); if (!$dryRun) { // Clean up legacy tables - $io->out(''); + $this->io->out(''); foreach (array_keys($legacyTables) as $tableName) { if ($dropTables) { - $io->out(sprintf('Dropping legacy table %s...', $tableName)); + $this->io->out(sprintf('Dropping legacy table %s...', $tableName)); $connection->execute('DROP TABLE ' . $connection->getDriver()->quoteIdentifier($tableName)); } else { - $io->out('Retaining legacy table. You should drop these tables once you have verified your upgrade.'); + $this->io->out('Retaining legacy table. You should drop these tables once you have verified your upgrade.'); } } - $io->out(''); - $io->success('Upgrade complete!'); - $io->out(''); - $io->out('Next steps:'); + $this->io->out(''); + $this->io->success('Upgrade complete!'); + $this->io->out(''); + $this->io->out('Next steps:'); if ($dropTables) { - $io->out(" 1. Set 'Migrations' => ['legacyTables' => false] in your config"); - $io->out(' 2. Test your application'); + $this->io->out(" 1. Set 'Migrations' => ['legacyTables' => false] in your config"); + $this->io->out(' 2. Test your application'); } else { - $io->out(' 1. Test your application'); - $io->out(' 2. Drop the phinxlog tables (re-run `bin/cake migrations upgrade --drop-tables`)'); - $io->out(" 3. Set 'Migrations' => ['legacyTables' => false] in your config"); + $this->io->out(' 1. Test your application'); + $this->io->out(' 2. Drop the phinxlog tables (re-run `bin/cake migrations upgrade --drop-tables`)'); + $this->io->out(" 3. Set 'Migrations' => ['legacyTables' => false] in your config"); } } else { - $io->out(''); - $io->out('This was a dry run. Run without --dry-run to execute.'); + $this->io->out(''); + $this->io->out('This was a dry run. Run without --dry-run to execute.'); } return self::CODE_SUCCESS; @@ -256,10 +244,9 @@ protected function tableExists(Connection $connection, string $tableName): bool * Create the unified migrations table. * * @param \Cake\Database\Connection $connection Database connection - * @param \Cake\Console\ConsoleIo $io Console IO * @return void */ - protected function createUnifiedTable(Connection $connection, ConsoleIo $io): void + protected function createUnifiedTable(Connection $connection): void { $factory = new ManagerFactory([ 'plugin' => null, @@ -269,7 +256,7 @@ protected function createUnifiedTable(Connection $connection, ConsoleIo $io): vo 'dry-run' => false, ]); - $manager = $factory->createManager($io); + $manager = $factory->createManager($this->io); $adapter = $manager->getEnvironment()->getAdapter(); if ($adapter instanceof WrapperInterface) { $adapter = $adapter->getAdapter(); @@ -287,7 +274,6 @@ protected function createUnifiedTable(Connection $connection, ConsoleIo $io): vo * @param string $tableName Legacy table name * @param string|null $plugin Plugin name (null for app) * @param bool $dryRun Whether this is a dry run - * @param \Cake\Console\ConsoleIo $io Console IO * @return int Number of records migrated */ protected function migrateTable( @@ -295,7 +281,6 @@ protected function migrateTable( string $tableName, ?string $plugin, bool $dryRun, - ConsoleIo $io, ): int { $unifiedTable = UnifiedMigrationsTableStorage::TABLE_NAME; $pluginLabel = $plugin ?? 'app'; @@ -307,7 +292,7 @@ protected function migrateTable( $rows = $query->execute()->fetchAll('assoc'); $count = count($rows); - $io->out(sprintf('Migrating %d record(s) from %s (%s)...', $count, $tableName, $pluginLabel)); + $this->io->out(sprintf('Migrating %d record(s) from %s (%s)...', $count, $tableName, $pluginLabel)); if ($dryRun || $count === 0) { return $count; @@ -329,7 +314,7 @@ protected function migrateTable( ]); $insertQuery->execute(); } catch (QueryException) { - $io->out('Already migrated ' . $row['migration_name'] . '.'); + $this->io->out('Already migrated ' . $row['migration_name'] . '.'); } } diff --git a/src/Db/Adapter/AbstractAdapter.php b/src/Db/Adapter/AbstractAdapter.php index 02034482c..9ab562d42 100644 --- a/src/Db/Adapter/AbstractAdapter.php +++ b/src/Db/Adapter/AbstractAdapter.php @@ -9,7 +9,7 @@ namespace Migrations\Db\Adapter; use BadMethodCallException; -use Cake\Console\ConsoleIo; +use Cake\Console\ConsoleIoInterface; use Cake\Core\Configure; use Cake\Database\Connection; use Cake\Database\Query; @@ -73,7 +73,7 @@ abstract class AbstractAdapter implements AdapterInterface, DirectActionInterfac */ protected array $options = []; - protected ConsoleIo $io; + protected ConsoleIoInterface $io; /** * @var string[] @@ -92,12 +92,12 @@ abstract class AbstractAdapter implements AdapterInterface, DirectActionInterfac * Class Constructor. * * @param array $options Options - * @param \Cake\Console\ConsoleIo|null $io Console input/output + * @param \Cake\Console\ConsoleIoInterface|null $io Console input/output */ - public function __construct(array $options, ?ConsoleIo $io = null) + public function __construct(array $options, ?ConsoleIoInterface $io = null) { $this->setOptions($options); - if ($io instanceof ConsoleIo) { + if ($io instanceof ConsoleIoInterface) { $this->setIo($io); } } @@ -291,9 +291,9 @@ protected function verboseLog(string $message): void { $io = $this->getIo(); if ( - !$io instanceof ConsoleIo || ( + !$io instanceof ConsoleIoInterface || ( !$this->isDryRunEnabled() && - $io->level() !== ConsoleIo::VERBOSE + $io->level() !== ConsoleIoInterface::VERBOSE ) ) { return; @@ -326,7 +326,7 @@ public function getSchemaTableName(): string * @param string $schemaTableName Schema Table Name * @return $this */ - public function setSchemaTableName(string $schemaTableName) + public function setSchemaTableName(string $schemaTableName): static { $this->schemaTableName = $schemaTableName; @@ -349,7 +349,7 @@ public function getSeedSchemaTableName(): string * @param string $seedSchemaTableName Seed Schema Table Name * @return $this */ - public function setSeedSchemaTableName(string $seedSchemaTableName) + public function setSeedSchemaTableName(string $seedSchemaTableName): static { $this->seedSchemaTableName = $seedSchemaTableName; @@ -428,7 +428,7 @@ public function isValidColumnType(Column $column): bool /** * @inheritDoc */ - public function setIo(ConsoleIo $io) + public function setIo(ConsoleIoInterface $io) { $this->io = $io; @@ -438,7 +438,7 @@ public function setIo(ConsoleIo $io) /** * @inheritDoc */ - public function getIo(): ?ConsoleIo + public function getIo(): ?ConsoleIoInterface { return $this->io ?? null; } diff --git a/src/Db/Adapter/AdapterInterface.php b/src/Db/Adapter/AdapterInterface.php index 48cad38c3..74abd7b68 100644 --- a/src/Db/Adapter/AdapterInterface.php +++ b/src/Db/Adapter/AdapterInterface.php @@ -8,7 +8,7 @@ namespace Migrations\Db\Adapter; -use Cake\Console\ConsoleIo; +use Cake\Console\ConsoleIoInterface; use Cake\Database\Connection; use Cake\Database\Query; use Cake\Database\Query\DeleteQuery; @@ -786,17 +786,17 @@ public function castToBool(mixed $value): mixed; /** * Sets the consoleio. * - * @param \Cake\Console\ConsoleIo $io ConsoleIo + * @param \Cake\Console\ConsoleIoInterface $io ConsoleIoInterface * @return $this */ - public function setIo(ConsoleIo $io); + public function setIo(ConsoleIoInterface $io); /** * Get the io instance * - * @return \Cake\Console\ConsoleIo $io The io instance to use + * @return \Cake\Console\ConsoleIoInterface $io The io instance to use */ - public function getIo(): ?ConsoleIo; + public function getIo(): ?ConsoleIoInterface; /** * Get the Connection for this adapter. diff --git a/src/Db/Adapter/AdapterWrapper.php b/src/Db/Adapter/AdapterWrapper.php index 64c0a4814..5f6e4edef 100644 --- a/src/Db/Adapter/AdapterWrapper.php +++ b/src/Db/Adapter/AdapterWrapper.php @@ -8,7 +8,7 @@ namespace Migrations\Db\Adapter; -use Cake\Console\ConsoleIo; +use Cake\Console\ConsoleIoInterface; use Cake\Database\Connection; use Cake\Database\Query; use Cake\Database\Query\DeleteQuery; @@ -565,7 +565,7 @@ public function dropCheckConstraint(string $tableName, string $constraintName): /** * @inheritDoc */ - public function setIo(ConsoleIo $io) + public function setIo(ConsoleIoInterface $io) { $this->getAdapter()->setIo($io); @@ -575,7 +575,7 @@ public function setIo(ConsoleIo $io) /** * @inheritDoc */ - public function getIo(): ?ConsoleIo + public function getIo(): ?ConsoleIoInterface { return $this->getAdapter()->getIo(); } diff --git a/src/Db/Adapter/MysqlAdapter.php b/src/Db/Adapter/MysqlAdapter.php index b3f0002bf..d961255de 100644 --- a/src/Db/Adapter/MysqlAdapter.php +++ b/src/Db/Adapter/MysqlAdapter.php @@ -449,7 +449,11 @@ protected function mapColumnData(array $data): array default => null, }; } - $data['type'] = 'binary'; + $data['type'] = $data['length'] !== null + && !in_array($data['length'], TableSchema::$columnLengths, true) + && empty($data['fixed']) + ? TableSchema::TYPE_VARBINARY + : TableSchema::TYPE_BINARY; } elseif ($data['type'] === self::TYPE_INTEGER) { if (isset($data['length']) && $data['length'] === self::INT_BIG) { $data['type'] = TableSchema::TYPE_BIGINTEGER; @@ -624,6 +628,8 @@ protected function mapColumnType(array $columnData): array } elseif ($type === TableSchema::TYPE_TIMESTAMP_FRACTIONAL) { $type = 'timestamp'; $length = $columnData['precision'] ?? $length; + } elseif ($type === TableSchema::TYPE_VARBINARY) { + $type = self::TYPE_BINARY; } elseif ($type === TableSchema::TYPE_BINARY) { // TODO could rawType be removed? We should be able to use the abstract type and length only. // CakePHP returns BLOB columns as 'binary' with specific lengths @@ -704,7 +710,7 @@ public function getColumns(string $tableName): array if ($record['onUpdate'] ?? false) { $column->setUpdate($record['onUpdate']); } - if ($record['fixed'] ?? false) { + if (str_starts_with($record['rawType'] ?? '', 'binary(')) { $column->setFixed(true); } diff --git a/src/Db/Adapter/SqlserverAdapter.php b/src/Db/Adapter/SqlserverAdapter.php index 9d50c84f0..84a1b9f98 100644 --- a/src/Db/Adapter/SqlserverAdapter.php +++ b/src/Db/Adapter/SqlserverAdapter.php @@ -350,7 +350,7 @@ public function getColumns(string $tableName): array foreach ($dialect->describeColumns($tableName) as $columnInfo) { $column = (new Column()) ->setName($columnInfo['name']) - ->setType($columnInfo['type']) + ->setType($columnInfo['type'] === TableSchema::TYPE_VARBINARY ? self::TYPE_BINARY : $columnInfo['type']) ->setNull($columnInfo['null']) ->setLimit($columnInfo['length']) ->setDefault($this->parseDefault($columnInfo['default'])) diff --git a/src/Db/Adapter/TimedOutputAdapter.php b/src/Db/Adapter/TimedOutputAdapter.php index 8b5feff33..6dfe938e0 100644 --- a/src/Db/Adapter/TimedOutputAdapter.php +++ b/src/Db/Adapter/TimedOutputAdapter.php @@ -9,7 +9,7 @@ namespace Migrations\Db\Adapter; use BadMethodCallException; -use Cake\Console\ConsoleIo; +use Cake\Console\ConsoleIoInterface; use Migrations\Db\InsertMode; use Migrations\Db\Table\Column; use Migrations\Db\Table\ForeignKey; @@ -54,7 +54,7 @@ public function startCommandTimer(): callable public function writeCommand(string $command, array $args = []): void { $io = $this->getIo(); - if ($io instanceof ConsoleIo && $io->level() < ConsoleIo::VERBOSE) { + if ($io instanceof ConsoleIoInterface && $io->level() < ConsoleIoInterface::VERBOSE) { return; } if ($args !== []) { diff --git a/src/Db/Table/Column.php b/src/Db/Table/Column.php index f49ff559b..050a6b0d4 100644 --- a/src/Db/Table/Column.php +++ b/src/Db/Table/Column.php @@ -167,7 +167,7 @@ public function __construct( * @param string $name Name * @return $this */ - public function setName(string $name) + public function setName(string $name): static { $this->name = $name; @@ -194,7 +194,7 @@ public function getName(): string * @return $this * @deprecated 5.0 Use setLength() instead. */ - public function setLimit(?int $limit) + public function setLimit(?int $limit): static { $this->length = $limit; @@ -218,7 +218,7 @@ public function getLimit(): ?int * @param bool $null Null * @return $this */ - public function setNull(bool $null) + public function setNull(bool $null): static { $this->null = $null; @@ -251,7 +251,7 @@ public function isNull(): bool * @param mixed $default Default * @return $this */ - public function setDefault(mixed $default) + public function setDefault(mixed $default): static { $this->default = $default; @@ -274,7 +274,7 @@ public function getDefault(): mixed * @param string|null $generated Generated option * @return $this */ - public function setGenerated(?string $generated) + public function setGenerated(?string $generated): static { $this->generated = $generated; @@ -297,7 +297,7 @@ public function getGenerated(): ?string * @param bool $identity Identity * @return $this */ - public function setIdentity(bool $identity) + public function setIdentity(bool $identity): static { $this->identity = $identity; @@ -330,7 +330,7 @@ public function isIdentity(): bool * @param string $after After * @return $this */ - public function setAfter(string $after) + public function setAfter(string $after): static { $this->after = $after; @@ -353,7 +353,7 @@ public function getAfter(): ?string * @param string $update On Update function * @return $this */ - public function setUpdate(string $update) + public function setUpdate(string $update): static { $this->update = $update; @@ -379,7 +379,7 @@ public function getUpdate(): ?string * @param int|null $precision Number precision * @return $this */ - public function setPrecision(?int $precision) + public function setPrecision(?int $precision): static { $this->setLimit($precision); @@ -406,7 +406,7 @@ public function getPrecision(): ?int * @param int $increment Number increment * @return $this */ - public function setIncrement(int $increment) + public function setIncrement(int $increment): static { $this->increment = $increment; @@ -429,7 +429,7 @@ public function getIncrement(): ?int * @param int $seed Number seed * @return $this */ - public function setSeed(int $seed) + public function setSeed(int $seed): static { $this->seed = $seed; @@ -455,7 +455,7 @@ public function getSeed(): ?int * @param int|null $scale Number scale * @return $this */ - public function setScale(?int $scale) + public function setScale(?int $scale): static { $this->scale = $scale; @@ -485,7 +485,7 @@ public function getScale(): ?int * @param int $scale Number scale * @return $this */ - public function setPrecisionAndScale(int $precision, int $scale) + public function setPrecisionAndScale(int $precision, int $scale): static { $this->setLimit($precision); $this->scale = $scale; @@ -499,7 +499,7 @@ public function setPrecisionAndScale(int $precision, int $scale) * @param string|null $comment Comment * @return $this */ - public function setComment(?string $comment) + public function setComment(?string $comment): static { $this->comment = $comment; @@ -561,7 +561,7 @@ public function getUnsigned(): bool * @param bool $unsigned Unsigned * @return $this */ - public function setUnsigned(bool $unsigned) + public function setUnsigned(bool $unsigned): static { $this->unsigned = $unsigned; @@ -575,7 +575,7 @@ public function setUnsigned(bool $unsigned) * @return $this * @deprecated 5.0 Use setUnsigned() instead. */ - public function setSigned(bool $signed) + public function setSigned(bool $signed): static { $this->unsigned = !$signed; @@ -600,7 +600,7 @@ public function getSigned(): bool * @param bool $timezone Timezone * @return $this */ - public function setTimezone(bool $timezone) + public function setTimezone(bool $timezone): static { $this->timezone = $timezone; @@ -633,7 +633,7 @@ public function isTimezone(): bool * @param array $properties Properties * @return $this */ - public function setProperties(array $properties) + public function setProperties(array $properties): static { $this->properties = $properties; @@ -656,7 +656,7 @@ public function getProperties(): array * @param string[]|string $values Value(s) * @return $this */ - public function setValues(array|string $values) + public function setValues(array|string $values): static { if (!is_array($values)) { $values = preg_split('/,\s*/', $values) ?: []; @@ -683,7 +683,7 @@ public function getValues(): ?array * @return $this * @deprecated 5.0 Use setCollate() instead. */ - public function setCollation(string $collation) + public function setCollation(string $collation): static { $this->collate = $collation; @@ -707,7 +707,7 @@ public function getCollation(): ?string * @param string $encoding Encoding * @return $this */ - public function setEncoding(string $encoding) + public function setEncoding(string $encoding): static { $this->encoding = $encoding; @@ -730,7 +730,7 @@ public function getEncoding(): ?string * @param string $algorithm Algorithm * @return $this */ - public function setAlgorithm(string $algorithm) + public function setAlgorithm(string $algorithm): static { $this->algorithm = $algorithm; @@ -753,7 +753,7 @@ public function getAlgorithm(): ?string * @param string $lock Lock mode * @return $this */ - public function setLock(string $lock) + public function setLock(string $lock): static { $this->lock = $lock; @@ -778,7 +778,7 @@ public function getLock(): ?string * @param bool|null $fixed Fixed * @return $this */ - public function setFixed(?bool $fixed) + public function setFixed(?bool $fixed): static { $this->fixed = $fixed; @@ -851,7 +851,7 @@ protected function getAliasedOptions(): array * @throws \RuntimeException * @return $this */ - public function setOptions(array $options) + public function setOptions(array $options): static { $validOptions = $this->getValidOptions(); $aliasOptions = $this->getAliasedOptions(); diff --git a/src/Db/Table/ForeignKey.php b/src/Db/Table/ForeignKey.php index 1bd85981a..73592e5aa 100644 --- a/src/Db/Table/ForeignKey.php +++ b/src/Db/Table/ForeignKey.php @@ -112,7 +112,7 @@ public function getColumns(): array * @throws \RuntimeException * @return $this */ - public function setOptions(array $options) + public function setOptions(array $options): static { foreach ($options as $option => $value) { if (!in_array($option, static::$validOptions, true)) { @@ -187,7 +187,7 @@ protected function mapAction(string $action): string * @param string $deferrableMode Constraint * @return $this */ - public function setDeferrableMode(string $deferrableMode) + public function setDeferrableMode(string $deferrableMode): static { $this->deferrable = $this->normalizeDeferrable($deferrableMode); @@ -250,7 +250,7 @@ protected function mapDeferrable(?string $action): ?string * @return $this * @deprecated 5.0 Use setDelete() instead. */ - public function setOnDelete(string $onDelete) + public function setOnDelete(string $onDelete): static { $this->delete = $this->normalizeAction($onDelete); @@ -277,7 +277,7 @@ public function getOnDelete(): ?string * @return $this * @deprecated 5.0 Use setUpdate() instead. */ - public function setOnUpdate(string $onUpdate) + public function setOnUpdate(string $onUpdate): static { $this->update = $this->normalizeAction($onUpdate); diff --git a/src/Db/Table/Index.php b/src/Db/Table/Index.php index 507509af9..d1db5e0da 100644 --- a/src/Db/Table/Index.php +++ b/src/Db/Table/Index.php @@ -112,7 +112,7 @@ public function __construct( * @param string|string[] $columns Columns * @return $this */ - public function setColumns(string|array $columns) + public function setColumns(string|array $columns): static { $this->columns = is_string($columns) ? [$columns] : $columns; @@ -125,7 +125,7 @@ public function setColumns(string|array $columns) * @param string $type Type * @return $this */ - public function setType(string $type) + public function setType(string $type): static { $this->type = $type; @@ -152,7 +152,7 @@ public function getType(): string * @return $this * @deprecated 5.0 Use setLength() instead. */ - public function setLimit(int|array $limit) + public function setLimit(int|array $limit): static { $this->setLength($limit); @@ -178,7 +178,7 @@ public function getLimit(): int|array|null * @param bool $value The concurrent mode for an index. * @return $this */ - public function setConcurrently(bool $value) + public function setConcurrently(bool $value): static { $this->concurrent = $value; @@ -201,7 +201,7 @@ public function getConcurrently(): bool * @param string $algorithm Algorithm * @return $this */ - public function setAlgorithm(string $algorithm) + public function setAlgorithm(string $algorithm): static { $this->algorithm = $algorithm; @@ -224,7 +224,7 @@ public function getAlgorithm(): ?string * @param string $lock Lock mode * @return $this */ - public function setLock(string $lock) + public function setLock(string $lock): static { $this->lock = $lock; @@ -252,7 +252,7 @@ public function getLock(): ?string * @param array $opclass Map of column names to operator classes. * @return $this */ - public function setOpclass(array $opclass) + public function setOpclass(array $opclass): static { $this->opclass = $opclass; @@ -276,7 +276,7 @@ public function getOpclass(): ?array * @throws \RuntimeException * @return $this */ - public function setOptions(array $options) + public function setOptions(array $options): static { // Valid Options $validOptions = ['concurrently', 'type', 'unique', 'name', 'limit', 'order', 'include', 'where', 'algorithm', 'lock', 'opclass']; diff --git a/src/Middleware/PendingMigrationsMiddleware.php b/src/Middleware/PendingMigrationsMiddleware.php index 8c2ba5427..1b0956ea2 100644 --- a/src/Middleware/PendingMigrationsMiddleware.php +++ b/src/Middleware/PendingMigrationsMiddleware.php @@ -26,7 +26,7 @@ class PendingMigrationsMiddleware implements MiddlewareInterface protected const SKIP_QUERY_KEY = 'skip-middleware-check'; - protected array $_defaultConfig = [ + protected array $defaultConfig = [ 'paths' => [ 'migrations' => ROOT . DS . 'config' . DS . 'Migrations' . DS, ], @@ -86,7 +86,7 @@ protected function pendingMigrations(): array } /** @var array $plugins */ - $plugins = (array)$this->_config['plugins']; + $plugins = (array)$this->config['plugins']; foreach ($plugins as $plugin) { if (!$this->checkPluginMigrations($plugin)) { $pending[$plugin] = 'bin/cake migrations migrate -p ' . $plugin; @@ -101,15 +101,15 @@ protected function pendingMigrations(): array */ protected function checkAppMigrations(): bool { - if ($this->_config['app'] === false) { + if ($this->config['app'] === false) { return true; } - $connection = ConnectionManager::get($this->_config['environment']['connection']); + $connection = ConnectionManager::get($this->config['environment']['connection']); $database = $connection->config()['database']; - $this->_config['environment']['database'] = $database; + $this->config['environment']['database'] = $database; - $manager = $this->getManager($this->_config); + $manager = $this->getManager($this->config); $migrations = $manager->getMigrations(); foreach ($migrations as $migration) { @@ -126,9 +126,9 @@ protected function checkAppMigrations(): bool */ protected function checkPluginMigrations(string $plugin): bool { - $connection = ConnectionManager::get($this->_config['environment']['connection']); + $connection = ConnectionManager::get($this->config['environment']['connection']); $database = $connection->config()['database']; - $this->_config['environment']['database'] = $database; + $this->config['environment']['database'] = $database; $pluginPath = Plugin::path($plugin); if (!is_dir($pluginPath . 'config' . DS . 'Migrations' . DS)) { @@ -139,7 +139,7 @@ protected function checkPluginMigrations(string $plugin): bool 'paths' => [ 'migrations' => $pluginPath . 'config' . DS . 'Migrations' . DS, ], - ] + $this->_config; + ] + $this->config; $table = Util::tableName($plugin); diff --git a/src/Migration/Environment.php b/src/Migration/Environment.php index a4ddf961e..64a92c179 100644 --- a/src/Migration/Environment.php +++ b/src/Migration/Environment.php @@ -8,7 +8,7 @@ namespace Migrations\Migration; -use Cake\Console\ConsoleIo; +use Cake\Console\ConsoleIoInterface; use Cake\Datasource\ConnectionManager; use Migrations\Db\Adapter\AdapterFactory; use Migrations\Db\Adapter\AdapterInterface; @@ -27,7 +27,7 @@ class Environment */ protected array $options; - protected ?ConsoleIo $io = null; + protected ?ConsoleIoInterface $io = null; protected int $currentVersion; @@ -163,7 +163,7 @@ public function executeSeed(SeedInterface $seed): void * @param string $name Environment Name * @return $this */ - public function setName(string $name) + public function setName(string $name): static { $this->name = $name; @@ -186,7 +186,7 @@ public function getName(): string * @param array $options Environment Options * @return $this */ - public function setOptions(array $options) + public function setOptions(array $options): static { $this->options = $options; @@ -206,10 +206,10 @@ public function getOptions(): array /** * Sets the consoleio. * - * @param \Cake\Console\ConsoleIo $io ConsoleIo + * @param \Cake\Console\ConsoleIoInterface $io ConsoleIoInterface * @return $this */ - public function setIo(ConsoleIo $io) + public function setIo(ConsoleIoInterface $io): static { $this->io = $io; @@ -219,9 +219,9 @@ public function setIo(ConsoleIo $io) /** * Get the io instance * - * @return \Cake\Console\ConsoleIo $io The io instance to use + * @return \Cake\Console\ConsoleIoInterface $io The io instance to use */ - public function getIo(): ?ConsoleIo + public function getIo(): ?ConsoleIoInterface { return $this->io; } @@ -253,7 +253,7 @@ public function getVersionLog(): array * @param int $version Environment Version * @return $this */ - public function setCurrentVersion(int $version) + public function setCurrentVersion(int $version): static { $this->currentVersion = $version; @@ -288,7 +288,7 @@ public function getCurrentVersion(): int * @param \Migrations\Db\Adapter\AdapterInterface $adapter Database Adapter * @return $this */ - public function setAdapter(AdapterInterface $adapter) + public function setAdapter(AdapterInterface $adapter): static { $this->adapter = $adapter; @@ -333,7 +333,7 @@ public function getAdapter(): AdapterInterface } $io = $this->getIo(); - if ($io instanceof ConsoleIo) { + if ($io instanceof ConsoleIoInterface) { $adapter->setIo($io); } $this->setAdapter($adapter); @@ -347,7 +347,7 @@ public function getAdapter(): AdapterInterface * @param string $schemaTableName Schema Table Name * @return $this */ - public function setSchemaTableName(string $schemaTableName) + public function setSchemaTableName(string $schemaTableName): static { $this->schemaTableName = $schemaTableName; diff --git a/src/Migration/Manager.php b/src/Migration/Manager.php index 65ef382f4..9f6035ab7 100644 --- a/src/Migration/Manager.php +++ b/src/Migration/Manager.php @@ -9,7 +9,7 @@ namespace Migrations\Migration; use Cake\Console\Arguments; -use Cake\Console\ConsoleIo; +use Cake\Console\ConsoleIoInterface; use DateTime; use Exception; use InvalidArgumentException; @@ -30,7 +30,7 @@ class Manager protected ConfigInterface $config; - protected ConsoleIo $io; + protected ConsoleIoInterface $io; protected ?Environment $environment = null; @@ -48,9 +48,9 @@ class Manager /** * @param \Migrations\Config\ConfigInterface $config Configuration Object - * @param \Cake\Console\ConsoleIo $io Console input/output + * @param \Cake\Console\ConsoleIoInterface $io Console input/output */ - public function __construct(ConfigInterface $config, ConsoleIo $io) + public function __construct(ConfigInterface $config, ConsoleIoInterface $io) { $this->setConfig($config); $this->setIo($io); @@ -846,10 +846,10 @@ public function getEnvironment(): Environment /** * Set the io instance * - * @param \Cake\Console\ConsoleIo $io The io instance to use + * @param \Cake\Console\ConsoleIoInterface $io The io instance to use * @return $this */ - public function setIo(ConsoleIo $io) + public function setIo(ConsoleIoInterface $io): static { $this->io = $io; @@ -859,9 +859,9 @@ public function setIo(ConsoleIo $io) /** * Get the io instance * - * @return \Cake\Console\ConsoleIo $io The io instance to use + * @return \Cake\Console\ConsoleIoInterface $io The io instance to use */ - public function getIo(): ConsoleIo + public function getIo(): ConsoleIoInterface { return $this->io; } @@ -871,7 +871,7 @@ public function getIo(): ConsoleIo * * @return $this */ - public function setEnvironment(Environment $environment) + public function setEnvironment(Environment $environment): static { $this->environment = $environment; @@ -884,7 +884,7 @@ public function setEnvironment(Environment $environment) * @param \Psr\Container\ContainerInterface $container Container * @return $this */ - public function setContainer(ContainerInterface $container) + public function setContainer(ContainerInterface $container): static { $this->container = $container; @@ -897,7 +897,7 @@ public function setContainer(ContainerInterface $container) * @param \Migrations\MigrationInterface[] $migrations Migrations * @return $this */ - public function setMigrations(array $migrations) + public function setMigrations(array $migrations): static { $this->migrations = $migrations; @@ -1051,7 +1051,7 @@ protected function getMigrationFiles(): array * @param \Migrations\SeedInterface[] $seeds Seeders * @return $this */ - public function setSeeds(array $seeds) + public function setSeeds(array $seeds): static { $this->seeds = $seeds; @@ -1240,7 +1240,7 @@ protected function getSeedFiles(): array * @param \Migrations\Config\ConfigInterface $config Configuration Object * @return $this */ - public function setConfig(ConfigInterface $config) + public function setConfig(ConfigInterface $config): static { $this->config = $config; diff --git a/src/Migration/ManagerFactory.php b/src/Migration/ManagerFactory.php index d4636f6c7..d33790f60 100644 --- a/src/Migration/ManagerFactory.php +++ b/src/Migration/ManagerFactory.php @@ -13,7 +13,7 @@ */ namespace Migrations\Migration; -use Cake\Console\ConsoleIo; +use Cake\Console\ConsoleIoInterface; use Cake\Core\Configure; use Cake\Core\Plugin; use Cake\Datasource\ConnectionManager; @@ -136,12 +136,12 @@ public function createConfig(): ConfigInterface /** * Get the migration manager for the current CLI options and application configuration. * - * @param \Cake\Console\ConsoleIo $io The command io. + * @param \Cake\Console\ConsoleIoInterface $io The command io. * @param \Migrations\Config\ConfigInterface $config A config instance. Providing null will create a new Config * based on the factory constructor options. * @return \Migrations\Migration\Manager */ - public function createManager(ConsoleIo $io, ?ConfigInterface $config = null): Manager + public function createManager(ConsoleIoInterface $io, ?ConfigInterface $config = null): Manager { $config ??= $this->createConfig(); diff --git a/src/MigrationInterface.php b/src/MigrationInterface.php index 5d4415dfa..1372120bd 100644 --- a/src/MigrationInterface.php +++ b/src/MigrationInterface.php @@ -8,7 +8,7 @@ namespace Migrations; -use Cake\Console\ConsoleIo; +use Cake\Console\ConsoleIoInterface; use Cake\Database\Query; use Cake\Database\Query\DeleteQuery; use Cake\Database\Query\InsertQuery; @@ -63,17 +63,17 @@ public function getAdapter(): ?AdapterInterface; /** * Set the Console IO object to be used. * - * @param \Cake\Console\ConsoleIo $io The Io + * @param \Cake\Console\ConsoleIoInterface $io The Io * @return $this */ - public function setIo(ConsoleIo $io); + public function setIo(ConsoleIoInterface $io); /** * Get the Console IO object to be used. * - * @return \Cake\Console\ConsoleIo|null + * @return \Cake\Console\ConsoleIoInterface|null */ - public function getIo(): ?ConsoleIo; + public function getIo(): ?ConsoleIoInterface; /** * Gets the config. diff --git a/src/SeedInterface.php b/src/SeedInterface.php index e20b81bb1..02c83f678 100644 --- a/src/SeedInterface.php +++ b/src/SeedInterface.php @@ -8,7 +8,7 @@ namespace Migrations; -use Cake\Console\ConsoleIo; +use Cake\Console\ConsoleIoInterface; use Migrations\Config\ConfigInterface; use Migrations\Db\Adapter\AdapterInterface; use Migrations\Db\Table; @@ -60,17 +60,17 @@ public function getAdapter(): AdapterInterface; /** * Set the Console IO object to be used. * - * @param \Cake\Console\ConsoleIo $io The Io + * @param \Cake\Console\ConsoleIoInterface $io The Io * @return $this */ - public function setIo(ConsoleIo $io); + public function setIo(ConsoleIoInterface $io); /** * Get the Console IO object to be used. * - * @return \Cake\Console\ConsoleIo|null + * @return \Cake\Console\ConsoleIoInterface|null */ - public function getIo(): ?ConsoleIo; + public function getIo(): ?ConsoleIoInterface; /** * Gets the config. diff --git a/tests/TestCase/Command/BakeMigrationCommandTest.php b/tests/TestCase/Command/BakeMigrationCommandTest.php index aa1fd0f63..7104a4881 100644 --- a/tests/TestCase/Command/BakeMigrationCommandTest.php +++ b/tests/TestCase/Command/BakeMigrationCommandTest.php @@ -37,7 +37,7 @@ protected function setUp(): void { parent::setUp(); - $this->_compareBasePath = Plugin::path('Migrations') . 'tests' . DS . 'comparisons' . DS . 'Migration' . DS; + $this->compareBasePath = Plugin::path('Migrations') . 'tests' . DS . 'comparisons' . DS . 'Migration' . DS; } protected function tearDown(): void diff --git a/tests/TestCase/Command/BakeMigrationDiffCommandTest.php b/tests/TestCase/Command/BakeMigrationDiffCommandTest.php index 0309c92af..6349dd1ae 100644 --- a/tests/TestCase/Command/BakeMigrationDiffCommandTest.php +++ b/tests/TestCase/Command/BakeMigrationDiffCommandTest.php @@ -491,7 +491,7 @@ protected function runDiffBakingTest(string $scenario): void // against the last migrated version, so having an unmigrated file would fail unlink($destination); - $this->_compareBasePath = Plugin::path('Migrations') . 'tests' . DS . 'comparisons' . DS . 'Diff' . DS . lcfirst($scenario) . DS; + $this->compareBasePath = Plugin::path('Migrations') . 'tests' . DS . 'comparisons' . DS . 'Diff' . DS . lcfirst($scenario) . DS; $bakeName = $this->getBakeName('TheDiff' . $scenario); $targetFolder = 'MigrationsDiff' . $scenario; @@ -616,7 +616,7 @@ public function assertCorrectSnapshot($bakeName, string $result): void $dbenv = $this->getDbType(); } $bakeName = Inflector::underscore($bakeName); - if (file_exists($this->_compareBasePath . $dbenv . DS . $bakeName . '.php')) { + if (file_exists($this->compareBasePath . $dbenv . DS . $bakeName . '.php')) { $this->assertSameAsFile($dbenv . DS . $bakeName . '.php', $result); } else { $this->assertSameAsFile($bakeName . '.php', $result); diff --git a/tests/TestCase/Command/BakeMigrationSnapshotCommandTest.php b/tests/TestCase/Command/BakeMigrationSnapshotCommandTest.php index a703f7a5d..11286521d 100644 --- a/tests/TestCase/Command/BakeMigrationSnapshotCommandTest.php +++ b/tests/TestCase/Command/BakeMigrationSnapshotCommandTest.php @@ -57,7 +57,7 @@ protected function setUp(): void parent::setUp(); $this->loadPlugins(['SimpleSnapshot']); - $this->_compareBasePath = Plugin::path('Migrations') . 'tests' . DS . 'comparisons' . DS . 'Migration' . DS; + $this->compareBasePath = Plugin::path('Migrations') . 'tests' . DS . 'comparisons' . DS . 'Migration' . DS; $this->migrationPath = ROOT . DS . 'config' . DS . 'Migrations' . DS; $this->generatedFiles = []; @@ -335,12 +335,12 @@ public function getBakeName(string $name) public function assertSameAsFile(string $path, string $result): void { if (!file_exists($path)) { - $path = $this->_compareBasePath . $path; + $path = $this->compareBasePath . $path; } - $this->_updateComparisons ??= (bool)env('UPDATE_TEST_COMPARISON_FILES'); + $this->updateComparisons ??= (bool)env('UPDATE_TEST_COMPARISON_FILES'); - if ($this->_updateComparisons) { + if ($this->updateComparisons) { file_put_contents($path, $result); } @@ -368,7 +368,7 @@ public function assertCorrectSnapshot($bakeName, string $result): void { $dbenv = getenv('DB'); $bakeName = Inflector::underscore($bakeName); - if (file_exists($this->_compareBasePath . $dbenv . DS . $bakeName . '.php')) { + if (file_exists($this->compareBasePath . $dbenv . DS . $bakeName . '.php')) { $this->assertSameAsFile($dbenv . DS . $bakeName . '.php', $result); } else { $this->assertSameAsFile($bakeName . '.php', $result); diff --git a/tests/TestCase/Command/BakeSeedCommandTest.php b/tests/TestCase/Command/BakeSeedCommandTest.php index f28285ee6..5dd1f7ad9 100644 --- a/tests/TestCase/Command/BakeSeedCommandTest.php +++ b/tests/TestCase/Command/BakeSeedCommandTest.php @@ -49,7 +49,7 @@ class BakeSeedCommandTest extends TestCase protected function setUp(): void { parent::setUp(); - $this->_compareBasePath = Plugin::path('Migrations') . 'tests' . DS . 'comparisons' . DS . 'Seeds' . DS; + $this->compareBasePath = Plugin::path('Migrations') . 'tests' . DS . 'comparisons' . DS . 'Seeds' . DS; } /** diff --git a/tests/TestCase/Command/CompletionTest.php b/tests/TestCase/Command/CompletionTest.php index d61686dcb..b708371c2 100644 --- a/tests/TestCase/Command/CompletionTest.php +++ b/tests/TestCase/Command/CompletionTest.php @@ -56,7 +56,7 @@ public function testMigrationsSubcommands(): void 'dump mark_migrated migrate reset rollback status upgrade', ]; } - $actual = $this->_out->messages(); + $actual = $this->out->messages(); $this->assertEquals($expected, $actual); } @@ -69,8 +69,8 @@ public function testMigrationsSubcommands(): void public function testMigrationsOptionsMarkMigrated(): void { $this->exec('completion options migrations.migrations mark_migrated'); - $this->assertCount(1, $this->_out->messages()); - $output = $this->_out->messages()[0]; + $this->assertCount(1, $this->out->messages()); + $output = $this->out->messages()[0]; $expected = '--connection -c --exclude -x --help -h --only -o --plugin -p --quiet -q'; $expected .= ' --source -s --target -t --verbose -v'; $outputExplode = explode(' ', trim($output)); @@ -90,8 +90,8 @@ public function testMigrationsOptionsMarkMigrated(): void public function testMigrationsOptionsMigrate(): void { $this->exec('completion options migrations.migrations migrate'); - $this->assertCount(1, $this->_out->messages()); - $output = $this->_out->messages()[0]; + $this->assertCount(1, $this->out->messages()); + $output = $this->out->messages()[0]; $expected = '--connection -c --count -k --date -d --dry-run -x --fake --help -h --no-lock --plugin -p'; $expected .= ' --quiet -q --source -s --target -t --verbose -v'; $outputExplode = explode(' ', trim($output)); @@ -111,8 +111,8 @@ public function testMigrationsOptionsMigrate(): void public function testMigrationsOptionsRollback(): void { $this->exec('completion options migrations.migrations rollback'); - $this->assertCount(1, $this->_out->messages()); - $output = $this->_out->messages()[0]; + $this->assertCount(1, $this->out->messages()); + $output = $this->out->messages()[0]; $expected = '--connection -c --count -k --date -d --dry-run -x --fake --force -f --help -h --no-lock --plugin -p'; $expected .= ' --quiet -q --source -s --target -t --verbose -v'; $outputExplode = explode(' ', trim($output)); @@ -132,8 +132,8 @@ public function testMigrationsOptionsRollback(): void public function testMigrationsOptionsStatus(): void { $this->exec('completion options migrations.migrations status'); - $this->assertCount(1, $this->_out->messages()); - $output = $this->_out->messages()[0]; + $this->assertCount(1, $this->out->messages()); + $output = $this->out->messages()[0]; $expected = '--all --cleanup --connection -c --format -f --help -h --plugin -p --quiet -q --source -s --verbose -v'; $outputExplode = explode(' ', trim($output)); sort($outputExplode); diff --git a/tests/TestCase/Command/DumpCommandTest.php b/tests/TestCase/Command/DumpCommandTest.php index a666415c6..dfbad6f88 100644 --- a/tests/TestCase/Command/DumpCommandTest.php +++ b/tests/TestCase/Command/DumpCommandTest.php @@ -15,7 +15,7 @@ class DumpCommandTest extends TestCase { protected Connection $connection; - protected string $_compareBasePath; + protected string $compareBasePath; protected string $dumpFile; diff --git a/tests/TestCase/Command/ResetCommandTest.php b/tests/TestCase/Command/ResetCommandTest.php index 7ccd45a72..b5df3d2ad 100644 --- a/tests/TestCase/Command/ResetCommandTest.php +++ b/tests/TestCase/Command/ResetCommandTest.php @@ -8,7 +8,6 @@ use Cake\Event\EventInterface; use Cake\Event\EventManager; use Migrations\Test\TestCase\TestCase; -use ReflectionProperty; class ResetCommandTest extends TestCase { @@ -40,11 +39,10 @@ protected function tearDown(): void protected function resetOutput(): void { - if ($this->_out instanceof StubConsoleOutput) { - $property = new ReflectionProperty($this->_out, '_out'); - $property->setValue($this->_out, []); + if ($this->out instanceof StubConsoleOutput) { + $this->out->clear(); } - $this->_in = null; + $this->in = null; } public function testHelp(): void diff --git a/tests/TestCase/Command/RollbackCommandTest.php b/tests/TestCase/Command/RollbackCommandTest.php index e24fdc250..bdc9e5ddf 100644 --- a/tests/TestCase/Command/RollbackCommandTest.php +++ b/tests/TestCase/Command/RollbackCommandTest.php @@ -9,7 +9,6 @@ use Cake\Event\EventManager; use InvalidArgumentException; use Migrations\Test\TestCase\TestCase; -use ReflectionProperty; class RollbackCommandTest extends TestCase { @@ -33,9 +32,8 @@ protected function tearDown(): void protected function resetOutput(): void { - if ($this->_out instanceof StubConsoleOutput) { - $property = new ReflectionProperty($this->_out, '_out'); - $property->setValue($this->_out, []); + if ($this->out instanceof StubConsoleOutput) { + $this->out->clear(); } } @@ -80,7 +78,7 @@ public function testExecuteActuallyWorks(): void $this->exec('migrations status -c test -s MigrationsRollback --format json'); $this->assertExitSuccess(); - $output = $this->_out->messages(); + $output = $this->out->messages(); $parsed = json_decode($output[0], true); $this->assertEquals('down', $parsed[0]['status'], 'Migration status should be down'); } diff --git a/tests/TestCase/Command/SeedCommandTest.php b/tests/TestCase/Command/SeedCommandTest.php index e93984102..a33e9779f 100644 --- a/tests/TestCase/Command/SeedCommandTest.php +++ b/tests/TestCase/Command/SeedCommandTest.php @@ -34,7 +34,7 @@ protected function createTables(): void { $this->exec('migrations migrate -c test -s TestsMigrations --no-lock'); $this->assertExitSuccess(); - $this->_in = null; + $this->in = null; } public function testHelp(): void diff --git a/tests/TestCase/Command/StatusCommandTest.php b/tests/TestCase/Command/StatusCommandTest.php index 929b07071..7a609b922 100644 --- a/tests/TestCase/Command/StatusCommandTest.php +++ b/tests/TestCase/Command/StatusCommandTest.php @@ -43,8 +43,8 @@ public function testExecuteSimpleJson(): void $this->exec('migrations status -c test --format json'); $this->assertExitSuccess(); - assert($this->_out instanceof StubConsoleOutput); - $output = $this->_out->messages(); + assert($this->out instanceof StubConsoleOutput); + $output = $this->out->messages(); $parsed = json_decode($output[0], true); $this->assertTrue(is_array($parsed)); $this->assertCount(2, $parsed); @@ -157,8 +157,8 @@ public function testAllJsonOutput(): void $this->exec('migrations status -c test --all --format json'); $this->assertExitCode(StatusCommand::CODE_STATUS_DOWN); - assert($this->_out instanceof StubConsoleOutput); - $messages = $this->_out->messages(); + assert($this->out instanceof StubConsoleOutput); + $messages = $this->out->messages(); $jsonLine = end($messages); $parsed = json_decode((string)$jsonLine, true); $this->assertIsArray($parsed); diff --git a/tests/TestCase/Command/UpgradeCommandTest.php b/tests/TestCase/Command/UpgradeCommandTest.php index 3a3890229..d9204ff46 100644 --- a/tests/TestCase/Command/UpgradeCommandTest.php +++ b/tests/TestCase/Command/UpgradeCommandTest.php @@ -3,6 +3,7 @@ namespace Migrations\Test\TestCase\Command; +use Cake\Core\BasePlugin; use Cake\Core\Configure; use Cake\Datasource\ConnectionManager; use Exception; @@ -202,7 +203,7 @@ public function testExecuteWithSlashInPluginName(): void // Load a fake plugin with a slash in the name using loadPlugins // which properly integrates with the console application - $this->loadPlugins(['CakeDC/Users' => ['path' => TMP]]); + $this->loadPlugins([new BasePlugin(['name' => 'CakeDC/Users', 'path' => TMP])]); try { $this->exec('migrations upgrade -c test'); diff --git a/tests/TestCase/Db/Adapter/RecordingAdapterTest.php b/tests/TestCase/Db/Adapter/RecordingAdapterTest.php index 260979e9e..248712ff2 100644 --- a/tests/TestCase/Db/Adapter/RecordingAdapterTest.php +++ b/tests/TestCase/Db/Adapter/RecordingAdapterTest.php @@ -73,7 +73,7 @@ public function testRecordingAdapterCanInvertAddColumn(): void ->getAdapter() ->expects($this->any()) ->method('getColumnForType') - ->willReturnCallback(function (string $columnName, string $type, array $options) { + ->willReturnCallback(function (string $columnName, string $type, array $options): Column { return (new Column()) ->setName($columnName) ->setType($type) diff --git a/tests/TestCase/Db/Adapter/SqlserverAdapterSchemaTest.php b/tests/TestCase/Db/Adapter/SqlserverAdapterSchemaTest.php new file mode 100644 index 000000000..4ca2ba047 --- /dev/null +++ b/tests/TestCase/Db/Adapter/SqlserverAdapterSchemaTest.php @@ -0,0 +1,68 @@ +> + */ + public static function binaryTypesProvider(): array + { + return [ + 'fixed binary' => [TableSchema::TYPE_BINARY], + 'variable binary' => [TableSchema::TYPE_VARBINARY], + ]; + } + + /** + * Binary schema types retain the migration type and column metadata. + * + * @param string $type CakePHP's reflected column type. + * @return void + */ + #[DataProvider('binaryTypesProvider')] + public function testBinaryColumnReflection(string $type): void + { + $dialect = $this->createMock(SchemaDialect::class); + $dialect->expects($this->once()) + ->method('describeColumns') + ->with('assets') + ->willReturn([[ + 'name' => 'payload', + 'type' => $type, + 'null' => true, + 'length' => 64, + 'default' => null, + 'comment' => 'Binary payload', + ]]); + + $adapter = $this->getMockBuilder(SqlserverAdapter::class) + ->setConstructorArgs([[]]) + ->onlyMethods(['getSchemaDialect']) + ->getMock(); + $adapter->expects($this->once()) + ->method('getSchemaDialect') + ->willReturn($dialect); + + $columns = $adapter->getColumns('assets'); + + $this->assertCount(1, $columns); + $this->assertSame('payload', $columns[0]->getName()); + $this->assertSame(SqlserverAdapter::TYPE_BINARY, $columns[0]->getType()); + $this->assertSame(64, $columns[0]->getLimit()); + $this->assertTrue($columns[0]->isNull()); + $this->assertNull($columns[0]->getDefault()); + $this->assertSame('Binary payload', $columns[0]->getComment()); + } +} diff --git a/tests/TestCase/Migration/ManagerFactoryTest.php b/tests/TestCase/Migration/ManagerFactoryTest.php index 12bdd2dbf..af3b7d04b 100644 --- a/tests/TestCase/Migration/ManagerFactoryTest.php +++ b/tests/TestCase/Migration/ManagerFactoryTest.php @@ -4,6 +4,7 @@ namespace Migrations\Test\TestCase\Migration; use Cake\Console\ConsoleIo; +use Cake\Console\ConsoleIoInterface; use Cake\Console\TestSuite\StubConsoleInput; use Cake\Console\TestSuite\StubConsoleOutput; use Cake\Database\Connection; @@ -29,6 +30,22 @@ public function testConnection(): void $this->assertSame('test', $result->getConfig()->getConnection()); } + /** + * Command IO implementations can be passed through to migration adapters. + * + * @return void + */ + public function testConsoleIoInterface(): void + { + $io = $this->createMock(ConsoleIoInterface::class); + $factory = new ManagerFactory(['connection' => 'test']); + $manager = $factory->createManager($io); + + $this->assertSame($io, $manager->getIo()); + $this->assertSame($io, $manager->getEnvironment()->getIo()); + $this->assertSame($io, $manager->getEnvironment()->getAdapter()->getIo()); + } + public function testCreateConfigPluginAdapter(): void { $factory = new ManagerFactory([ diff --git a/tests/TestCase/Migration/ManagerTest.php b/tests/TestCase/Migration/ManagerTest.php index 8d88b5755..2628afa38 100644 --- a/tests/TestCase/Migration/ManagerTest.php +++ b/tests/TestCase/Migration/ManagerTest.php @@ -121,7 +121,7 @@ protected function getConfigWithPlugin(array $paths = []): array * @param array $paths The paths config to override. * @return \Migrations\Db\Adapter\AdapterInterface */ - protected function prepareEnvironment(array $paths = []): AdapterInterface + private function prepareEnvironment(array $paths = []): AdapterInterface { $configArray = $this->getConfigArray(); diff --git a/tests/comparisons/Diff/addRemove/schema-dump-test_comparisons_mysql.lock b/tests/comparisons/Diff/addRemove/schema-dump-test_comparisons_mysql.lock index 567467f793e68b75a3132c281cc280e623a70aef..92a7ea8a28c330db0df280d8bec37af1b2a66b46 100644 GIT binary patch delta 284 zcmbQlH;I3OBfFu2l@fy%!^8}0M$3&$+!%#S!Tj{p{M^)%qRNoUg4D@Vn6(6ot)MEC zGZKr6Q%fduGMO@3ZnkHNAzsTaW^sbrmGWnf)f3jpE}Gn)Va diff --git a/tests/comparisons/Diff/addRemove/schema-dump-test_comparisons_pgsql.lock b/tests/comparisons/Diff/addRemove/schema-dump-test_comparisons_pgsql.lock index 0fda7cc04045fab6cc891a2ead81ddbe8bb20d10..c5f543d80b0d19a89d8b0ef282919286bc77bdee 100644 GIT binary patch delta 297 zcmbQnJB@FGBfFu2l@fy%!^8}0M$3&$>=}hj!Tj{p{M^)%qRNoUg4D@(7_|h7t)MEC zGZKr6Q%fc@F_|)2Znj`@B3{c(W^q delta 176 zcmbQnH;s3KBfF)Q5`z{){N#UZVqC>mhK3OCL=S65^NlU`jFXdCl_v``88Vu0c4cyc zaIZ5P1G(HRc3>_~Z7o9I^n cpNFi-7^0{oHMbzYD6yzg$vVl(z`C{;0KT3tcK`qY diff --git a/tests/comparisons/Diff/decimalChange/schema-dump-test_comparisons_mysql.lock b/tests/comparisons/Diff/decimalChange/schema-dump-test_comparisons_mysql.lock index 499dc7d327b4a95715bb914d6a750b8d84be8230..292bb650619e07a285c67deb7b37b46f4a646780 100644 GIT binary patch delta 231 zcmeC;y2~}ehuzS?N{K;>VPc&%qvgh3j*LR4V19aPer{?>QDsPFLF(j*%sRrwR#276 z8Hq*3sU=F*ev{>yj2SIA2Q#_i(j|{YmvwC|Ty*kDW*0e#12XecQY%u6m8=u346Ld_ zN=(2GnXJpQ#uTC?zn~;DKMz@n5m-q{YHmS(QDRZ0l68`mfpxK!1;k6iicGb&03L)t A@&Et; delta 161 zcmcc1)x|ZzhuzXji9w4YezFy-B3H4Mp&^7jG1!{Xd}F^O zxjePC2!)fsGrK52HD%_dq*kOBD_JL68CX?=6q!N|k7QW`GdaJYBr`t`S&=bBQAuiU SL4HwUQKgb~l9hpVZ7l$5$}Cp^ diff --git a/tests/comparisons/Diff/default/schema-dump-test_comparisons_mysql.lock b/tests/comparisons/Diff/default/schema-dump-test_comparisons_mysql.lock index 9d56436ca2229477ac0d0b9eb70a113e273b0b84..5c1c96c12f8ac6916f425c7fd9c186ed765bb6b4 100644 GIT binary patch literal 9487 zcmeHNU2oeq6zy-(C}8l1P|JrMWDlv)_}+NfMolzvSJ8sKmV}<=t(%lq+%f zS={H6e~yy3bTWROM6Z5&l@@uu(l{(23(F9oG7@$2_CG|O+Y?a|zo-4!1u0srWOU|F zyXER}ZI`i0=}Io7p-s(^I?toC`{XrN8eK9u7j<4mXE#`TZw2R4FREp9rjj_Ojj>%- znbei49_hSYhStzxA++OP;3`j z&$)W=k8G}33R6n^nCCKqNSG&w)+2Fj1vt1Ils_j?SsA4lc$J#9@ELTO#$;Gncv z^ne87Fi~C2-_6+R@>!}{i;O|HOgg6B4QM!%d`P8P1No6qha&o5zkwgg2gr6G^mheq z;KfInn;-o@Qg$=6w!w> za4u}4%6yF2y%Td_)ZHQ$2e=~|iLgK4hqqHA#sI96WA$yDkG8iOReb?dnb+uq#>33# zk1!v2lU0|}%=Vaz5UO58A8dR(R^Vp9;*>U~eI^ImB{^d{YNk!5KlxgC0zkr1 zsGoj)@7?L@`rTF_4Da*RzjG$Y_?=69is>b&4TtiVv=3A|lMloT2<8fC9_B`JWQKmI!_I#f;}fol0YfrA}pL8DJ8Qhmuk7Jn*%gP1{{e?%JpO4DP)2nLy zXdXJUn{Q6LkaIN-KH+P#`}Tc9`H}l(mu6S^7WeJz?noH@c?XsQ5^jBDz7c|lzVOca9-K=-vk{QN4O6c?zZ{_~hBREl)7lU% c*FgY=g_SV=2EFb#=KB_l7i&1$Cgb_}UpyAQRR910 delta 663 zcmeD8+Uz{Rk=@cti9w4Ye)2mpF|J}OLqiC6qK7r3+2#guH^#{;SOq3aFc|~6K1?wn zuF&MOQrtYX#a8B4N~smesYL~o53;K>noV9WExOr<#TleVdh!caBcK*(HZOh(0y=4OwcxbL^F^d5y9z1*MIMMGP2MdS#sfCO6yn>>PQqr) za5L(}g5`}N5+$j*1^GpZMU_g{Nmd5dKwC|$lu8oQCkh%ULj$fPF)1fi$r>h83}V8a z<|2*~j59bvVS?;qh%;cW=a6<(fU-05Qc^2YfufeR`z zWUN)tT?jOxv^cd0)rogxP@K3%&J5_p$8zzANSUi(0u;KWfDl4;^>n2~g09{yrkux! M>}(0F&IU#-06eU{ZU6uP diff --git a/tests/comparisons/Diff/default/schema-dump-test_comparisons_pgsql.lock b/tests/comparisons/Diff/default/schema-dump-test_comparisons_pgsql.lock index 399d95af1126491bfa0031bb2a9d5e51ff082e77..6b5c22de400353212021f2cc6ecdbf90588ecd35 100644 GIT binary patch delta 1159 zcmbPa|HFBL<76gzp^3!?lP3xaZ@wd;%P3@OrNp4cke-^Kn_5y-8B$r0I(Z?RmO!zU zp#fMXIU}*CIJIOl6O$=elNXZ#@tS5bn}anyX4WBIlOC%XSW`KxA@Q1yvq5YUWGBHU ze^C>#P18j6iMQz^Cq$D47YUl$xFOEFz-@%fCVBKASF-lAuC0ZOPB!Gd%?62+$-;at zj24q4_%@3Ir6Dnxn4FwiTnVsJhD1VVzbaD{?G!?9B;HH~^qj~ceelun- zi1GOaC7Jno#Y)zRRt8qpAQu>c)s&>>7UUNt7F8-)Cs`R-7h73CgcFl;Qk5Xw#G;bS zjWsNv#073E>}zpC^ZkuW_Ty%Rqxl z64Qa+)t9gadv~S;8Q#^9vH+*UVku)>sRJ`Z9+ie@5|F{ENgJMcpt%?x=@4I+0CT%< kVgV>%j3EqLm=0c$qB-}&TI_iagetPathname(); - if (preg_match('/schema-dump-.*\.lock$/', $path) === 1) { + if (preg_match('/schema-dump-.*\.lock$/', (string) $path) === 1) { $files[] = $path; } } @@ -174,7 +174,7 @@ function fixUninitializedTypedProperties( fwrite( STDERR, "Cannot infer default for uninitialized typed property " . - "{$className}::\${$propertyName} in {$file}\n" + sprintf('%s::$%s in %s%s', $className, $propertyName, $file, PHP_EOL) ); exit(EXIT_ERROR); } diff --git a/tests/comparisons/Diff/simple/schema-dump-test_comparisons_mysql.lock b/tests/comparisons/Diff/simple/schema-dump-test_comparisons_mysql.lock index 88789db9ad01a8e93828da240126200a8c23cd09..056ae2bebd385268615913ce01d0bf40a2ce8a57 100644 GIT binary patch delta 500 zcmZ1?b60MHBfFu2l@fy%!^8}0M$3&$+!%#S!Tj{p{M^)%qRNoUg4D^5Tv`IfR#276 z8Hq*3sU?#+nM@fiH`_DC5U*tyvpJ*XWJh+<&Fn1B#B0lBH3QnTfYpn5Eu8E?n>IVL zM-Z=N2Zsqz%Uh0UTw3JOgFwmJ&$_l2E;_lKYdISvG$*TayD(Zz&f?xI3Y3O~Xkv15 zYH_h|YDq?Z%4A6%Q=mLBBqpcuOjE(C25!0uI6@|~@vecHzLPiD)CeqElA2qPUzAu> isbrmGWnf)wWdRXROv*`Bf^ZXyN-~pkQj3*I*V5T delta 233 zcmcaBw?t-wqq?P)5`z{)d`V(bPO6f1v6Y3DQesg_W^ztyF^Fqu2$7%YVa;g1vBiyX zvKy!JWGN;?M)S=+OfeAd4`yQ^SBE76!o9+31mv=_c|o`f*+H^b*`czvoCZMdI?iaY zEKhAM!jj1;+{@Xa7ETuAabYx{9LBSGvJx-Qw#gy9t09U_AugJ%%(n)v_$ptpgfY}7 UsksIDMTtd~O4dnM2G+H;09qqIiU0rr diff --git a/tests/comparisons/Diff/simple/schema-dump-test_comparisons_pgsql.lock b/tests/comparisons/Diff/simple/schema-dump-test_comparisons_pgsql.lock index 29007cb78993b806006d4a32ab53f421a0d9734a..de631af62948e0bb5bd56780bf76e0be98bedce2 100644 GIT binary patch delta 513 zcmaDWwM=$`BfFu2l@fy%!^8}0M$3&$>=}hj!Tj{p{M^)%qRNoUg4D?i*|Y?Tt)MEC zGZKr6Q%fc@F_|)2Znj`@B3{c(W^pD&%9Dke3>nQgyD~XJ zxYwDDfn07DI|z3ss}YcUhSeFujb{hRPG*P7DsmbCxj~$cU|F8pT7)H&-*GKxhgvv! zHn$6-`Q!)OnVPb|gqvggW&Wu8)V19aPer{?>QDsPFLF(iOj9T)=R#276 z8Hq*3sU=F*e%7_MaM8(POqy~KqcZbSQY%u6m8=u346Ld_N=(2;PL5|sbrmGWnf)wWdRXROv*`Bf^ZXyN-~pkKql7K0sv)qF<`(1^B^FgGStnT;Sl8A9 E0Jdf#Pyhe` diff --git a/tests/comparisons/Diff/withAutoIdIncompatibleSignedPrimaryKeys/schema-dump-test_comparisons_mysql.lock b/tests/comparisons/Diff/withAutoIdIncompatibleSignedPrimaryKeys/schema-dump-test_comparisons_mysql.lock index 67884e41e939e7f9ed4f26c27b5f370d485d3f5a..be1e3fbba40cff0f3b8384433da700ff4c371bd4 100644 GIT binary patch delta 182 zcmZo*U&cPck=@Y1N{K;>VPb|gqvggW&Wu8)V19aPer{?>QDsPFLF(iOj9T)=R#276 z8Hq*3sU=F*e%7_MaM8(POqy~KqcZbSQY%u6m8=u346Ld_N=(2;PL5|sbrmGWnf)wWdRXROv*`Bf^ZXyN-~pkKql7K0sv)qF<`(1^B^FgGStnT;Sl8A9 E0Jdf#Pyhe` diff --git a/tests/comparisons/Diff/withAutoIdIncompatibleUnsignedPrimaryKeys/schema-dump-test_comparisons_mysql.lock b/tests/comparisons/Diff/withAutoIdIncompatibleUnsignedPrimaryKeys/schema-dump-test_comparisons_mysql.lock index 9e291c6700f5276305d7f9e7dc60bd70d8c0c16c..b6cc0d718dd81aecd27405fc785df2c45dd95ae1 100644 GIT binary patch delta 182 zcmZo*U&cPck=@Y1N{K;>VPb|gqvggW&Wu8)V19aPer{?>QDsPFLF(iOj9T)=R#276 z8Hq*3sU=F*e%7_MaM8(POqy~KqcZbSQY%u6m8=u346Ld_N=(2;PL5|sbrmGWnf)wWdRXROv*`Bf^ZXyN-~pkKql7K0sv)qF<`(1^B^FgGStnT;Sl8A9 E0Jdf#Pyhe` diff --git a/tests/test_app/App/Command/CustomBakeMigrationDiffCommand.php b/tests/test_app/App/Command/CustomBakeMigrationDiffCommand.php index c52597f6c..b4dabde59 100644 --- a/tests/test_app/App/Command/CustomBakeMigrationDiffCommand.php +++ b/tests/test_app/App/Command/CustomBakeMigrationDiffCommand.php @@ -3,8 +3,6 @@ namespace TestApp\Command; -use Cake\Console\Arguments; -use Cake\Console\ConsoleIo; use Cake\Console\ConsoleOptionParser; use Cake\Core\Plugin; use Migrations\Command\BakeMigrationDiffCommand; @@ -30,36 +28,33 @@ protected function buildOptionParser(ConsoleOptionParser $parser): ConsoleOption ->addOption('comparison'); } - public function execute(Arguments $args, ConsoleIo $io): ?int + public function execute(): ?int { - $testTargetFolder = $args->getOption('test-target-folder'); + $testTargetFolder = $this->args->getOption('test-target-folder'); assert($testTargetFolder !== null); - $this->pathFragment = 'config' . DS . $testTargetFolder . DS; - return parent::execute($args, $io); + return parent::execute(); } - public function getPath(Arguments $args): string + public function getPath(): string { // Avoids having to use the `source` option, as it would be passed down to // other commands, causing a migration files lookup in the folder where // the new migration has been baked, causing an error as a class with the // same name will already exist from loading/applying the comparison diff. - $path = ROOT . DS . $this->pathFragment; if ($this->plugin) { - $path = $this->_pluginPath($this->plugin) . $this->pathFragment; + $path = $this->pluginPath($this->plugin) . $this->pathFragment; } return str_replace('/', DS, $path); } - protected function getDumpSchema(Arguments $args): array + protected function getDumpSchema(): array { - $comparison = $args->getOption('comparison'); + $comparison = $this->args->getOption('comparison'); assert($comparison !== null); - $diffConfigFolder = Plugin::path('Migrations') . 'tests' . DS . 'comparisons' . DS . 'Diff' . DS . $comparison . DS; $diffDumpPath = $diffConfigFolder . 'schema-dump-test_comparisons_' . env('DB') . '.lock'; From 194100bcb92495f93d53bea73c1eb87cadfa475a Mon Sep 17 00:00:00 2001 From: Jasper Smet Date: Wed, 7 Oct 2026 09:01:03 +0200 Subject: [PATCH 2/2] Apply CakePHP 6 code standards to existing migration classes --- src/Db/Action/AddCheckConstraint.php | 2 +- src/Db/Action/AddColumn.php | 2 +- src/Db/Action/AddForeignKey.php | 2 +- src/Db/Action/AddIndex.php | 2 +- src/Db/Action/ChangeColumn.php | 2 +- src/Db/Action/DropForeignKey.php | 2 +- src/Db/Action/DropIndex.php | 4 +- src/Db/Action/RemoveColumn.php | 2 +- src/Db/Action/RenameColumn.php | 2 +- src/Db/Adapter/AdapterFactory.php | 8 +-- src/Db/AlterInstructions.php | 2 +- src/Db/Expression.php | 2 +- src/Db/InsertMode.php | 1 + src/Db/Literal.php | 2 +- src/Db/Plan/Intent.php | 2 +- src/Db/Table.php | 80 +++++++++++----------- src/Db/Table/Partition.php | 2 +- src/Db/Table/TableMetadata.php | 6 +- src/Db/Table/Trigger.php | 10 +-- src/Db/Table/View.php | 8 +-- tests/TestCase/Command/SeedCommandTest.php | 8 +-- tests/TestCase/TestCase.php | 2 +- 22 files changed, 78 insertions(+), 75 deletions(-) diff --git a/src/Db/Action/AddCheckConstraint.php b/src/Db/Action/AddCheckConstraint.php index ca558208e..b6c05f70e 100644 --- a/src/Db/Action/AddCheckConstraint.php +++ b/src/Db/Action/AddCheckConstraint.php @@ -48,7 +48,7 @@ public static function build( $checkConstraint = new CheckConstraint($name, $expression); - return new AddCheckConstraint($table, $checkConstraint); + return new self($table, $checkConstraint); } /** diff --git a/src/Db/Action/AddColumn.php b/src/Db/Action/AddColumn.php index 5029d727b..88668b215 100644 --- a/src/Db/Action/AddColumn.php +++ b/src/Db/Action/AddColumn.php @@ -46,7 +46,7 @@ public static function build(TableMetadata $table, string $columnName, string $t $column->setType($type); $column->setOptions($options); // map options to column methods - return new AddColumn($table, $column); + return new self($table, $column); } /** diff --git a/src/Db/Action/AddForeignKey.php b/src/Db/Action/AddForeignKey.php index f7a97cabd..f16360092 100644 --- a/src/Db/Action/AddForeignKey.php +++ b/src/Db/Action/AddForeignKey.php @@ -72,7 +72,7 @@ public static function build( ); $fk->setOptions($options); - return new AddForeignKey($table, $fk); + return new self($table, $fk); } /** diff --git a/src/Db/Action/AddIndex.php b/src/Db/Action/AddIndex.php index 85d38a207..8f41d394e 100644 --- a/src/Db/Action/AddIndex.php +++ b/src/Db/Action/AddIndex.php @@ -51,7 +51,7 @@ public static function build(TableMetadata $table, string|array|Index $columns, $index = $columns; } - return new AddIndex($table, $index); + return new self($table, $index); } /** diff --git a/src/Db/Action/ChangeColumn.php b/src/Db/Action/ChangeColumn.php index a3770fb45..ff987750b 100644 --- a/src/Db/Action/ChangeColumn.php +++ b/src/Db/Action/ChangeColumn.php @@ -59,7 +59,7 @@ public static function build(TableMetadata $table, string $columnName, string $t $column->setType($type); $column->setOptions($options); // map options to column methods - return new ChangeColumn($table, $columnName, $column); + return new self($table, $columnName, $column); } /** diff --git a/src/Db/Action/DropForeignKey.php b/src/Db/Action/DropForeignKey.php index 5e9cfde9d..20aa92b9c 100644 --- a/src/Db/Action/DropForeignKey.php +++ b/src/Db/Action/DropForeignKey.php @@ -52,7 +52,7 @@ public static function build(TableMetadata $table, string|array $columns, ?strin $foreignKey->setName($constraint); } - return new DropForeignKey($table, $foreignKey); + return new self($table, $foreignKey); } /** diff --git a/src/Db/Action/DropIndex.php b/src/Db/Action/DropIndex.php index 9299dd36d..0dacadefd 100644 --- a/src/Db/Action/DropIndex.php +++ b/src/Db/Action/DropIndex.php @@ -43,7 +43,7 @@ public static function build(TableMetadata $table, array $columns = []): self $index = new Index(); $index->setColumns($columns); - return new DropIndex($table, $index); + return new self($table, $index); } /** @@ -59,7 +59,7 @@ public static function buildFromName(TableMetadata $table, string $name): self $index = new Index(); $index->setName($name); - return new DropIndex($table, $index); + return new self($table, $index); } /** diff --git a/src/Db/Action/RemoveColumn.php b/src/Db/Action/RemoveColumn.php index a73c5512e..44badc890 100644 --- a/src/Db/Action/RemoveColumn.php +++ b/src/Db/Action/RemoveColumn.php @@ -43,7 +43,7 @@ public static function build(TableMetadata $table, string $columnName): self $column = new Column(); $column->setName($columnName); - return new RemoveColumn($table, $column); + return new self($table, $column); } /** diff --git a/src/Db/Action/RenameColumn.php b/src/Db/Action/RenameColumn.php index 1092a5f7d..da3f5424c 100644 --- a/src/Db/Action/RenameColumn.php +++ b/src/Db/Action/RenameColumn.php @@ -51,7 +51,7 @@ public static function build(TableMetadata $table, string $columnName, string $n $column = new Column(); $column->setName($columnName); - return new RenameColumn($table, $column, $newName); + return new self($table, $column, $newName); } /** diff --git a/src/Db/Adapter/AdapterFactory.php b/src/Db/Adapter/AdapterFactory.php index 43c5e573e..a4a81f136 100644 --- a/src/Db/Adapter/AdapterFactory.php +++ b/src/Db/Adapter/AdapterFactory.php @@ -21,7 +21,7 @@ class AdapterFactory /** * @var static|null */ - protected static ?AdapterFactory $instance = null; + protected static ?self $instance = null; /** * Constructor. @@ -37,7 +37,7 @@ final public function __construct() */ public static function instance(): static { - if (!static::$instance instanceof AdapterFactory) { + if (!static::$instance instanceof self) { static::$instance = new static(); } @@ -76,7 +76,7 @@ public static function instance(): static * @throws \RuntimeException * @return $this */ - public function registerAdapter(string $name, Closure|string $class) + public function registerAdapter(string $name, Closure|string $class): static { if ( !$class instanceof Closure && !is_subclass_of($class, AdapterInterface::class) @@ -122,7 +122,7 @@ public function getAdapter(string $name, array $options): AdapterInterface * @throws \RuntimeException * @return $this */ - public function registerWrapper(string $name, string $class) + public function registerWrapper(string $name, string $class): static { if (!is_subclass_of($class, WrapperInterface::class)) { throw new RuntimeException(sprintf( diff --git a/src/Db/AlterInstructions.php b/src/Db/AlterInstructions.php index 39a20d1fa..facf5ac1a 100644 --- a/src/Db/AlterInstructions.php +++ b/src/Db/AlterInstructions.php @@ -102,7 +102,7 @@ public function getPostSteps(): array * @throws \InvalidArgumentException When algorithm or lock specifications conflict * @return void */ - public function merge(AlterInstructions $other): void + public function merge(self $other): void { $this->alterParts = array_merge($this->alterParts, $other->getAlterParts()); $this->postSteps = array_merge($this->postSteps, $other->getPostSteps()); diff --git a/src/Db/Expression.php b/src/Db/Expression.php index 10b6dc5d2..24429d509 100644 --- a/src/Db/Expression.php +++ b/src/Db/Expression.php @@ -37,7 +37,7 @@ public function __toString(): string * @param string $value The expression * @return self */ - public static function from(string $value): Expression + public static function from(string $value): self { return new self($value); } diff --git a/src/Db/InsertMode.php b/src/Db/InsertMode.php index e04b707c1..c460a41eb 100644 --- a/src/Db/InsertMode.php +++ b/src/Db/InsertMode.php @@ -13,6 +13,7 @@ * * Defines different insertion strategies for handling duplicate key conflicts. */ +// phpcs:ignore CakePHP.NamingConventions.ValidEnumName.InvalidEnumName -- Preserve the public enum name used by migration adapters. enum InsertMode: string { /** diff --git a/src/Db/Literal.php b/src/Db/Literal.php index 843ad5645..75862dcf2 100644 --- a/src/Db/Literal.php +++ b/src/Db/Literal.php @@ -41,7 +41,7 @@ public function __toString(): string * @param string $value The literal's value * @return self */ - public static function from(string $value): Literal + public static function from(string $value): self { return new self($value); } diff --git a/src/Db/Plan/Intent.php b/src/Db/Plan/Intent.php index 1003abd78..21621338b 100644 --- a/src/Db/Plan/Intent.php +++ b/src/Db/Plan/Intent.php @@ -49,7 +49,7 @@ public function getActions(): array * @param \Migrations\Db\Plan\Intent $another The other intent to merge in * @return void */ - public function merge(Intent $another): void + public function merge(self $another): void { $this->actions = array_merge($this->actions, $another->getActions()); } diff --git a/src/Db/Table.php b/src/Db/Table.php index 7f4768ede..4c97fbff2 100644 --- a/src/Db/Table.php +++ b/src/Db/Table.php @@ -44,6 +44,8 @@ use Migrations\Db\Table\Partition; use Migrations\Db\Table\PartitionDefinition; use Migrations\Db\Table\TableMetadata; +use Migrations\Db\Table\Trigger; +use Migrations\Db\Table\View; use RuntimeException; /** @@ -145,7 +147,7 @@ public function getTable(): TableMetadata * @param \Migrations\Db\Adapter\AdapterInterface $adapter Database Adapter * @return $this */ - public function setAdapter(AdapterInterface $adapter) + public function setAdapter(AdapterInterface $adapter): static { $this->adapter = $adapter; @@ -196,7 +198,7 @@ public function exists(): bool * * @return $this */ - public function drop() + public function drop(): static { $this->actions->addAction(new DropTable($this->table)); @@ -209,7 +211,7 @@ public function drop() * @param string $newTableName New Table Name * @return $this */ - public function rename(string $newTableName) + public function rename(string $newTableName): static { $this->actions->addAction(new RenameTable($this->table, $newTableName)); @@ -222,7 +224,7 @@ public function rename(string $newTableName) * @param string|string[]|null $columns Column name(s) to belong to the primary key, or null to drop the key * @return $this */ - public function changePrimaryKey(string|array|null $columns) + public function changePrimaryKey(string|array|null $columns): static { $this->actions->addAction(new ChangePrimaryKey($this->table, $columns)); @@ -247,7 +249,7 @@ public function hasPrimaryKey(string|array $columns, ?string $constraint = null) * @param string|null $comment New comment string, or null to drop the comment * @return $this */ - public function changeComment(?string $comment) + public function changeComment(?string $comment): static { $this->actions->addAction(new ChangeComment($this->table, $comment)); @@ -288,7 +290,7 @@ function (Column $column) use ($name): bool { * @param array $data Data * @return $this */ - public function setData(array $data) + public function setData(array $data): static { $this->data = $data; @@ -332,7 +334,7 @@ public function reset(): void * @param string|string[] $columns Table Column(s) * @return $this */ - public function addPrimaryKey(string|array $columns) + public function addPrimaryKey(string|array $columns): static { $this->primaryKey = $columns; @@ -353,7 +355,7 @@ public function addPrimaryKey(string|array $columns) * @throws \InvalidArgumentException * @return $this */ - public function addColumn(string|Column $columnName, ?string $type = null, array $options = []) + public function addColumn(string|Column $columnName, ?string $type = null, array $options = []): static { if ($columnName instanceof Column) { $action = new AddColumn($this->table, $columnName); @@ -384,7 +386,7 @@ public function addColumn(string|Column $columnName, ?string $type = null, array * @param string $columnName Column Name * @return $this */ - public function removeColumn(string $columnName) + public function removeColumn(string $columnName): static { $action = RemoveColumn::build($this->table, $columnName); $this->actions->addAction($action); @@ -399,7 +401,7 @@ public function removeColumn(string $columnName) * @param string $newName New Column Name * @return $this */ - public function renameColumn(string $oldName, string $newName) + public function renameColumn(string $oldName, string $newName): static { $action = RenameColumn::build($this->table, $oldName, $newName); $this->actions->addAction($action); @@ -419,7 +421,7 @@ public function renameColumn(string $oldName, string $newName) * @param array $options Options * @return $this */ - public function updateColumn(string $columnName, string|Column|null $newColumnType, array $options = []) + public function updateColumn(string $columnName, string|Column|null $newColumnType, array $options = []): static { if (!($newColumnType instanceof Column)) { $options['preserveUnspecified'] = true; @@ -439,7 +441,7 @@ public function updateColumn(string $columnName, string|Column|null $newColumnTy * @param array $options Options * @return $this */ - public function changeColumn(string $columnName, string|Column|null $newColumnType, array $options = []) + public function changeColumn(string $columnName, string|Column|null $newColumnType, array $options = []): static { if ($newColumnType instanceof Column) { if ($options) { @@ -506,7 +508,7 @@ public function hasColumn(string $columnName): bool * @param array $options Index Options * @return $this */ - public function addIndex(string|array|Index $columns, array $options = []) + public function addIndex(string|array|Index $columns, array $options = []): static { $action = AddIndex::build($this->table, $columns, $options); $this->actions->addAction($action); @@ -520,7 +522,7 @@ public function addIndex(string|array|Index $columns, array $options = []) * @param string|string[] $columns Columns * @return $this */ - public function removeIndex(string|array $columns) + public function removeIndex(string|array $columns): static { $action = DropIndex::build($this->table, is_string($columns) ? [$columns] : $columns); $this->actions->addAction($action); @@ -534,7 +536,7 @@ public function removeIndex(string|array $columns) * @param string $name Index name * @return $this */ - public function removeIndexByName(string $name) + public function removeIndexByName(string $name): static { $action = DropIndex::buildFromName($this->table, $name); $this->actions->addAction($action); @@ -576,7 +578,7 @@ public function hasIndexByName(string $indexName): bool * @param array $options Options * @return $this */ - public function addForeignKey(string|array|ForeignKey $columns, string|TableMetadata|null $referencedTable = null, string|array $referencedColumns = ['id'], array $options = []) + public function addForeignKey(string|array|ForeignKey $columns, string|TableMetadata|null $referencedTable = null, string|array $referencedColumns = ['id'], array $options = []): static { if ($columns instanceof ForeignKey) { $action = new AddForeignKey($this->table, $columns); @@ -598,7 +600,7 @@ public function addForeignKey(string|array|ForeignKey $columns, string|TableMeta * @param string|null $constraint Constraint names * @return $this */ - public function dropForeignKey(string|array $columns, ?string $constraint = null) + public function dropForeignKey(string|array $columns, ?string $constraint = null): static { $action = DropForeignKey::build($this->table, $columns, $constraint); $this->actions->addAction($action); @@ -625,7 +627,7 @@ public function hasForeignKey(string|array $columns, ?string $constraint = null) * @param array $options Options for the check constraint (e.g., 'name') * @return $this */ - public function addCheckConstraint(string|CheckConstraint $expression, array $options = []) + public function addCheckConstraint(string|CheckConstraint $expression, array $options = []): static { if ($expression instanceof CheckConstraint) { $action = new AddCheckConstraint($this->table, $expression); @@ -643,7 +645,7 @@ public function addCheckConstraint(string|CheckConstraint $expression, array $op * @param string $constraintName The name of the check constraint to drop * @return $this */ - public function dropCheckConstraint(string $constraintName) + public function dropCheckConstraint(string $constraintName): static { $action = new DropCheckConstraint($this->table, $constraintName); $this->actions->addAction($action); @@ -670,7 +672,7 @@ public function hasCheckConstraint(string $constraintName): bool * @param array $options Partition options (count for HASH/KEY) * @return $this */ - public function partitionBy(string $type, string|array|Literal $columns, array $options = []) + public function partitionBy(string $type, string|array|Literal $columns, array $options = []): static { $partition = new Partition($type, $columns, [], $options['count'] ?? null, $options); $this->table->setPartition($partition); @@ -686,7 +688,7 @@ public function partitionBy(string $type, string|array|Literal $columns, array $ * @param array $options Additional options (tablespace, table for PG) * @return $this */ - public function addPartition(string $name, mixed $value = null, array $options = []) + public function addPartition(string $name, mixed $value = null, array $options = []): static { $partition = $this->table->getPartition(); if (!$partition instanceof Partition) { @@ -711,7 +713,7 @@ public function addPartition(string $name, mixed $value = null, array $options = * @param string $name Partition name * @return $this */ - public function dropPartition(string $name) + public function dropPartition(string $name): static { $this->actions->addAction(new DropPartition($this->table, $name)); @@ -726,7 +728,7 @@ public function dropPartition(string $name) * @param array $options Additional options * @return $this */ - public function addPartitionToExisting(string $name, mixed $value, array $options = []) + public function addPartitionToExisting(string $name, mixed $value, array $options = []): static { $definition = new PartitionDefinition( $name, @@ -748,7 +750,7 @@ public function addPartitionToExisting(string $name, mixed $value, array $option * @param bool $withTimezone Whether to set the timezone option on the added columns * @return $this */ - public function addTimestamps(string|false|null $createdAt = 'created', string|false|null $updatedAt = 'updated', bool $withTimezone = false) + public function addTimestamps(string|false|null $createdAt = 'created', string|false|null $updatedAt = 'updated', bool $withTimezone = false): static { $createdAt ??= 'created'; $updatedAt ??= 'updated'; @@ -790,7 +792,7 @@ public function addTimestamps(string|false|null $createdAt = 'created', string|f * @param string|false|null $updatedAt Alternate name for the updated_at column * @return $this */ - public function addTimestampsWithTimezone(string|false|null $createdAt = null, string|false|null $updatedAt = null) + public function addTimestampsWithTimezone(string|false|null $createdAt = null, string|false|null $updatedAt = null): static { $this->addTimestamps($createdAt, $updatedAt, true); @@ -808,7 +810,7 @@ public function addTimestampsWithTimezone(string|false|null $createdAt = null, s * or array("col1" => "value1", "col2" => "anotherValue1") * @return $this */ - public function insert(array $data) + public function insert(array $data): static { // handle array of array situations $keys = array_keys($data); @@ -836,7 +838,7 @@ public function insert(array $data) * @param array $data array of data in the same format as insert() * @return $this */ - public function insertOrSkip(array $data) + public function insertOrSkip(array $data): static { $this->insertMode = InsertMode::IGNORE; @@ -877,7 +879,7 @@ public function insertOrSkip(array $data) * @return $this * @throws \RuntimeException When using PostgreSQL or SQLite without specifying conflictColumns */ - public function insertOrUpdate(array $data, array $updateColumns, array $conflictColumns) + public function insertOrUpdate(array $data, array $updateColumns, array $conflictColumns): static { $this->insertMode = InsertMode::UPSERT; $this->upsertUpdateColumns = $updateColumns; @@ -1064,16 +1066,16 @@ public function save(): void * @param array $options View options * @return $this */ - public function createView(string $viewName, string $definition, array $options = []) + public function createView(string $viewName, string $definition, array $options = []): static { - $view = new Table\View( + $view = new View( $viewName, $definition, $options['replace'] ?? false, $options['materialized'] ?? false, ); - $action = new Action\CreateView($this->table, $view); + $action = new CreateView($this->table, $view); $this->actions->addAction($action); return $this; @@ -1086,9 +1088,9 @@ public function createView(string $viewName, string $definition, array $options * @param array $options View options * @return $this */ - public function dropView(string $viewName, array $options = []) + public function dropView(string $viewName, array $options = []): static { - $action = new Action\DropView( + $action = new DropView( $this->table, $viewName, $options['materialized'] ?? false, @@ -1107,17 +1109,17 @@ public function dropView(string $viewName, array $options = []) * @param array $options Trigger options * @return $this */ - public function createTrigger(string $triggerName, string|array $event, string $definition, array $options = []) + public function createTrigger(string $triggerName, string|array $event, string $definition, array $options = []): static { - $trigger = new Table\Trigger( + $trigger = new Trigger( $triggerName, - $options['timing'] ?? Table\Trigger::BEFORE, + $options['timing'] ?? Trigger::BEFORE, $event, $definition, $options['forEach'] ?? true, ); - $action = new Action\CreateTrigger($this->table, $trigger); + $action = new CreateTrigger($this->table, $trigger); $this->actions->addAction($action); return $this; @@ -1129,9 +1131,9 @@ public function createTrigger(string $triggerName, string|array $event, string $ * @param string $triggerName Trigger name * @return $this */ - public function dropTrigger(string $triggerName) + public function dropTrigger(string $triggerName): static { - $action = new Action\DropTrigger($this->table, $triggerName); + $action = new DropTrigger($this->table, $triggerName); $this->actions->addAction($action); return $this; diff --git a/src/Db/Table/Partition.php b/src/Db/Table/Partition.php index dffd7410a..3f9808ddc 100644 --- a/src/Db/Table/Partition.php +++ b/src/Db/Table/Partition.php @@ -107,7 +107,7 @@ public function getOptions(): array * @param \Migrations\Db\Table\PartitionDefinition $definition The partition definition * @return $this */ - public function addDefinition(PartitionDefinition $definition) + public function addDefinition(PartitionDefinition $definition): static { $this->definitions[] = $definition; diff --git a/src/Db/Table/TableMetadata.php b/src/Db/Table/TableMetadata.php index 3fc5b4a45..3f9e07a8c 100644 --- a/src/Db/Table/TableMetadata.php +++ b/src/Db/Table/TableMetadata.php @@ -45,7 +45,7 @@ public function __construct(string $name, array $options = []) * @param string $name The name of the table * @return $this */ - public function setName(string $name) + public function setName(string $name): static { $this->name = $name; @@ -78,7 +78,7 @@ public function getOptions(): array * @param array $options The options for the table creation * @return $this */ - public function setOptions(array $options) + public function setOptions(array $options): static { $this->options = $options; @@ -101,7 +101,7 @@ public function getPartition(): ?Partition * @param \Migrations\Db\Table\Partition|null $partition The partition configuration * @return $this */ - public function setPartition(?Partition $partition) + public function setPartition(?Partition $partition): static { $this->partition = $partition; diff --git a/src/Db/Table/Trigger.php b/src/Db/Table/Trigger.php index a4e6286cd..a4664018e 100644 --- a/src/Db/Table/Trigger.php +++ b/src/Db/Table/Trigger.php @@ -72,7 +72,7 @@ public function __construct( * @param string $name Name * @return $this */ - public function setName(string $name) + public function setName(string $name): static { $this->name = $name; @@ -95,7 +95,7 @@ public function getName(): string * @param string $timing Timing * @return $this */ - public function setTiming(string $timing) + public function setTiming(string $timing): static { $this->timing = $timing; @@ -118,7 +118,7 @@ public function getTiming(): string * @param string|array $event Event(s) * @return $this */ - public function setEvent(string|array $event) + public function setEvent(string|array $event): static { $this->event = $event; @@ -141,7 +141,7 @@ public function getEvent(): string|array * @param string $definition Definition * @return $this */ - public function setDefinition(string $definition) + public function setDefinition(string $definition): static { $this->definition = $definition; @@ -164,7 +164,7 @@ public function getDefinition(): string * @param bool $forEach For each row flag * @return $this */ - public function setForEach(bool $forEach) + public function setForEach(bool $forEach): static { $this->forEach = $forEach; diff --git a/src/Db/Table/View.php b/src/Db/Table/View.php index ac45da392..389028fba 100644 --- a/src/Db/Table/View.php +++ b/src/Db/Table/View.php @@ -40,7 +40,7 @@ public function __construct( * @param string $name Name * @return $this */ - public function setName(string $name) + public function setName(string $name): static { $this->name = $name; @@ -63,7 +63,7 @@ public function getName(): string * @param string $definition Definition * @return $this */ - public function setDefinition(string $definition) + public function setDefinition(string $definition): static { $this->definition = $definition; @@ -86,7 +86,7 @@ public function getDefinition(): string * @param bool $replace Replace flag * @return $this */ - public function setReplace(bool $replace) + public function setReplace(bool $replace): static { $this->replace = $replace; @@ -109,7 +109,7 @@ public function getReplace(): bool * @param bool $materialized Materialized flag * @return $this */ - public function setMaterialized(bool $materialized) + public function setMaterialized(bool $materialized): static { $this->materialized = $materialized; diff --git a/tests/TestCase/Command/SeedCommandTest.php b/tests/TestCase/Command/SeedCommandTest.php index a33e9779f..33de351cc 100644 --- a/tests/TestCase/Command/SeedCommandTest.php +++ b/tests/TestCase/Command/SeedCommandTest.php @@ -499,7 +499,7 @@ public function testSeedStatusCommand(): void public function testSeederPluginIsTrackedWithPluginName(): void { - $this->_loadTestPlugin('TestBlog'); + $this->loadTestPlugin('TestBlog'); $this->createTables(); $this->exec('seeds run -c test -p TestBlog --source CallSeeds PluginLettersSeed'); @@ -520,7 +520,7 @@ public function testSeederPluginIsTrackedWithPluginName(): void public function testSeederPluginLegacyLogEntryIsNotRunAgain(): void { - $this->_loadTestPlugin('TestBlog'); + $this->loadTestPlugin('TestBlog'); $this->createTables(); /** @var \Cake\Database\Connection $connection */ @@ -557,7 +557,7 @@ public function testSeederPluginLegacyLogEntryIsNotRunAgain(): void public function testSeedStatusCommandWithPlugin(): void { - $this->_loadTestPlugin('TestBlog'); + $this->loadTestPlugin('TestBlog'); $this->createTables(); $this->exec('seeds run -c test -p TestBlog --source CallSeeds PluginLettersSeed'); @@ -573,7 +573,7 @@ public function testSeedStatusCommandWithPlugin(): void public function testSeedResetCommandWithPlugin(): void { - $this->_loadTestPlugin('TestBlog'); + $this->loadTestPlugin('TestBlog'); $this->createTables(); $this->exec('seeds run -c test -p TestBlog --source CallSeeds PluginLettersSeed'); diff --git a/tests/TestCase/TestCase.php b/tests/TestCase/TestCase.php index e9734f79c..50a6e240a 100644 --- a/tests/TestCase/TestCase.php +++ b/tests/TestCase/TestCase.php @@ -72,7 +72,7 @@ protected function tearDown(): void * @param string $name plugin name to load * @return void */ - protected function _loadTestPlugin(string $name) + protected function loadTestPlugin(string $name) { $root = dirname(__FILE__, 2) . DS; $path = $root . 'test_app' . DS . 'Plugin' . DS . $name . DS;